chiark / gitweb /
e18da2f470c0d569ee7426aa6f1fc077c8b82746
[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_ex_cred(username="SANGER\mv3",password=None):
78     if password is None:
79         password = getpass.getpass(prompt="Password for user %s: " % username)
80     return exchangelib.ServiceAccount(username,password)
81
82 def ex_login(emailaddr,ad_cache_path=None):
83     global exchange_credential
84     autodiscover = True
85     if exchange_credential is None:
86         exchange_credential = get_ex_cred()
87     if ad_cache_path is not None:
88         try:
89             with open(ad_cache_path,"rb") as f:
90                 url,auth_type = pickle.load(f)
91                 autodiscover = False
92         except FileNotFoundError:
93             pass
94
95     if autodiscover:
96         ex_ac = exchangelib.Account(emailaddr,
97                                     credentials = exchange_credential,
98                                     autodiscover = autodiscover)
99         if ad_cache_path is not None:
100             cache=(ex_ac.protocol.service_endpoint,
101                    ex_ac.protocol.auth_type)
102             with open(ad_cache_path,"wb") as f:
103                 pickle.dump(cache,f)
104     else:
105         ex_conf = exchangelib.Configuration(service_endpoint=url,
106                                             credentials=exchange_credential,
107                                             auth_type=auth_type)
108         ex_ac = exchangelib.Account(emailaddr,
109                                     config=ex_conf,
110                                     autodiscover=False,
111                                     access_type=exchangelib.DELEGATE)
112
113     return ex_ac
114
115 def get_ex_events(calendar):
116     ans={}
117     for event in calendar.all().only('changekey','item_id','gcal_link'):
118         if event.item_id in ans:
119             logger.warning("Event item_id %s was duplicated!" % event.item_id)
120         ans[event.item_id] = CachedExEvent(event.changekey,event.gcal_link)
121     logger.info("%d events found" % len(ans))
122     return ans
123
124 def ex_event_changes(old,new):
125     olds = set(old.keys())
126     news = set(new.keys())
127     added = list(news-olds)
128     deleted = list(olds-news)
129     changed = []
130     #intersection - i.e. common to both sets
131     for event in olds & news:
132         if old[event].changekey != new[event].changekey:
133             changed.append(event)
134     logger.info("%d events updated, %d added, %d deleted" % (len(changed),
135                                                               len(added),
136                                                               len(deleted)))
137     return added, deleted, changed
138
139 #exchangelib gives us days in recurrence patterns as integers,
140 #RFC5545 wants SU,MO,TU,WE,TH,FR,SA
141 #it has a utility function to convert to Monday, Tuesday, ...
142 def rr_daystr_from_int(i):
143     return exchangelib.recurrence._weekday_to_str(i).upper()[:2]
144
145 def rrule_from_ex(event,gcal_tz):
146     if event.type != "RecurringMaster":
147         logger.error("Cannot make recurrence from not-recurring event")
148         return None
149     if event.recurrence is None:
150         logger.error("Empty recurrence structure")
151         return None
152     if isinstance(event.recurrence.pattern,
153                   exchangelib.recurrence.DailyPattern):
154         rr = "RRULE:FREQ=DAILY;INTERVAL=%d" % event.recurrence.pattern.interval
155     elif isinstance(event.recurrence.pattern,
156                     exchangelib.recurrence.WeeklyPattern):
157         rr = "RRULE:FREQ=WEEKLY;INTERVAL=%d;BYDAY=%s;WKST=%s" % \
158                           (event.recurrence.pattern.interval,
159                            ",".join([rr_daystr_from_int(x) for x in event.recurrence.pattern.weekdays]),
160                            rr_daystr_from_int(event.recurrence.pattern.first_day_of_week) )
161     else:
162         logger.error("Recurrence %s not supported" % event.recurrence)
163         return None
164     if isinstance(event.recurrence.boundary,
165                   exchangelib.recurrence.EndDatePattern):
166         rr += ";UNTIL={0:%Y}{0:%m}{0:%d}".format(event.recurrence.boundary.end)
167     else:
168         logger.error("Recurrence %s not supported" % event.recurrence)
169         return None
170     if event.modified_occurrences is not None or \
171        event.deleted_occurrences is not None:
172         logger.warning("Modified/Deleted recurrences not supported")
173     return [rr]
174
175 def build_gcal_event_from_ex(event,gcal_tz):
176     gevent={}
177     gevent["summary"]=event.subject
178     if event.is_all_day:
179         gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
180         gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
181     else:
182         gevent["end"]={"dateTime": event.end.astimezone(gcal_tz).isoformat(),
183                        "timeZone": str(gcal_tz)}
184         gevent["start"]={"dateTime": event.start.astimezone(gcal_tz).isoformat(),
185                          "timeZone": str(gcal_tz)}
186     if event.text_body is not None and event.text_body.strip() != '':
187         gevent["description"] = event.text_body
188     if event.location is not None:
189         gevent["location"] = event.location
190     gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
191     return gevent
192
193 def add_ex_to_gcal(ex_acct,
194                    gcal_acct,gcal_tz,events,
195                    added,
196                    gcal_id="primary"):
197     for ev_id in added:
198         event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
199         gevent = build_gcal_event_from_ex(event,gcal_tz)
200         if event.type=="RecurringMaster":
201             rr = rrule_from_ex(event,gcal_tz)
202             if rr is not None:
203                 gevent["recurrence"] = rr
204                 print(gevent)
205             else:
206                 logger.warning("Unable to set recurrence for %s" % event.item_id)
207                 continue #don't make the gcal event
208         gevent = gcal_acct.events().insert(calendarId=gcal_id,
209                                            body=gevent).execute()
210         event.gcal_link = gevent.get("id")
211         event.save(update_fields=["gcal_link"])
212         events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
213
214 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
215     for ev_id in deleted:
216         if events[ev_id].gcal_link is not None:
217             gcal_acct.events().delete(calendarId=gcal_id,
218                                       eventId=events[ev_id].gcal_link,
219                                       sendUpdates="none").execute()
220
221 def update_ex_to_gcal(ex_acct,
222                       gcal_acct,gcal_tz,
223                       events,changed,
224                       gcal_id="primary"):
225     for ev_id in changed:
226         event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
227         if not event.is_recurring:
228             gevent = build_gcal_event_from_ex(event,gcal_tz)
229             gevent = gcal_acct.events().update(calendarId=gcal_id,
230                                                eventId=event.gcal_link,
231                                                body=gevent,
232                                                sendUpdates="none").execute()
233         else:
234             logger.warning("recurring events not yet supported")
235
236 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary"):
237     recur = 0
238     matched = 0
239     skipped = 0
240     for ev_id in events:
241         event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
242         if event.is_recurring:
243             recur += 1
244             continue
245         elif event.gcal_link is not None:
246             skipped += 1
247             continue
248         matches = gcal_acct.events().list(calendarId=gcal_id,
249                                           timeMin=event.start.isoformat(),
250                                           timeMax=event.end.isoformat()).execute()
251         for ge in matches['items']:
252             if ge['summary'].strip()==event.subject.strip():
253                 logger.info("Matching '%s' starting at %s" % (event.subject,
254                                                               event.start.isoformat()))
255                 event.gcal_link = ge['id']
256                 event.save(update_fields=["gcal_link"])
257                 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
258                 gevent = {}
259                 gevent["start"] = ge["start"]
260                 gevent["end"] = ge["end"]
261                 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
262                 try:
263                     gcal_acct.events().update(calendarId=gcal_id,
264                                               eventId=event.gcal_link,
265                                               body=gevent,
266                                               sendUpdates="none").execute()
267                 #this may fail if we don't own the event
268                 except googleapiclient.errors.HttpError as err:
269                     if err.resp.status == 403:
270                         pass
271                 matched += 1
272                 break
273     logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
274     
275 def get_gcal_cred():
276     #each such file can only store a single credential
277     storage = oauth2client.file.Storage(gcal_authpath)
278     gcal_credential = storage.get()
279     #if no credential found, or they're invalid (e.g. expired),
280     #then get a new one; pass --noauth_local_webserver on the command line
281     #if you don't want it to spawn a browser
282     if gcal_credential is None or gcal_credential.invalid:
283         gcal_credential = oauth2client.tools.run_flow(flow,
284                                                       storage,
285                                                       oauth2client.tools.argparser.parse_args())
286     return gcal_credential
287
288 def gcal_login():
289     gcal_credential = get_gcal_cred()
290     # Object to handle http requests; could add proxy details
291     http = httplib2.Http()
292     http = gcal_credential.authorize(http)
293     return apiclient.discovery.build('calendar', 'v3', http=http)
294
295 def get_gcal_timezone(gcal_account,calendarid="primary"):
296     gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
297     return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
298
299 def main():
300     try:
301         with open(cachepath,"rb") as f:
302             cache = pickle.load(f)
303     except FileNotFoundError:
304         cache = None
305
306     ex_account = ex_login("mv3@sanger.ac.uk",".gooswapper_exch_conf.dat")
307     current = get_ex_events(ex_account.calendar)
308
309     gcal_account = gcal_login()
310     gcal_tz = get_gcal_timezone(gcal_account)
311     
312     if cache is not None:
313         added,deleted,changed = ex_event_changes(cache,current)
314         add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,added)
315         #delete op needs the "cache" set, as that has the link ids in
316         #for events that are now deleted
317         del_ex_to_gcal(ex_account,gcal_account,cache,deleted)
318         update_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,changed)
319     else:
320         match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current)
321         
322     with open(cachepath,"wb") as f:
323         pickle.dump(current,f)
324
325 if __name__ == "__main__":
326     main()
327
328