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)
19 #Exchange-related library
20 sys.path.append("/upstreams/exchangelib")
23 #Google calendar-api libraries
25 import apiclient.discovery
27 import oauth2client.file
28 import oauth2client.client
29 import googleapiclient.errors
31 #Not sure what the distribution approach here is...
32 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
33 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
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,
43 gcal_authpath=".gooswap_gcal_creds.dat"
45 cachepath=".gooswapcache"
47 exchange_credential = None
49 CachedExEvent=collections.namedtuple('CachedExEvent',
50 ['changekey','gcal_link'])
52 class ex_gcal_link(exchangelib.ExtendedProperty):
53 distinguished_property_set_id = 'PublicStrings'
54 property_name = "google calendar event id"
55 property_type = 'String'
57 exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
59 def get_ex_event_by_itemid(calendar,itemid):
60 return calendar.get(item_id=itemid)
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]
66 def get_ex_cred(username="SANGER\mv3",password=None):
68 password = getpass.getpass(prompt="Password for user %s: " % username)
69 return exchangelib.ServiceAccount(username,password)
71 def ex_login(emailaddr,ad_cache_path=None):
72 global exchange_credential
74 if exchange_credential is None:
75 exchange_credential = get_ex_cred()
76 if ad_cache_path is not None:
78 with open(ad_cache_path,"rb") as f:
79 url,auth_type = pickle.load(f)
81 except FileNotFoundError:
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:
94 ex_conf = exchangelib.Configuration(service_endpoint=url,
95 credentials=exchange_credential,
97 ex_ac = exchangelib.Account(emailaddr,
100 access_type=exchangelib.DELEGATE)
104 def get_ex_events(calendar):
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))
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)
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),
126 return added, deleted, changed
128 def build_gcal_event_from_ex(event,gcal_tz):
130 gevent["summary"]=event.subject
132 gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
133 gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
135 gevent["end"]={"dateTime": event.end.isoformat(),
136 "timeZone": event.end.tzname()}
137 gevent["start"]={"dateTime": event.start.isoformat(),
138 "timeZone": event.start.tzname()}
139 if event.text_body is not None and event.text_body.strip() != '':
140 gevent["description"] = event.text_body
141 if event.location is not None:
142 gevent["location"] = event.location
143 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
146 def add_ex_to_gcal(ex_acct,
147 gcal_acct,gcal_tz,events,
151 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
152 if not event.is_recurring:
153 gevent = build_gcal_event_from_ex(event,gcal_tz)
154 gevent = gcal_acct.events().insert(calendarId=gcal_id,
155 body=gevent).execute()
156 event.gcal_link = gevent.get("id")
158 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
160 logger.warning("recurring events not yet supported")
162 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
163 for ev_id in deleted:
164 if events[ev_id].gcal_link is not None:
165 gcal_acct.events().delete(calendarId=gcal_id,
166 eventId=events[ev_id].gcal_link,
167 sendUpdates="none").execute()
169 def update_ex_to_gcal(ex_acct,
173 for ev_id in changed:
174 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
175 if not event.is_recurring:
176 gevent = build_gcal_event_from_ex(event,gcal_tz)
177 gevent = gcal_acct.events().update(calendarId=gcal_id,
178 eventId=event.gcal_link,
180 sendUpdates="none").execute()
182 logger.warning("recurring events not yet supported")
184 def match_ex_to_gcal(ex_acct,gcal_acct,gcal_tz,events,gcal_id="primary"):
189 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
190 if event.is_recurring:
193 elif event.gcal_link is not None:
196 matches = gcal_acct.events().list(calendarId=gcal_id,
197 timeMin=event.start.isoformat(),
198 timeMax=event.end.isoformat()).execute()
199 for ge in matches['items']:
200 if ge['summary'].strip()==event.subject.strip():
201 logger.info("Matching '%s' starting at %s" % (event.subject,
202 event.start.isoformat()))
203 event.gcal_link = ge['id']
204 event.save(update_fields=["gcal_link"])
205 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
207 gevent["start"] = ge["start"]
208 gevent["end"] = ge["end"]
209 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
211 gcal_acct.events().update(calendarId=gcal_id,
212 eventId=event.gcal_link,
214 sendUpdates="none").execute()
215 #this may fail if we don't own the event
216 except googleapiclient.errors.HttpError as err:
217 if err.resp.status == 403:
221 logger.info("Matched %d events, skipped %d with existing link, and %d recurring ones" % (matched,skipped,recur))
224 #each such file can only store a single credential
225 storage = oauth2client.file.Storage(gcal_authpath)
226 gcal_credential = storage.get()
227 #if no credential found, or they're invalid (e.g. expired),
228 #then get a new one; pass --noauth_local_webserver on the command line
229 #if you don't want it to spawn a browser
230 if gcal_credential is None or gcal_credential.invalid:
231 gcal_credential = oauth2client.tools.run_flow(flow,
233 oauth2client.tools.argparser.parse_args())
234 return gcal_credential
237 gcal_credential = get_gcal_cred()
238 # Object to handle http requests; could add proxy details
239 http = httplib2.Http()
240 http = gcal_credential.authorize(http)
241 return apiclient.discovery.build('calendar', 'v3', http=http)
243 def get_gcal_timezone(gcal_account,calendarid="primary"):
244 gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
245 return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
249 with open(cachepath,"rb") as f:
250 cache = pickle.load(f)
251 except FileNotFoundError:
254 ex_account = ex_login("mv3@sanger.ac.uk",".gooswapper_exch_conf.dat")
255 current = get_ex_events(ex_account.calendar)
257 gcal_account = gcal_login()
258 gcal_tz = get_gcal_timezone(gcal_account)
260 if cache is not None:
261 added,deleted,changed = ex_event_changes(cache,current)
262 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,added)
263 #delete op needs the "cache" set, as that has the link ids in
264 #for events that are now deleted
265 del_ex_to_gcal(ex_account,gcal_account,cache,deleted)
266 update_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,changed)
268 match_ex_to_gcal(ex_account,gcal_account,gcal_tz,current)
270 with open(cachepath,"wb") as f:
271 pickle.dump(current,f)
273 if __name__ == "__main__":