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