chiark / gitweb /
05db810ff0b5f226d91a6357e734815d1ccfbc76
[gooswapper] / gooswapper.py
1 #!/usr/bin/env python3
2
3 # Copyright (C) 2018 Genome Research Limited
4 #
5 # Author: Matthew Vernon <mv3@sanger.ac.uk>
6 #
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.
11 #
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.
16 #
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/>.
19
20 import sys
21 import getpass
22 import os
23 import os.path
24 import pickle
25 import collections
26 import argparse
27 import time
28 import logging
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)
38
39 #Exchange-related library
40 sys.path.append("/upstreams/exchangelib")
41 import exchangelib
42
43 #Google calendar-api libraries
44 import httplib2
45 import apiclient.discovery
46 import oauth2client
47 import oauth2client.file
48 import oauth2client.client
49 import googleapiclient.errors
50
51 #Not sure what the distribution approach here is...
52 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
53 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
54
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,
59                                                gcal_client_secret,
60                                                scope)
61
62 gsdir = os.path.expanduser("~/.gooswapper")
63 gcal_authpath = gsdir + "/.gooswap_gcal_creds.dat"
64
65 cachepath=None
66
67 exchange_credential = None
68
69 CachedExEvent=collections.namedtuple('CachedExEvent',
70                                      ['changekey','gcal_link'])
71
72 class ex_gcal_link(exchangelib.ExtendedProperty):
73     distinguished_property_set_id = 'PublicStrings'
74     property_name = "google calendar event id"
75     property_type = 'String'
76
77 try:
78     exchangelib.CalendarItem.get_field_by_fieldname('gcal_link')
79 except ValueError:
80     exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
81
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)
86     cache.pop(itemid)
87     with open(cachepath,"wb") as f:
88         pickle.dump(cache,f)
89
90 def get_ex_event_by_itemid(calendar,itemid):
91     return calendar.get(item_id=itemid)
92
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]
96
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()
99
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")
103         return None
104     ans = gcal_acct.events().instances(calendarId=gcal_id,
105                                        eventId=gcal_master,
106                                        originalStart=start.isoformat(),
107                                        showDeleted=True).execute()
108     if len(ans['items']) != 1:
109         logger.error("Searching for recurrance instance returned %d events" % \
110                      len(ans['items']))
111         return None
112     return ans['items'][0]
113
114 def get_ex_cred(username="SANGER\mv3",password=None):
115     if password is None:
116         password = getpass.getpass(prompt="Password for user %s: " % username)
117     return exchangelib.ServiceAccount(username,password)
118
119 def ex_login(username,emailaddr,ad_cache_path=None):
120     global exchange_credential
121     autodiscover = True
122     if exchange_credential is None:
123         exchange_credential = get_ex_cred(username)
124     if ad_cache_path is not None:
125         try:
126             with open(ad_cache_path,"rb") as f:
127                 url,auth_type = pickle.load(f)
128                 autodiscover = False
129         except FileNotFoundError:
130             pass
131
132     if autodiscover:
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:
140                 pickle.dump(cache,f)
141     else:
142         ex_conf = exchangelib.Configuration(service_endpoint=url,
143                                             credentials=exchange_credential,
144                                             auth_type=auth_type)
145         ex_ac = exchangelib.Account(emailaddr,
146                                     config=ex_conf,
147                                     autodiscover=False,
148                                     access_type=exchangelib.DELEGATE)
149
150     return ex_ac
151
152 def get_ex_events(calendar):
153     ans={}
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))
159     return ans
160
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)
166     changed = []
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),
172                                                               len(added),
173                                                               len(deleted)))
174     return added, deleted, changed
175
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]
181
182 #for monthly patterns, we want the week (or -1 for last) combined with each
183 #day specified
184 def rr_daystr_monthly(p):
185     if p.week_number == 5:
186         wn = "-1"
187     else:
188         wn = str(p.week_number)
189     return ",".join([wn + rr_daystr_from_int(x) for x in p.weekdays])
190
191 def rrule_from_ex(event,gcal_tz):
192     if event.type != "RecurringMaster":
193         logger.error("Cannot make recurrence from not-recurring event")
194         return None
195     if event.recurrence is None:
196         logger.error("Empty recurrence structure")
197         return None
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))
227     else:
228         logger.error("Recurrence %s not supported" % event.recurrence)
229         return None
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
236     else:
237         logger.error("Recurrence %s not supported" % event.recurrence)
238         return None
239     return [rr]
240
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
248                 return
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'),
253                                                body=gevent,
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,
260                                                d.start,gcal_id)
261             if instance is None: #give up after any failure
262                 return
263             if instance["status"] != "cancelled":
264                 instance["status"]="cancelled"
265                 gcal_acct.events().update(calendarId=gcal_id,
266                                           eventId=instance.get('id'),
267                                           body=instance,
268                                           sendUpdates="none").execute()
269
270 def build_gcal_event_from_ex(event,gcal_tz):
271     gevent={}
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
277     else:
278         stz = gcal_tz
279     if event._end_timezone is not None:
280         etz = event._end_timezone
281     else:
282         etz = gcal_tz
283     if event.is_all_day:
284         gevent["end"]={"date": str(event.end.astimezone(etz).date())}
285         gevent["start"]={"date": str(event.start.astimezone(stz).date())}
286     else:
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}}
296     return gevent
297
298 def add_ex_to_gcal(ex_acct,
299                    gcal_acct,gcal_tz,events,
300                    added,
301                    gcal_id="primary"):
302     for ev_id in added:
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)
307             if rr is not None:
308                 gevent["recurrence"] = rr
309                 print(gevent)
310             else:
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
322             event.refresh()
323         events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
324         
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,
330                                                gcal_id)
331             if gevent["status"] != "cancelled":
332                 gcal_acct.events().delete(calendarId=gcal_id,
333                                           eventId=events[ev_id].gcal_link,
334                                           sendUpdates="none").execute()
335
336 def update_ex_to_gcal(ex_acct,
337                       gcal_acct,gcal_tz,
338                       events,changed,
339                       gcal_id="primary"):
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")
344             continue
345         gevent = build_gcal_event_from_ex(event,gcal_tz)
346         if event.type=="RecurringMaster":
347             rr = rrule_from_ex(event,gcal_tz)
348             if rr is not None:
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)
356             else:
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,
362                                                body=gevent,
363                                                sendUpdates="none").execute()
364         except googleapiclient.errors.HttpError as err:
365             if err.resp.status == 403:
366                 pass
367
368 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary",ignore_link=True):
369     recur = 0
370     matched = 0
371     skipped = 0
372     toadd = []
373     for ev_id in events:
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:
376             skipped += 1
377             continue
378         missing=True
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)
391                 gevent = {}
392                 gevent["start"] = ge["start"]
393                 gevent["end"] = ge["end"]
394                 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
395                 try:
396                     gcal_acct.events().update(calendarId=gcal_id,
397                                               eventId=event.gcal_link,
398                                               body=gevent,
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:
403                         pass
404                 matched += 1
405                 missing = False
406                 break
407         if missing == True:
408             toadd.append(ev_id)
409     logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
410     return toadd
411     
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,
421                                                       storage,
422                                                       args)
423     return gcal_credential
424
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)
431
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'])
435
436 def main():
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",
444                     action="store_true")
445     args = ap.parse_args()
446     if args.gcalid is None:
447         gcal_id = "primary"
448     else:
449         gcal_id = args.gcalid
450
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
455     global cachepath
456     cachepath = gsdir + "/.cache-%s" % \
457                 (args.exchemail.replace('@','_').replace('/','_'))
458
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)
464
465     #Main loop (broken at the end if login is false)
466     while True:
467         try:
468             with open(cachepath,"rb") as f:
469                 cache = pickle.load(f)
470         except FileNotFoundError:
471             cache = None
472
473         current = get_ex_events(ex_account.calendar)
474
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,
478                            added,gcal_id)
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,
483                               changed,gcal_id)
484         else:
485             toadd = match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
486                                      gcal_id)
487             add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
488                            toadd,gcal_id)
489         
490         with open(cachepath,"wb") as f:
491             pickle.dump(current,f)
492
493         #If not looping, break here (after 1 run)
494         if args.loop==False:
495             break
496         #otherwise, wait 10 minutes, then go round again
497         time.sleep(600)
498
499 if __name__ == "__main__":
500     main()
501
502