9 logger = logging.getLogger('gooswapper')
10 logger.setLevel(logging.INFO)
11 consolelog = logging.StreamHandler()
12 consolelog.setLevel(logging.INFO)
13 logformatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
14 consolelog.setFormatter(logformatter)
15 logger.addHandler(consolelog)
16 #We can't use this, because that way all the libraries' logs spam us
17 #logging.basicConfig(level=logging.INFO)
19 #Exchange-related library
20 sys.path.append("/upstreams/exchangelib")
23 #Google calendar-api libraries
25 import apiclient.discovery
27 import oauth2client.file
28 import oauth2client.client
29 import googleapiclient.errors
31 #Not sure what the distribution approach here is...
32 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
33 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
35 #scope URL for r/w calendar access
36 scope = 'https://www.googleapis.com/auth/calendar'
37 #flow object, for doing OAuth2.0 stuff
38 flow = oauth2client.client.OAuth2WebServerFlow(gcal_client_id,
43 gcal_authpath=".gooswap_gcal_creds.dat"
45 cachepath=".gooswapcache"
47 exchange_credential = None
49 CachedExEvent=collections.namedtuple('CachedExEvent',
50 ['changekey','gcal_link'])
52 class ex_gcal_link(exchangelib.ExtendedProperty):
53 distinguished_property_set_id = 'PublicStrings'
54 property_name = "google calendar event id"
55 property_type = 'String'
58 exchangelib.CalendarItem.get_field_by_fieldname('gcal_link')
60 exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
62 #useful if you want to replay an event
63 def drop_from_ex_cache(itemid):
64 with open(cachepath,"rb") as f:
65 cache = pickle.load(f)
67 with open(cachepath,"wb") as f:
70 def get_ex_event_by_itemid(calendar,itemid):
71 return calendar.get(item_id=itemid)
73 def get_ex_event_by_id_and_changekey(acct,itemid,changekey):
74 l=list(acct.fetch([(itemid,changekey)]))
75 return list(acct.fetch([(itemid,changekey)]))[0]
77 def get_gcal_recur_instance(gcal_acct,gcal_master,start,gcal_id="primary"):
78 ans = gcal_acct.events().instances(calendarId=gcal_id,
80 originalStart=start.isoformat(),
81 showDeleted=True).execute()
82 if len(ans['items']) != 1:
83 logger.error("Searching for recurrance instance returned %d events" % \
86 return ans['items'][0]
88 def get_ex_cred(username="SANGER\mv3",password=None):
90 password = getpass.getpass(prompt="Password for user %s: " % username)
91 return exchangelib.ServiceAccount(username,password)
93 def ex_login(emailaddr,ad_cache_path=None):
94 global exchange_credential
96 if exchange_credential is None:
97 exchange_credential = get_ex_cred()
98 if ad_cache_path is not None:
100 with open(ad_cache_path,"rb") as f:
101 url,auth_type = pickle.load(f)
103 except FileNotFoundError:
107 ex_ac = exchangelib.Account(emailaddr,
108 credentials = exchange_credential,
109 autodiscover = autodiscover)
110 if ad_cache_path is not None:
111 cache=(ex_ac.protocol.service_endpoint,
112 ex_ac.protocol.auth_type)
113 with open(ad_cache_path,"wb") as f:
116 ex_conf = exchangelib.Configuration(service_endpoint=url,
117 credentials=exchange_credential,
119 ex_ac = exchangelib.Account(emailaddr,
122 access_type=exchangelib.DELEGATE)
126 def get_ex_events(calendar):
128 for event in calendar.all().only('changekey','item_id','gcal_link'):
129 if event.item_id in ans:
130 logger.warning("Event item_id %s was duplicated!" % event.item_id)
131 ans[event.item_id] = CachedExEvent(event.changekey,event.gcal_link)
132 logger.info("%d events found" % len(ans))
135 def ex_event_changes(old,new):
136 olds = set(old.keys())
137 news = set(new.keys())
138 added = list(news-olds)
139 deleted = list(olds-news)
141 #intersection - i.e. common to both sets
142 for event in olds & news:
143 if old[event].changekey != new[event].changekey:
144 changed.append(event)
145 logger.info("%d events updated, %d added, %d deleted" % (len(changed),
148 return added, deleted, changed
150 #exchangelib gives us days in recurrence patterns as integers,
151 #RFC5545 wants SU,MO,TU,WE,TH,FR,SA
152 #it has a utility function to convert to Monday, Tuesday, ...
153 def rr_daystr_from_int(i):
154 return exchangelib.recurrence._weekday_to_str(i).upper()[:2]
156 def rrule_from_ex(event,gcal_tz):
157 if event.type != "RecurringMaster":
158 logger.error("Cannot make recurrence from not-recurring event")
160 if event.recurrence is None:
161 logger.error("Empty recurrence structure")
163 if isinstance(event.recurrence.pattern,
164 exchangelib.recurrence.DailyPattern):
165 rr = "RRULE:FREQ=DAILY;INTERVAL=%d" % event.recurrence.pattern.interval
166 elif isinstance(event.recurrence.pattern,
167 exchangelib.recurrence.WeeklyPattern):
168 rr = "RRULE:FREQ=WEEKLY;INTERVAL=%d;BYDAY=%s;WKST=%s" % \
169 (event.recurrence.pattern.interval,
170 ",".join([rr_daystr_from_int(x) for x in event.recurrence.pattern.weekdays]),
171 rr_daystr_from_int(event.recurrence.pattern.first_day_of_week) )
173 logger.error("Recurrence %s not supported" % event.recurrence)
175 if isinstance(event.recurrence.boundary,
176 exchangelib.recurrence.EndDatePattern):
177 rr += ";UNTIL={0:%Y}{0:%m}{0:%d}".format(event.recurrence.boundary.end)
179 logger.error("Recurrence %s not supported" % event.recurrence)
183 def modify_recurring(ex_acct,gcal_acct,gcal_tz,
184 events,master,gcal_id="primary"):
185 if master.modified_occurrences is not None:
186 for mod in master.modified_occurrences:
187 instance = get_gcal_recur_instance(gcal_acct,master.gcal_link,
188 mod.original_start,gcal_id)
189 if instance is None: #give up after first failure
191 mod_event = get_ex_event_by_itemid(ex_acct.calendar,mod.item_id)
192 gevent = build_gcal_event_from_ex(mod_event,gcal_tz)
193 gevent = gcal_acct.events().update(calendarId=gcal_id,
194 eventId=instance.get('id'),
196 sendUpdates="none").execute()
197 mod_event.gcal_link = gevent.get("id")
198 mod_event.save(update_fields=["gcal_link"])
199 if master.deleted_occurrences is not None:
200 for d in master.deleted_occurrences:
201 instance = get_gcal_recur_instance(gcal_acct,master.gcal_link,
203 if instance is None: #give up after any failure
205 if instance["status"] != "cancelled":
206 instance["status"]="cancelled"
207 gcal_acct.events().update(calendarId=gcal_id,
208 eventId=instance.get('id'),
210 sendUpdates="none").execute()
212 def build_gcal_event_from_ex(event,gcal_tz):
214 gevent["summary"]=event.subject
216 gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
217 gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
219 gevent["end"]={"dateTime": event.end.astimezone(gcal_tz).isoformat(),
220 "timeZone": str(gcal_tz)}
221 gevent["start"]={"dateTime": event.start.astimezone(gcal_tz).isoformat(),
222 "timeZone": str(gcal_tz)}
223 if event.text_body is not None and event.text_body.strip() != '':
224 gevent["description"] = event.text_body
225 if event.location is not None:
226 gevent["location"] = event.location
227 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
230 def add_ex_to_gcal(ex_acct,
231 gcal_acct,gcal_tz,events,
235 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
236 gevent = build_gcal_event_from_ex(event,gcal_tz)
237 if event.type=="RecurringMaster":
238 rr = rrule_from_ex(event,gcal_tz)
240 gevent["recurrence"] = rr
243 logger.warning("Unable to set recurrence for %s" % event.item_id)
244 continue #don't make the gcal event
245 gevent = gcal_acct.events().insert(calendarId=gcal_id,
246 body=gevent).execute()
247 event.gcal_link = gevent.get("id")
248 event.save(update_fields=["gcal_link"])
249 if event.type=="RecurringMaster" and (event.deleted_occurrences or \
250 event.modified_occurrences):
251 modify_recurring(ex_acct,gcal_acct,gcal_tz,
252 events,event,gcal_id)
253 #changekey is updated by the above
255 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
257 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
258 for ev_id in deleted:
259 if events[ev_id].gcal_link is not None:
260 gcal_acct.events().delete(calendarId=gcal_id,
261 eventId=events[ev_id].gcal_link,
262 sendUpdates="none").execute()
264 def update_ex_to_gcal(ex_acct,
268 for ev_id in changed:
269 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
270 gevent = build_gcal_event_from_ex(event,gcal_tz)
271 if event.type=="RecurringMaster":
272 rr = rrule_from_ex(event,gcal_tz)
274 gevent["recurrence"] = rr
275 if event.deleted_occurrences or \
276 event.modified_occurrences:
277 modify_recurring(ex_acct,gcal_acct,gcal_tz,
278 events,event,gcal_id)
279 event.refresh() #changekey is updated by the above
280 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
282 logger.warning("Unable to set recurrence for %s" % event.item_id)
283 continue #don't make the gcal event
284 gevent = gcal_acct.events().update(calendarId=gcal_id,
285 eventId=event.gcal_link,
287 sendUpdates="none").execute()
289 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary"):
294 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
295 if event.is_recurring:
298 elif event.gcal_link is not None:
301 matches = gcal_acct.events().list(calendarId=gcal_id,
302 timeMin=event.start.isoformat(),
303 timeMax=event.end.isoformat()).execute()
304 for ge in matches['items']:
305 if ge['summary'].strip()==event.subject.strip():
306 logger.info("Matching '%s' starting at %s" % (event.subject,
307 event.start.isoformat()))
308 event.gcal_link = ge['id']
309 event.save(update_fields=["gcal_link"])
310 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
312 gevent["start"] = ge["start"]
313 gevent["end"] = ge["end"]
314 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
316 gcal_acct.events().update(calendarId=gcal_id,
317 eventId=event.gcal_link,
319 sendUpdates="none").execute()
320 #this may fail if we don't own the event
321 except googleapiclient.errors.HttpError as err:
322 if err.resp.status == 403:
326 logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
329 #each such file can only store a single credential
330 storage = oauth2client.file.Storage(gcal_authpath)
331 gcal_credential = storage.get()
332 #if no credential found, or they're invalid (e.g. expired),
333 #then get a new one; pass --noauth_local_webserver on the command line
334 #if you don't want it to spawn a browser
335 if gcal_credential is None or gcal_credential.invalid:
336 gcal_credential = oauth2client.tools.run_flow(flow,
338 oauth2client.tools.argparser.parse_args())
339 return gcal_credential
342 gcal_credential = get_gcal_cred()
343 # Object to handle http requests; could add proxy details
344 http = httplib2.Http()
345 http = gcal_credential.authorize(http)
346 return apiclient.discovery.build('calendar', 'v3', http=http)
348 def get_gcal_timezone(gcal_account,calendarid="primary"):
349 gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
350 return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
354 with open(cachepath,"rb") as f:
355 cache = pickle.load(f)
356 except FileNotFoundError:
359 ex_account = ex_login("mv3@sanger.ac.uk",".gooswapper_exch_conf.dat")
360 current = get_ex_events(ex_account.calendar)
362 gcal_account = gcal_login()
363 gcal_tz = get_gcal_timezone(gcal_account)
365 if cache is not None:
366 added,deleted,changed = ex_event_changes(cache,current)
367 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,added)
368 #delete op needs the "cache" set, as that has the link ids in
369 #for events that are now deleted
370 del_ex_to_gcal(ex_account,gcal_account,cache,deleted)
371 update_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,changed)
373 match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current)
375 with open(cachepath,"wb") as f:
376 pickle.dump(current,f)
378 if __name__ == "__main__":