chiark / gitweb /
Handle the remaining recurrence types
[gooswapper] / gooswapper.py
1 #!/usr/bin/env python3
2
3 import sys
4 import getpass
5 import os
6 import pickle
7 import collections
8 import logging
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)
18
19 #Exchange-related library
20 sys.path.append("/upstreams/exchangelib")
21 import exchangelib
22
23 #Google calendar-api libraries
24 import httplib2
25 import apiclient.discovery
26 import oauth2client
27 import oauth2client.file
28 import oauth2client.client
29 import googleapiclient.errors
30
31 #Not sure what the distribution approach here is...
32 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
33 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
34
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,
39                                                gcal_client_secret,
40                                                scope)
41
42
43 gcal_authpath=".gooswap_gcal_creds.dat"
44
45 cachepath=".gooswapcache"
46
47 exchange_credential = None
48
49 CachedExEvent=collections.namedtuple('CachedExEvent',
50                                      ['changekey','gcal_link'])
51
52 class ex_gcal_link(exchangelib.ExtendedProperty):
53     distinguished_property_set_id = 'PublicStrings'
54     property_name = "google calendar event id"
55     property_type = 'String'
56
57 try:
58     exchangelib.CalendarItem.get_field_by_fieldname('gcal_link')
59 except ValueError:
60     exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
61
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)
66     cache.pop(itemid)
67     with open(cachepath,"wb") as f:
68         pickle.dump(cache,f)
69
70 def get_ex_event_by_itemid(calendar,itemid):
71     return calendar.get(item_id=itemid)
72
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]
76
77 def get_gcal_recur_instance(gcal_acct,gcal_master,start,gcal_id="primary"):
78     ans = gcal_acct.events().instances(calendarId=gcal_id,
79                                        eventId=gcal_master,
80                                        originalStart=start.isoformat(),
81                                        showDeleted=True).execute()
82     if len(ans['items']) != 1:
83         logger.error("Searching for recurrance instance returned %d events" % \
84                      len(ans['items']))
85         return None
86     return ans['items'][0]
87
88 def get_ex_cred(username="SANGER\mv3",password=None):
89     if password is None:
90         password = getpass.getpass(prompt="Password for user %s: " % username)
91     return exchangelib.ServiceAccount(username,password)
92
93 def ex_login(emailaddr,ad_cache_path=None):
94     global exchange_credential
95     autodiscover = True
96     if exchange_credential is None:
97         exchange_credential = get_ex_cred()
98     if ad_cache_path is not None:
99         try:
100             with open(ad_cache_path,"rb") as f:
101                 url,auth_type = pickle.load(f)
102                 autodiscover = False
103         except FileNotFoundError:
104             pass
105
106     if autodiscover:
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:
114                 pickle.dump(cache,f)
115     else:
116         ex_conf = exchangelib.Configuration(service_endpoint=url,
117                                             credentials=exchange_credential,
118                                             auth_type=auth_type)
119         ex_ac = exchangelib.Account(emailaddr,
120                                     config=ex_conf,
121                                     autodiscover=False,
122                                     access_type=exchangelib.DELEGATE)
123
124     return ex_ac
125
126 def get_ex_events(calendar):
127     ans={}
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))
133     return ans
134
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)
140     changed = []
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),
146                                                               len(added),
147                                                               len(deleted)))
148     return added, deleted, changed
149
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]
155
156 #for monthly patterns, we want the week (or -1 for last) combined with each
157 #day specified
158 def rr_daystr_monthly(p):
159     if p.week_number == 5:
160         wn = "-1"
161     else:
162         wn = str(p.week_number)
163     return ",".join([wn + rr_daystr_from_int(x) for x in p.weekdays])
164
165 def rrule_from_ex(event,gcal_tz):
166     if event.type != "RecurringMaster":
167         logger.error("Cannot make recurrence from not-recurring event")
168         return None
169     if event.recurrence is None:
170         logger.error("Empty recurrence structure")
171         return None
172     if isinstance(event.recurrence.pattern,
173                   exchangelib.recurrence.DailyPattern):
174         rr = "RRULE:FREQ=DAILY;INTERVAL=%d" % event.recurrence.pattern.interval
175     elif isinstance(event.recurrence.pattern,
176                     exchangelib.recurrence.WeeklyPattern):
177         rr = "RRULE:FREQ=WEEKLY;INTERVAL=%d;BYDAY=%s;WKST=%s" % \
178                           (event.recurrence.pattern.interval,
179                            ",".join([rr_daystr_from_int(x) for x in event.recurrence.pattern.weekdays]),
180                            rr_daystr_from_int(event.recurrence.pattern.first_day_of_week) )
181     elif isinstance(event.recurrence.pattern,
182                     exchangelib.recurrence.RelativeMonthlyPattern):
183         rr = "RRULE:FREQ=MONTHLY;INTERVAL=%d;BYDAY=%s" % \
184                      (event.recurrence.pattern.interval,
185                       rr_daystr_monthly(event.recurrence.pattern))
186     elif isinstance(event.recurrence.pattern,
187                     exchangelib.recurrence.AbsoluteMonthlyPattern):
188         rr = "RRULE:FREQ=MONTHLY;INTERVAL=%d;BYMONTHDAY=%d" % \
189                           (event.recurrence.pattern.interval,
190                            event.recurrence.pattern.day_of_month)
191     elif isinstance(event.recurrence.pattern,
192                     exchangelib.recurrence.AbsoluteYearlyPattern):
193         rr = "RRULE:FREQ=YEARLY;BYMONTH=%d;BYMONTHDAY=%d" % \
194                           (event.recurrence.pattern.month,
195                            event.recurrence.pattern.day_of_month)
196     elif isinstance(event.recurrence.pattern,
197                     exchangelib.recurrence.RelativeYearlyPattern):
198         rr = "RRULE:FREQ=YEARLY;BYMONTH=%d;BYDAY=%s" % \
199                           (event.recurrence.pattern.month,
200                            rr_daystr_monthly(event.recurrence.pattern))
201     else:
202         logger.error("Recurrence %s not supported" % event.recurrence)
203         return None
204     if isinstance(event.recurrence.boundary,
205                   exchangelib.recurrence.EndDatePattern):
206         rr += ";UNTIL={0:%Y}{0:%m}{0:%d}".format(event.recurrence.boundary.end)
207     elif isinstance(event.recurrence.boundary,
208                     exchangelib.recurrence.NoEndPattern):
209         pass #no end date to set
210     else:
211         logger.error("Recurrence %s not supported" % event.recurrence)
212         return None
213     return [rr]
214
215 def modify_recurring(ex_acct,gcal_acct,gcal_tz,
216                      events,master,gcal_id="primary"):
217     if master.modified_occurrences is not None:
218         for mod in master.modified_occurrences:
219             instance = get_gcal_recur_instance(gcal_acct,master.gcal_link,
220                                                mod.original_start,gcal_id)
221             if instance is None: #give up after first failure
222                 return
223             mod_event = get_ex_event_by_itemid(ex_acct.calendar,mod.item_id)
224             gevent = build_gcal_event_from_ex(mod_event,gcal_tz)
225             gevent = gcal_acct.events().update(calendarId=gcal_id,
226                                                eventId=instance.get('id'),
227                                                body=gevent,
228                                                sendUpdates="none").execute()
229             mod_event.gcal_link = gevent.get("id")
230             mod_event.save(update_fields=["gcal_link"])
231     if master.deleted_occurrences is not None:
232         for d in master.deleted_occurrences:
233             instance = get_gcal_recur_instance(gcal_acct,master.gcal_link,
234                                                d.start,gcal_id)
235             if instance is None: #give up after any failure
236                 return
237             if instance["status"] != "cancelled":
238                 instance["status"]="cancelled"
239                 gcal_acct.events().update(calendarId=gcal_id,
240                                           eventId=instance.get('id'),
241                                           body=instance,
242                                           sendUpdates="none").execute()
243
244 def build_gcal_event_from_ex(event,gcal_tz):
245     gevent={}
246     gevent["summary"]=event.subject
247     if event.is_all_day:
248         gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
249         gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
250     else:
251         gevent["end"]={"dateTime": event.end.astimezone(gcal_tz).isoformat(),
252                        "timeZone": str(gcal_tz)}
253         gevent["start"]={"dateTime": event.start.astimezone(gcal_tz).isoformat(),
254                          "timeZone": str(gcal_tz)}
255     if event.text_body is not None and event.text_body.strip() != '':
256         gevent["description"] = event.text_body
257     if event.location is not None:
258         gevent["location"] = event.location
259     gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
260     return gevent
261
262 def add_ex_to_gcal(ex_acct,
263                    gcal_acct,gcal_tz,events,
264                    added,
265                    gcal_id="primary"):
266     for ev_id in added:
267         event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
268         gevent = build_gcal_event_from_ex(event,gcal_tz)
269         if event.type=="RecurringMaster":
270             rr = rrule_from_ex(event,gcal_tz)
271             if rr is not None:
272                 gevent["recurrence"] = rr
273                 print(gevent)
274             else:
275                 logger.warning("Unable to set recurrence for %s" % event.item_id)
276                 continue #don't make the gcal event
277         gevent = gcal_acct.events().insert(calendarId=gcal_id,
278                                            body=gevent).execute()
279         event.gcal_link = gevent.get("id")
280         event.save(update_fields=["gcal_link"])
281         if event.type=="RecurringMaster" and (event.deleted_occurrences or \
282                                               event.modified_occurrences):
283             modify_recurring(ex_acct,gcal_acct,gcal_tz,
284                              events,event,gcal_id)
285             #changekey is updated by the above
286             event.refresh()
287         events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
288         
289 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
290     for ev_id in deleted:
291         if events[ev_id].gcal_link is not None:
292             gcal_acct.events().delete(calendarId=gcal_id,
293                                       eventId=events[ev_id].gcal_link,
294                                       sendUpdates="none").execute()
295
296 def update_ex_to_gcal(ex_acct,
297                       gcal_acct,gcal_tz,
298                       events,changed,
299                       gcal_id="primary"):
300     for ev_id in changed:
301         event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
302         gevent = build_gcal_event_from_ex(event,gcal_tz)
303         if event.type=="RecurringMaster":
304             rr = rrule_from_ex(event,gcal_tz)
305             if rr is not None:
306                 gevent["recurrence"] = rr
307                 if event.deleted_occurrences or \
308                    event.modified_occurrences:
309                     modify_recurring(ex_acct,gcal_acct,gcal_tz,
310                                      events,event,gcal_id)
311                     event.refresh() #changekey is updated by the above
312                     events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
313             else:
314                 logger.warning("Unable to set recurrence for %s" % event.item_id)
315                 continue #don't make the gcal event
316         gevent = gcal_acct.events().update(calendarId=gcal_id,
317                                                eventId=event.gcal_link,
318                                                body=gevent,
319                                                sendUpdates="none").execute()
320
321 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary"):
322     recur = 0
323     matched = 0
324     skipped = 0
325     for ev_id in events:
326         event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
327         if event.is_recurring:
328             recur += 1
329             continue
330         elif event.gcal_link is not None:
331             skipped += 1
332             continue
333         matches = gcal_acct.events().list(calendarId=gcal_id,
334                                           timeMin=event.start.isoformat(),
335                                           timeMax=event.end.isoformat()).execute()
336         for ge in matches['items']:
337             if ge['summary'].strip()==event.subject.strip():
338                 logger.info("Matching '%s' starting at %s" % (event.subject,
339                                                               event.start.isoformat()))
340                 event.gcal_link = ge['id']
341                 event.save(update_fields=["gcal_link"])
342                 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
343                 gevent = {}
344                 gevent["start"] = ge["start"]
345                 gevent["end"] = ge["end"]
346                 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
347                 try:
348                     gcal_acct.events().update(calendarId=gcal_id,
349                                               eventId=event.gcal_link,
350                                               body=gevent,
351                                               sendUpdates="none").execute()
352                 #this may fail if we don't own the event
353                 except googleapiclient.errors.HttpError as err:
354                     if err.resp.status == 403:
355                         pass
356                 matched += 1
357                 break
358     logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
359     
360 def get_gcal_cred():
361     #each such file can only store a single credential
362     storage = oauth2client.file.Storage(gcal_authpath)
363     gcal_credential = storage.get()
364     #if no credential found, or they're invalid (e.g. expired),
365     #then get a new one; pass --noauth_local_webserver on the command line
366     #if you don't want it to spawn a browser
367     if gcal_credential is None or gcal_credential.invalid:
368         gcal_credential = oauth2client.tools.run_flow(flow,
369                                                       storage,
370                                                       oauth2client.tools.argparser.parse_args())
371     return gcal_credential
372
373 def gcal_login():
374     gcal_credential = get_gcal_cred()
375     # Object to handle http requests; could add proxy details
376     http = httplib2.Http()
377     http = gcal_credential.authorize(http)
378     return apiclient.discovery.build('calendar', 'v3', http=http)
379
380 def get_gcal_timezone(gcal_account,calendarid="primary"):
381     gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
382     return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
383
384 def main():
385     try:
386         with open(cachepath,"rb") as f:
387             cache = pickle.load(f)
388     except FileNotFoundError:
389         cache = None
390
391     ex_account = ex_login("mv3@sanger.ac.uk",".gooswapper_exch_conf.dat")
392     current = get_ex_events(ex_account.calendar)
393
394     gcal_account = gcal_login()
395     gcal_tz = get_gcal_timezone(gcal_account)
396     
397     if cache is not None:
398         added,deleted,changed = ex_event_changes(cache,current)
399         add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,added)
400         #delete op needs the "cache" set, as that has the link ids in
401         #for events that are now deleted
402         del_ex_to_gcal(ex_account,gcal_account,cache,deleted)
403         update_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,changed)
404     else:
405         match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current)
406         
407     with open(cachepath,"wb") as f:
408         pickle.dump(current,f)
409
410 if __name__ == "__main__":
411     main()
412
413