chiark / gitweb /
tidy up the exchange extended property
[gooswapper] / gooswapper.py
1 #!/usr/bin/env python3
2
3 import sys
4 import getpass
5 import os
6 import pickle
7 import logging
8 logger = logging.getLogger('gooswapper')
9 logger.setLevel(logging.INFO)
10 consolelog = logging.StreamHandler()
11 consolelog.setLevel(logging.INFO)
12 logformatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
13 consolelog.setFormatter(logformatter)
14 logger.addHandler(consolelog)
15 #We can't use this, because that way all the libraries' logs spam us
16 #logging.basicConfig(level=logging.INFO)
17
18 #Exchange-related library
19 sys.path.append("/upstreams/exchangelib")
20 import exchangelib
21
22 #Google calendar-api libraries
23 import httplib2
24 import apiclient.discovery
25 import oauth2client
26 import oauth2client.file
27 import oauth2client.client
28
29 #Not sure what the distribution approach here is...
30 gcal_client_id = '805127902516-ptbbtgpq9o8pjr6r3k6hsm60j589o85u.apps.googleusercontent.com'
31 gcal_client_secret = '8hpdxV3MauorryTDoZ1YK8JO'
32
33 #scope URL for r/w calendar access
34 scope = 'https://www.googleapis.com/auth/calendar'
35 #flow object, for doing OAuth2.0 stuff
36 flow = oauth2client.client.OAuth2WebServerFlow(gcal_client_id,
37                                                gcal_client_secret,
38                                                scope)
39
40
41 gcal_authpath=".gooswap_gcal_creds.dat"
42
43 cachepath=".gooswapcache"
44
45 exchange_credential = None
46
47 class ex_gcal_link(exchangelib.ExtendedProperty):
48     distinguished_property_set_id = 'PublicStrings'
49     property_name = "google calendar event id"
50     property_type = 'String'
51
52 exchangelib.CalendarItem.register('gcal_link',ex_gcal_link)
53
54 #see docs for exchangelib.UID for why this is needed
55 class GlobalObjectId(exchangelib.ExtendedProperty):
56      distinguished_property_set_id = 'Meeting'
57      property_id = 3
58      property_type = 'Binary'
59
60 exchangelib.CalendarItem.register('global_object_id', GlobalObjectId)
61
62 def get_ex_event_by_uid(calendar,uid):
63     return calendar.get(global_object_id=GlobalObjectId(exchangelib.UID(uid)))
64
65 def get_ex_event_by_id_and_changekey(acct,itemid,changekey):
66     l=list(acct.fetch([(itemid,changekey)]))
67     return list(acct.fetch([(itemid,changekey)]))[0]
68
69 def get_ex_cred(username="SANGER\mv3",password=None):
70     if password is None:
71         password = getpass.getpass(prompt="Password for user %s: " % username)
72     return exchangelib.ServiceAccount(username,password)
73 #    return exchangelib.Credentials(username,password)
74
75 def ex_login(emailaddr,autodiscover=True):
76     global exchange_credential
77     if exchange_credential is None:
78         exchange_credential = get_ex_cred()
79     return exchangelib.Account(emailaddr,
80                                credentials = exchange_credential,
81                                autodiscover = autodiscover)
82
83 def get_ex_events(calendar):
84     ans={}
85     itemids={}
86     for event in calendar.all().only('uid','changekey','item_id','gcal_link'):
87         if event.gcal_link is not None:
88 #            event.delete()
89             continue
90         if event.uid in ans:
91             logger.warning("Event uid %s was duplicated!" % event.uid)
92         ans[event.uid] = event.changekey
93         itemids[event.uid] = event.item_id
94     logger.info("%d events found" % len(ans))
95     return (ans,itemids)
96
97 def ex_event_changes(old,new):
98     olds = set(old.keys())
99     news = set(new.keys())
100     added = list(news-olds)
101     deleted = list(olds-news)
102     changed = []
103     #intersection - i.e. common to both sets
104     for event in olds & news:
105         if old[event] != new[event]:
106             changed.append(event)
107     logger.info("%d events updated, %d added, %d deleted" % (len(changed),
108                                                               len(added),
109                                                               len(deleted)))
110     return added, deleted, changed
111
112 #XXX doesn't work - cf https://github.com/ecederstrand/exchangelib/issues/492
113 def add_ex_to_gcal_needs_ev_id(ex_cal,events):
114     for ev_id in events:
115         print(ev_id)
116         event = get_ex_event_by_uid(ex_cal,ev_id)
117         event.gcal_link = "Testing"
118         event.save()
119
120 def add_ex_to_gcal(ex_acct,
121                    gcal_acct,gcal_tz,events,
122                    itemids,added,
123                    gcal_id="primary"):
124     for ev_id in added:
125         event = get_ex_event_by_id_and_changekey(ex_acct,
126                                                  itemids[ev_id],events[ev_id])
127         if event.is_all_day:
128             gevent={}
129             gevent["summary"]=event.subject
130             gevent["end"]={"date": str(event.end.astimezone(gcal_tz).date())}
131             gevent["start"]={"date": str(event.start.astimezone(gcal_tz).date())}
132             if event.text_body.strip() != '':
133                 gevent["description"] = event.text_body
134             if event.location is not None:
135                 gevent["location"] = event.location
136             gevent["extended_properties"]={"shared": {"ex_id": event.item_id}}
137             gevent=gcal_acct.events().insert(calendarId=gcal_id, body=gevent).execute()
138             event.gcal_link = gevent.get("id")
139             event.save()
140             events[event.uid] = event.changekey
141         else:
142             logger.warning("only all-day events supported")
143             
144 def get_gcal_cred():
145     #each such file can only store a single credential
146     storage = oauth2client.file.Storage(gcal_authpath)
147     gcal_credential = storage.get()
148     #if no credential found, or they're invalid (e.g. expired),
149     #then get a new one; pass --noauth_local_webserver on the command line
150     #if you don't want it to spawn a browser
151     if gcal_credential is None or gcal_credential.invalid:
152         gcal_credential = oauth2client.tools.run_flow(flow,
153                                                       storage,
154                                                       oauth2client.tools.argparser.parse_args())
155     return gcal_credential
156
157 def gcal_login():
158     gcal_credential = get_gcal_cred()
159     # Object to handle http requests; could add proxy details
160     http = httplib2.Http()
161     http = gcal_credential.authorize(http)
162     return apiclient.discovery.build('calendar', 'v3', http=http)
163
164 def get_gcal_timezone(gcal_account,calendarid="primary"):
165     gcal = gcal_account.calendars().get(calendarId=calendarid).execute()
166     return exchangelib.EWSTimeZone.timezone(gcal['timeZone'])
167
168 def main():
169     try:
170         with open(cachepath,"rb") as f:
171             cache = pickle.load(f)
172     except FileNotFoundError:
173         cache = None
174
175     ex_account = ex_login("mv3@sanger.ac.uk")
176     current,itemids = get_ex_events(ex_account.calendar)
177
178     gcal_account = gcal_login()
179     gcal_tz = get_gcal_timezone(gcal_account)
180     
181     if cache is not None:
182         added,deleted,changed = ex_event_changes(cache,current)
183         add_ex_to_gcal(ex_account,gcal_account,gcal_tz,current,
184                        itemids,added)
185         
186     with open(cachepath,"wb") as f:
187         pickle.dump(current,f)
188
189 if __name__ == "__main__":
190     main()
191
192