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
30 #Not sure what the distribution approach here is...
31 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
32 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
34 #scope URL for r/w calendar access
35 scope = 'https://www.googleapis.com/auth/calendar'
36 #flow object, for doing OAuth2.0 stuff
37 flow = oauth2client.client.OAuth2WebServerFlow(gcal_client_id,
42 gcal_authpath=".gooswap_gcal_creds.dat"
44 cachepath=".gooswapcache"
46 exchange_credential = None
48 CachedExEvent=collections.namedtuple('CachedExEvent',
49 ['changekey','gcal_link'])
51 class ex_gcal_link(exchangelib.ExtendedProperty):
52 distinguished_property_set_id = 'PublicStrings'
53 property_name = "google calendar event id"
54 property_type = 'String'
56 exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
58 def get_ex_event_by_itemid(calendar,itemid):
59 return calendar.get(item_id=itemid)
61 def get_ex_event_by_id_and_changekey(acct,itemid,changekey):
62 l=list(acct.fetch([(itemid,changekey)]))
63 return list(acct.fetch([(itemid,changekey)]))[0]
65 def get_ex_cred(username="SANGER\mv3",password=None):
67 password = getpass.getpass(prompt="Password for user %s: " % username)
68 return exchangelib.ServiceAccount(username,password)
70 def ex_login(emailaddr,ad_cache_path=None):
71 global exchange_credential
73 if exchange_credential is None:
74 exchange_credential = get_ex_cred()
75 if ad_cache_path is not None:
77 with open(ad_cache_path,"rb") as f:
78 url,auth_type = pickle.load(f)
80 except FileNotFoundError:
84 ex_ac = exchangelib.Account(emailaddr,
85 credentials = exchange_credential,
86 autodiscover = autodiscover)
87 if ad_cache_path is not None:
88 cache=(ex_ac.protocol.service_endpoint,
89 ex_ac.protocol.auth_type)
90 with open(ad_cache_path,"wb") as f:
93 ex_conf = exchangelib.Configuration(service_endpoint=url,
94 credentials=exchange_credential,
96 ex_ac = exchangelib.Account(emailaddr,
99 access_type=exchangelib.DELEGATE)
103 def get_ex_events(calendar):
105 for event in calendar.all().only('changekey','item_id','gcal_link'):
106 if event.item_id in ans:
107 logger.warning("Event item_id %s was duplicated!" % event.item_id)
108 ans[event.item_id] = CachedExEvent(event.changekey,event.gcal_link)
109 logger.info("%d events found" % len(ans))
112 def ex_event_changes(old,new):
113 olds = set(old.keys())
114 news = set(new.keys())
115 added = list(news-olds)
116 deleted = list(olds-news)
118 #intersection - i.e. common to both sets
119 for event in olds & news:
120 if old[event].changekey != new[event].changekey:
121 changed.append(event)
122 logger.info("%d events updated, %d added, %d deleted" % (len(changed),
125 return added, deleted, changed
127 def add_ex_to_gcal(ex_acct,
128 gcal_acct,gcal_tz,events,
132 event = get_ex_event_by_itemid(ex_acct.calendar,ev_id)
133 if not event.is_recurring:
135 gevent["summary"]=event.subject
137 gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
138 gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
140 gevent["end"]={"dateTime": event.end.isoformat(),
141 "timeZone": event.end.tzname()}
142 gevent["start"]={"dateTime": event.start.isoformat(),
143 "timeZone": event.start.tzname()}
144 if event.text_body.strip() != '':
145 gevent["description"] = event.text_body
146 if event.location is not None:
147 gevent["location"] = event.location
148 gevent["extendedProperties"]={"shared": {"ex_id": event.item_id}}
149 gevent=gcal_acct.events().insert(calendarId=gcal_id, body=gevent).execute()
150 event.gcal_link = gevent.get("id")
152 events[event.item_id] = events[event.item_id]._replace(changekey=event.changekey,gcal_link=event.gcal_link)
154 logger.warning("only all-day events supported")
156 def del_ex_to_gcal(ex_acct, gcal_acct, events, deleted, gcal_id="primary"):
157 for ev_id in deleted:
158 if events[ev_id].gcal_link is not None:
159 gcal_acct.events().delete(calendarId=gcal_id,
160 eventId=events[ev_id].gcal_link,
161 sendUpdates="none").execute()
164 #each such file can only store a single credential
165 storage = oauth2client.file.Storage(gcal_authpath)
166 gcal_credential = storage.get()
167 #if no credential found, or they're invalid (e.g. expired),
168 #then get a new one; pass --noauth_local_webserver on the command line
169 #if you don't want it to spawn a browser
170 if gcal_credential is None or gcal_credential.invalid:
171 gcal_credential = oauth2client.tools.run_flow(flow,
173 oauth2client.tools.argparser.parse_args())
174 return gcal_credential
177 gcal_credential = get_gcal_cred()
178 # Object to handle http requests; could add proxy details
179 http = httplib2.Http()
180 http = gcal_credential.authorize(http)
181 return apiclient.discovery.build('calendar', 'v3', http=http)
183 def get_gcal_timezone(gcal_account,calendarid="primary"):
184 gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
185 return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
189 with open(cachepath,"rb") as f:
190 cache = pickle.load(f)
191 except FileNotFoundError:
194 ex_account = ex_login("mv3@sanger.ac.uk",".gooswapper_exch_conf.dat")
195 current = get_ex_events(ex_account.calendar)
197 gcal_account = gcal_login()
198 gcal_tz = get_gcal_timezone(gcal_account)
200 if cache is not None:
201 added,deleted,changed = ex_event_changes(cache,current)
202 add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,added)
203 #delete op needs the "cache" set, as that has the link ids in
204 #for events that are now deleted
205 del_ex_to_gcal(ex_account,gcal_account,cache,deleted)
207 with open(cachepath,"wb") as f:
208 pickle.dump(current,f)
210 if __name__ == "__main__":