-
Notifications
You must be signed in to change notification settings - Fork 1
/
gplus_event.py
248 lines (201 loc) · 8.32 KB
/
gplus_event.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
"""
Copyright 2013 Kendrick Ledet
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
from splinter import Browser
from dateutil import parser as dtparser
import atexit
import argparse
import json
def load_config():
with open('config.json', 'r') as config:
return json.loads(config.read())
def cli_parse():
'''Parse command-line arguments'''
options = {'title': None, 'desc': None, 'date': None,
'time': None, 'id': None}
parser = argparse.ArgumentParser()
parser.add_argument("action", help='''use "create" to create a new event\n
"update" to update an event\n"details" to get event info''') # noqa
parser.add_argument("--title", help="event title")
parser.add_argument("--date", help="event date")
parser.add_argument("--id", help="event id")
parser.add_argument("--desc", help="event description")
parser.add_argument("--filedesc", help="path to txt file w/ event description", # noqa
type=argparse.FileType('r'))
parser.add_argument("--otp", help="2-step verification code")
parser.add_argument("--show", help="1 to display the browser, 0 for invisible virtual display", # noqa
default=0, type=int)
try:
args = parser.parse_args()
except:
parser.print_help()
exit(1)
disp = None
if not args.show: # set up invisible virtual display
from pyvirtualdisplay.smartdisplay import SmartDisplay
try:
disp = SmartDisplay(visible=0, bgcolor='black').start()
atexit.register(disp.stop)
except:
if disp:
disp.stop()
raise
if args.title:
options['title'] = args.title
if args.desc:
options['desc'] = args.desc
elif args.filedesc:
options['desc'] = args.filedesc.read()
if args.date:
options['date'] = dtparser.parse(args.date).strftime('%Y-%m-%d')
options['time'] = dtparser.parse(args.date).strftime('%I:%M %p')
if args.id:
options['id'] = args.id
if args.otp:
options['otp'] = args.otp
options['action'] = args.action
return options
class GPlusEventManager(object):
def __init__(self, email, passwd, otp):
self.email = email
self.passwd = passwd
self.br = Browser('firefox')
atexit.register(self.force_br_quit)
# To dynamically load jQuery into the HTML head
self.loadjq = """var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src =
'//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';
head.appendChild(script);"""
self.otp = otp
self.logged_in = self.login()
def force_br_quit(self):
try:
self.br.quit()
except:
pass
def create(self, title, desc, date, time):
""" Create a new Google Plus event """
if not self.logged_in:
self.logged_in = self.login()
create_btn = 'div[guidedhelpid="events_create_event_button"]'
self.br.find_by_css(create_btn)[0].click()
return self.complete_form(title, desc, date, time, update=False)
def update(self, id, title=None, desc=None, date=None, time=None):
""" Update a Google Plus event """
if not self.logged_in:
self.logged_in = self.login()
self.br.visit(id)
dropdown = 'div[class="A7kfHd q3sPdd"]'
while self.br.is_element_not_present_by_css(dropdown):
pass
self.br.find_by_css(dropdown).click()
self.br.find_by_xpath('//*[@id=":o"]/div').click()
return self.complete_form(title, desc, date, time, update=True)
def complete_form(self, title, desc, date, time, update):
"""Fill event create/edit form,
the CSS selectors are valid in both types of form"""
title_input = 'input[placeholder="Event title"]'
while self.br.is_element_not_present_by_css(title_input):
pass
if title:
title_placeholder = self.br.find_by_css(title_input)
title_placeholder.fill(title)
if date:
self.br.find_by_css('input[class="g-A-G T4 lUa"]').click()
rm_date = '''document.body.getElementsByClassName("g-A-G T4 lUa")
[0].value = ""'''
self.br.execute_script(rm_date)
date_field = 'input[class="g-A-G T4 lUa"]'
self.br.find_by_css(date_field).type('{}\t'.format(date))
if time:
self.br.execute_script(self.loadjq)
loaded = False
rm_time = '$(".EKa")[0].value = ""'
while not loaded:
try:
self.br.execute_script(rm_time)
except Exception, e:
pass
else:
loaded = True
time_field = 'input[class="g-A-G T4 EKa"]'
self.br.find_by_css(time_field)[0].type('{}'.format(time))
if desc:
set_desc = '''document.body.getElementsByClassName("yd editable")
[1].innerHTML = "{}"'''.format(desc)
self.br.execute_script(set_desc)
invite_btn = self.br.find_by_css('div[guidedhelpid="sharebutton"]')
invite_inp = self.br.find_by_css('input[class="i-j-h-G-G"]')
invite_btn.click()
if not update: # If new entry, invite Public group by default
invite_inp.click()
invite_inp.type('Public\n')
invite_btn.click()
while not self.br.is_text_present('Going ('):
pass # wait on page load for new event
url = self.br.url
self.br.quit()
return url # return event url
def details(self, id):
"""Read details of a Google event"""
if not self.logged_in:
self.logged_in = self.login()
self.br.visit(id)
details = {}
title = self.br.find_by_css('div[class="Iba"]')
desc = self.br.find_by_css('div[class="T7BsYe"]')
details['title'] = title.text.split('\n')[0]
details['desc'] = desc.text
guest_list = self.br.find_by_css('a[href^="./"]')[2:]
details['guests'] = [{guest.text: guest['href']}
for guest in guest_list]
return details
def login(self):
url = 'https://plus.google.com/u/0/events'
self.br.visit(url)
self.br.fill('Email', self.email)
self.br.fill('Passwd', self.passwd)
try:
self.br.find_by_name('signIn').click()
while self.br.is_element_present_by_name('signIn'):
pass
if self.otp:
self.br.fill('smsUserPin', self.otp)
self.br.find_by_id('smsVerifyPin').click()
while self.br.is_element_present_by_id('smsVerifyPin'):
pass
if self.br.is_element_present_by_id('smsauth-time-sync-tip'):
print 'Expired OTP {}'.format(self.otp)
exit(1)
except Exception, e:
print 'Could not login'
exit(1)
else:
return True
conf = load_config()
if __name__ == '__main__':
opts = cli_parse()
gpem = GPlusEventManager(conf['username'], conf['password'],
opts.get('otp'))
if opts['action'] == 'create':
id = gpem.create(opts['title'], opts['desc'],
opts['date'], opts['time'])
print 'Created: {}'.format(id)
elif opts['action'] == 'update':
id = gpem.update(opts['id'], opts['title'], opts['desc'],
opts['date'], opts['time'])
print 'Event {} updated'.format(opts['id'])
elif opts['action'] == 'details':
details = gpem.details(opts['id'])
print details