3 # Copyright (C) 2018 Genome Research Limited
5 # Author: Matthew Vernon <mv3@sanger.ac.uk>
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU Affero General Public License as published
9 # by the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU Affero General Public License for more details.
17 # You should have received a copy of the GNU Affero General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
29 logger = logging.getLogger('gooswapper')
30 logger.setLevel(logging.INFO)
31 consolelog = logging.StreamHandler()
32 consolelog.setLevel(logging.INFO)
33 logformatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
34 consolelog.setFormatter(logformatter)
35 logger.addHandler(consolelog)
36 #We can't use this, because that way all the libraries' logs spam us
37 #logging.basicConfig(level=logging.INFO)
39 #Exchange-related library
40 sys.path.append("/upstreams/exchangelib")
43 #Google calendar-api libraries
45 import apiclient.discovery
47 import oauth2client.file
48 import oauth2client.client
49 import googleapiclient.errors
51 #Not sure what the distribution approach here is...
52 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
53 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
55 #scope URL for r/w calendar access
56 scope = 'https://www.googleapis.com/auth/calendar'
57 #flow object, for doing OAuth2.0 stuff
58 flow = oauth2client.client.OAuth2WebServerFlow(gcal_client_id,
62 gsdir = os.path.expanduser("~/.gooswapper")
63 gcal_authpath = gsdir + "/.gooswap_gcal_creds.dat"
67 exchange_credential = None
69 CachedExEvent=collections.namedtuple('CachedExEvent',
70 ['changekey','gcal_link'])
72 class ex_gcal_link(exchangelib.ExtendedProperty):
73 distinguished_property_set_id = 'PublicStrings'
74 property_name = "google calendar event id"
75 property_type = 'String'
78 exchangelib.CalendarItem.get_field_by_fieldname('gcal_link')
80 exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
82 #useful if you want to replay an event
83 def drop_from_ex_cache(itemid):
84 with open(cachepath,"rb") as f:
85 cache = pickle.load(f)
87 with open(cachepath,"wb") as f:
90 def get_ex_event_by_itemid(calendar,itemid):
91 return calendar.get(item_id=itemid)
93 def get_ex_event_by_id_and_changekey(acct,itemid,changekey):
94 l=list(acct.fetch([(itemid,changekey)]))
95 return list(acct.fetch([(itemid,changekey)]))[0]
97 def get_gcal_event_by_eventid(gcal_acct,eventId,gcal_id="primary"):
98 return gcal_acct.events().get(calendarId=gcal_id,eventId=eventId).execute()
100 def get_gcal_recur_instance(gcal_acct,gcal_master,start,gcal_id="primary"):
101 if gcal_master is None:
102 logger.warning("Cannot get recurrences from event with null gcal id")
104 ans = gcal_acct.events().instances(calendarId=gcal_id,
106 originalStart=start.isoformat(),
107 showDeleted=True).execute()
108 if len(ans['items']) != 1:
109 logger.error("Searching for recurrance instance returned %d events" % \
112 return ans['items'][0]
114 def get_ex_cred(username="SANGER\mv3",password=None):
116 password = getpass.getpass(prompt="Password for user %s: " % username)
117 return exchangelib.ServiceAccount(username,password)
119 def ex_login(username,emailaddr,ad_cache_path=None):
120 global exchange_credential
122 if exchange_credential is None:
123 exchange_credential = get_ex_cred(username)
124 if ad_cache_path is not None:
126 with open(ad_cache_path,"rb") as f:
127 url,auth_type = pickle.load(f)
129 except FileNotFoundError:
133 ex_ac = exchangelib.Account(emailaddr,
134 credentials = exchange_credential,
135 autodiscover = autodiscover)
136 if ad_cache_path is not None:
137 cache=(ex_ac.protocol.service_endpoint,
138 ex_ac.protocol.auth_type)
139 with open(ad_cache_path,"wb") as f:
142 ex_conf = exchangelib.Configuration(service_endpoint=url,
143 credentials=exchange_credential,
145 ex_ac = exchangelib.Account(emailaddr,
148 access_type=exchangelib.DELEGATE)
152 def get_ex_events(calendar):
154 for event in calendar.all().only('changekey','item_id','gcal_link'):
155 if event.item_id in ans:
156 logger.warning("Event item_id %s was duplicated!" % event.item_id)
157 ans[event.item_id] = CachedExEvent(event.changekey,event.gcal_link)
158 logger.info("%d events found" % len(ans))
161 def ex_event_changes(old,new):
162 olds = set(old.keys())
163 news = set(new.keys())
164 added = list(news-olds)
165 deleted = list(olds-news)
167 #intersection - i.e. common to both sets
168 for event in olds & news:
169 if old[event].changekey != new[event].changekey:
170 changed.append(event)
171 logger.info("%d events updated, %d added, %d deleted" % (len(changed),
174 return added, deleted, changed
176 #exchangelib gives us days in recurrence patterns as integers,
177 #RFC5545 wants SU,MO,TU,WE,TH,FR,SA
178 #it has a utility function to convert to Monday, Tuesday, ...
179 def rr_daystr_from_int(i):
180 return exchangelib.recurrence._weekday_to_str(i).upper()[:2]
182 #for monthly patterns, we want the week (or -1 for last) combined with each
184 def rr_daystr_monthly(p):
185 if p.week_number == 5:
188 wn = str(p.week_number)
189 return ",".join([wn + rr_daystr_from_int(x) for x in p.weekdays])
191 def rrule_from_ex(event,gcal_tz):
192 if event.type != "RecurringMaster":
193 logger.error("Cannot make recurrence from not-recurring event")
195 if event.recurrence is None:
196 logger.error("Empty recurrence structure")
198 if isinstance(event.recurrence.pattern,
199 exchangelib.recurrence.DailyPattern):
200 rr = "RRULE:FREQ=DAILY;INTERVAL=%d" % event.recurrence.pattern.interval
201 elif isinstance(event.recurrence.pattern,
202 exchangelib.recurrence.WeeklyPattern):
203 rr = "RRULE:FREQ=WEEKLY;INTERVAL=%d;BYDAY=%s;WKST=%s" % \
204 (event.recurrence.pattern.interval,
205 ",".join([rr_daystr_from_int(x) for x in event.recurrence.pattern.weekdays]),
206 rr_daystr_from_int(event.recurrence.pattern.first_day_of_week) )
207 elif isinstance(event.recurrence.pattern,
208 exchangelib.recurrence.RelativeMonthlyPattern):
209 rr = "RRULE:FREQ=MONTHLY;INTERVAL=%d;BYDAY=%s" % \
210 (event.recurrence.pattern.interval,
211 rr_daystr_monthly(event.recurrence.pattern))
212 elif isinstance(event.recurrence.pattern,
213 exchangelib.recurrence.AbsoluteMonthlyPattern):
214 rr = "RRULE:FREQ=MONTHLY;INTERVAL=%d;BYMONTHDAY=%d" % \
215 (event.recurrence.pattern.interval,
216 event.recurrence.pattern.day_of_month)
217 elif isinstance(event.recurrence.pattern,
218 exchangelib.recurrence.AbsoluteYearlyPattern):
219 rr = "RRULE:FREQ=YEARLY;BYMONTH=%d;BYMONTHDAY=%d" % \
220 (event.recurrence.pattern.month,
221 event.recurrence.pattern.day_of_month)
222 elif isinstance(event.recurrence.pattern,
223 exchangelib.recurrence.RelativeYearlyPattern):
224 rr = "RRULE:FREQ=YEARLY;BYMONTH=%d;BYDAY=%s" % \
225 (event.recurrence.pattern.month,
226 rr_daystr_monthly(event.recurrence.pattern))
228 logger.error("Recurrence %s not supported" % event.recurrence)
230 if isinstance(event.recurrence.boundary,
231 exchangelib.recurrence.EndDatePattern):
232 rr += ";UNTIL={0:%Y}{0:%m}{0:%d}".format(event.recurrence.boundary.end)
233 elif isinstance(event.recurrence.boundary,
234 exchangelib.recurrence.NoEndPattern):
235 pass #no end date to set
237 logger.error("Recurrence %s not supported" % event.recurrence)
241 def modify_recurring(ex_acct,gcal_acct,gcal_tz,
242 events,master,gcal_id="primary"):
243 if master.modified_occurrences is not None:
244 for mod in master.modified_occurrences:
245 instance = get_gcal_recur_instance(gcal_acct,master.gcal_link,
246 mod.original_start,gcal_id)
247 if instance is None: #give up after first failure
249 mod_event = get_ex_event_by_itemid(ex_acct.calendar,mod.item_id)
250 gevent = build_gcal_event_from_ex(mod_event,gcal_tz)
251 gevent = gcal_acct.events().update(calendarId=gcal_id,
252 eventId=instance.get('id'),
254 sendUpdates="none").execute()
255 mod_event.gcal_link = gevent.get("id")
256 mod_event.save(update_fields=["gcal_link"])
257 if master.deleted_occurrences is not None:
258 for d in master.deleted_occurrences:
259 instance = get_gcal_recur_instance(gcal_acct,master.gcal_link,
261 if instance is None: #give up after any failure
263 if instance["status"] != "cancelled":
264 instance["status"]="cancelled"
265 gcal_acct.events().update(calendarId=gcal_id,
266 eventId=instance.get('id'),
268 sendUpdates="none").execute()
270 def build_gcal_event_from_ex(event,gcal_tz):
272 gevent["summary"]=event.subject
273 #Use the event's timezones if possible, otherwise fall back to the
274 #target calendar timezone
275 if event._start_timezone is not None:
276 stz = event._start_timezone
279 if event._end_timezone is not None:
280 etz = event._end_timezone
284 gevent["end"]={"date": str(event.end.astimezone(etz).date())}
285 gevent["start"]={"date": str(event.start.astimezone(stz).date())}
287 gevent["end"]={"dateTime": event.end.astimezone(etz).isoformat(),
288 "timeZone": str(etz)}
289 gevent["start"]={"dateTime": event.start.astimezone(stz).isoformat(),
290 "timeZone": str(stz)}
291 if event.text_body is not None and event.text_body.strip() != '':
292 gevent["description"] = event.text_body
293 if event.location is not None:
294 gevent["location"] = event.location
295 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
298 def add_ex_to_gcal(ex_acct,
299 gcal_acct,gcal_tz,events,
303 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
304 gevent = build_gcal_event_from_ex(event,gcal_tz)
305 if event.type=="RecurringMaster":
306 rr = rrule_from_ex(event,gcal_tz)
308 gevent["recurrence"] = rr
311 logger.warning("Unable to set recurrence for %s" % event.item_id)
312 continue #don't make the gcal event
313 gevent = gcal_acct.events().insert(calendarId=gcal_id,
314 body=gevent).execute()
315 event.gcal_link = gevent.get("id")
316 event.save(update_fields=["gcal_link"])
317 if event.type=="RecurringMaster" and (event.deleted_occurrences or \
318 event.modified_occurrences):
319 modify_recurring(ex_acct,gcal_acct,gcal_tz,
320 events,event,gcal_id)
321 #changekey is updated by the above
323 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
325 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
326 for ev_id in deleted:
327 if events[ev_id].gcal_link is not None:
328 gevent = get_gcal_event_by_eventid(gcal_acct,
329 events[ev_id].gcal_link,
331 if gevent["status"] != "cancelled":
332 gcal_acct.events().delete(calendarId=gcal_id,
333 eventId=events[ev_id].gcal_link,
334 sendUpdates="none").execute()
336 def update_ex_to_gcal(ex_acct,
340 for ev_id in changed:
341 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
342 if event.gcal_link is None:
343 logger.warning("Cannot apply update where event has no gcal link")
345 gevent = build_gcal_event_from_ex(event,gcal_tz)
346 if event.type=="RecurringMaster":
347 rr = rrule_from_ex(event,gcal_tz)
349 gevent["recurrence"] = rr
350 if event.deleted_occurrences or \
351 event.modified_occurrences:
352 modify_recurring(ex_acct,gcal_acct,gcal_tz,
353 events,event,gcal_id)
354 event.refresh() #changekey is updated by the above
355 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
357 logger.warning("Unable to set recurrence for %s" % event.item_id)
358 continue #don't make the gcal event
359 try: #may fail if we don't own the event
360 gevent = gcal_acct.events().update(calendarId=gcal_id,
361 eventId=event.gcal_link,
363 sendUpdates="none").execute()
364 except googleapiclient.errors.HttpError as err:
365 if err.resp.status == 403:
368 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary",ignore_link=True):
374 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
375 if event.gcal_link is not None and ignore_link is False:
379 matches = gcal_acct.events().list(calendarId=gcal_id,
380 timeMin=event.start.isoformat(),
381 timeMax=event.end.isoformat()).execute()
382 for ge in matches['items']:
383 if ( ge.get("summary") is None and event.subject is None ) or \
384 ( ge.get("summary") is not None and event.subject is not None \
385 and ge['summary'].strip()==event.subject.strip()):
386 logger.info("Matching '%s' starting at %s" % (event.subject,
387 event.start.isoformat()))
388 event.gcal_link = ge['id']
389 event.save(update_fields=["gcal_link"])
390 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
392 gevent["start"] = ge["start"]
393 gevent["end"] = ge["end"]
394 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
396 gcal_acct.events().update(calendarId=gcal_id,
397 eventId=event.gcal_link,
399 sendUpdates="none").execute()
400 #this may fail if we don't own the event
401 except googleapiclient.errors.HttpError as err:
402 if err.resp.status == 403:
409 logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
412 def get_gcal_cred(args):
413 #each such file can only store a single credential
414 storage = oauth2client.file.Storage(gcal_authpath)
415 gcal_credential = storage.get()
416 #if no credential found, or they're invalid (e.g. expired),
417 #then get a new one; pass --noauth_local_webserver on the command line
418 #if you don't want it to spawn a browser
419 if gcal_credential is None or gcal_credential.invalid:
420 gcal_credential = oauth2client.tools.run_flow(flow,
423 return gcal_credential
425 def gcal_login(args):
426 gcal_credential = get_gcal_cred(args)
427 # Object to handle http requests; could add proxy details
428 http = httplib2.Http()
429 http = gcal_credential.authorize(http)
430 return apiclient.discovery.build('calendar', 'v3', http=http)
432 def get_gcal_timezone(gcal_account,calendarid="primary"):
433 gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
434 return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
437 ap=argparse.ArgumentParser(description="Gooswapper calendar sync",
438 parents=[oauth2client.tools.argparser])
439 ap.add_argument("exchuser",help="Exchange user e.g. 'SANGER\mv3'")
440 ap.add_argument("exchemail",
441 help="Exchange calendar email e.g. ISGGroup@sanger.ac.uk")
442 ap.add_argument("-g","--gcalid",help="google Calendar ID")
443 ap.add_argument("-l","--loop",help="keep running indefinitely",
445 args = ap.parse_args()
446 if args.gcalid is None:
449 gcal_id = args.gcalid
451 #Make our config dir if it doesn't exist
452 if not os.path.exists(gsdir):
453 os.mkdir(gsdir,0o700)
454 #Cache file is specific to the Exchange calendar
456 cachepath = gsdir + "/.cache-%s" % \
457 (args.exchemail.replace('@','_').replace('/','_'))
459 #log in to the accounts
460 ex_account = ex_login(args.exchuser,args.exchemail,
461 gsdir+"/.gooswapper_exch_conf.dat")
462 gcal_account = gcal_login(args)
463 gcal_tz = get_gcal_timezone(gcal_account,gcal_id)
465 #Main loop (broken at the end if login is false)
468 with open(cachepath,"rb") as f:
469 cache = pickle.load(f)
470 except FileNotFoundError:
473 current = get_ex_events(ex_account.calendar)
475 if cache is not None:
476 added,deleted,changed = ex_event_changes(cache,current)
477 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
479 #delete op needs the "cache" set, as that has the link ids in
480 #for events that are now deleted
481 del_ex_to_gcal(ex_account,gcal_account,cache,deleted,gcal_id)
482 update_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
485 toadd = match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
487 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
490 with open(cachepath,"wb") as f:
491 pickle.dump(current,f)
493 #If not looping, break here (after 1 run)
496 #otherwise, wait 10 minutes, then go round again
499 if __name__ == "__main__":