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
274 gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
275 gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
277 gevent["end"]={"dateTime": event.end.astimezone(gcal_tz).isoformat(),
278 "timeZone": str(gcal_tz)}
279 gevent["start"]={"dateTime": event.start.astimezone(gcal_tz).isoformat(),
280 "timeZone": str(gcal_tz)}
281 if event.text_body is not None and event.text_body.strip() != '':
282 gevent["description"] = event.text_body
283 if event.location is not None:
284 gevent["location"] = event.location
285 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
288 def add_ex_to_gcal(ex_acct,
289 gcal_acct,gcal_tz,events,
293 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
294 gevent = build_gcal_event_from_ex(event,gcal_tz)
295 if event.type=="RecurringMaster":
296 rr = rrule_from_ex(event,gcal_tz)
298 gevent["recurrence"] = rr
301 logger.warning("Unable to set recurrence for %s" % event.item_id)
302 continue #don't make the gcal event
303 gevent = gcal_acct.events().insert(calendarId=gcal_id,
304 body=gevent).execute()
305 event.gcal_link = gevent.get("id")
306 event.save(update_fields=["gcal_link"])
307 if event.type=="RecurringMaster" and (event.deleted_occurrences or \
308 event.modified_occurrences):
309 modify_recurring(ex_acct,gcal_acct,gcal_tz,
310 events,event,gcal_id)
311 #changekey is updated by the above
313 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
315 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
316 for ev_id in deleted:
317 if events[ev_id].gcal_link is not None:
318 gevent = get_gcal_event_by_eventid(gcal_acct,
319 events[ev_id].gcal_link,
321 if gevent["status"] != "cancelled":
322 gcal_acct.events().delete(calendarId=gcal_id,
323 eventId=events[ev_id].gcal_link,
324 sendUpdates="none").execute()
326 def update_ex_to_gcal(ex_acct,
330 for ev_id in changed:
331 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
332 if event.gcal_link is None:
333 logger.warning("Cannot apply update where event has no gcal link")
335 gevent = build_gcal_event_from_ex(event,gcal_tz)
336 if event.type=="RecurringMaster":
337 rr = rrule_from_ex(event,gcal_tz)
339 gevent["recurrence"] = rr
340 if event.deleted_occurrences or \
341 event.modified_occurrences:
342 modify_recurring(ex_acct,gcal_acct,gcal_tz,
343 events,event,gcal_id)
344 event.refresh() #changekey is updated by the above
345 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
347 logger.warning("Unable to set recurrence for %s" % event.item_id)
348 continue #don't make the gcal event
349 try: #may fail if we don't own the event
350 gevent = gcal_acct.events().update(calendarId=gcal_id,
351 eventId=event.gcal_link,
353 sendUpdates="none").execute()
354 except googleapiclient.errors.HttpError as err:
355 if err.resp.status == 403:
358 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary",ignore_link=True):
364 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
365 if event.gcal_link is not None and ignore_link is False:
369 matches = gcal_acct.events().list(calendarId=gcal_id,
370 timeMin=event.start.isoformat(),
371 timeMax=event.end.isoformat()).execute()
372 for ge in matches['items']:
373 if ( ge.get("summary") is None and event.subject is None ) or \
374 ( ge.get("summary") is not None and event.subject is not None \
375 and ge['summary'].strip()==event.subject.strip()):
376 logger.info("Matching '%s' starting at %s" % (event.subject,
377 event.start.isoformat()))
378 event.gcal_link = ge['id']
379 event.save(update_fields=["gcal_link"])
380 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
382 gevent["start"] = ge["start"]
383 gevent["end"] = ge["end"]
384 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
386 gcal_acct.events().update(calendarId=gcal_id,
387 eventId=event.gcal_link,
389 sendUpdates="none").execute()
390 #this may fail if we don't own the event
391 except googleapiclient.errors.HttpError as err:
392 if err.resp.status == 403:
399 logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
402 def get_gcal_cred(args):
403 #each such file can only store a single credential
404 storage = oauth2client.file.Storage(gcal_authpath)
405 gcal_credential = storage.get()
406 #if no credential found, or they're invalid (e.g. expired),
407 #then get a new one; pass --noauth_local_webserver on the command line
408 #if you don't want it to spawn a browser
409 if gcal_credential is None or gcal_credential.invalid:
410 gcal_credential = oauth2client.tools.run_flow(flow,
413 return gcal_credential
415 def gcal_login(args):
416 gcal_credential = get_gcal_cred(args)
417 # Object to handle http requests; could add proxy details
418 http = httplib2.Http()
419 http = gcal_credential.authorize(http)
420 return apiclient.discovery.build('calendar', 'v3', http=http)
422 def get_gcal_timezone(gcal_account,calendarid="primary"):
423 gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
424 return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
427 ap=argparse.ArgumentParser(description="Gooswapper calendar sync",
428 parents=[oauth2client.tools.argparser])
429 ap.add_argument("exchuser",help="Exchange user e.g. 'SANGER\mv3'")
430 ap.add_argument("exchemail",
431 help="Exchange calendar email e.g. ISGGroup@sanger.ac.uk")
432 ap.add_argument("-g","--gcalid",help="google Calendar ID")
433 ap.add_argument("-l","--loop",help="keep running indefinitely",
435 args = ap.parse_args()
436 if args.gcalid is None:
439 gcal_id = args.gcalid
441 #Make our config dir if it doesn't exist
442 if not os.path.exists(gsdir):
443 os.mkdir(gsdir,0o700)
444 #Cache file is specific to the Exchange calendar
446 cachepath = gsdir + "/.cache-%s" % \
447 (args.exchemail.replace('@','_').replace('/','_'))
449 #log in to the accounts
450 ex_account = ex_login(args.exchuser,args.exchemail,
451 gsdir+"/.gooswapper_exch_conf.dat")
452 gcal_account = gcal_login(args)
453 gcal_tz = get_gcal_timezone(gcal_account,gcal_id)
455 #Main loop (broken at the end if login is false)
458 with open(cachepath,"rb") as f:
459 cache = pickle.load(f)
460 except FileNotFoundError:
463 current = get_ex_events(ex_account.calendar)
465 if cache is not None:
466 added,deleted,changed = ex_event_changes(cache,current)
467 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
469 #delete op needs the "cache" set, as that has the link ids in
470 #for events that are now deleted
471 del_ex_to_gcal(ex_account,gcal_account,cache,deleted,gcal_id)
472 update_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
475 toadd = match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
477 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
480 with open(cachepath,"wb") as f:
481 pickle.dump(current,f)
483 #If not looping, break here (after 1 run)
486 #otherwise, wait 10 minutes, then go round again
489 if __name__ == "__main__":