-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcalendar
executable file
·238 lines (174 loc) · 7.44 KB
/
calendar
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
#!/usr/bin/env python
# -*- coding: utf-8
from sys import stdin, stdout, argv
from os import path
import re
import email
import base64
import argparse
import httplib2
from icalendar import Calendar, Event
from datetime import datetime
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from apiclient.discovery import build
from apiclient.errors import HttpError
import logging
logging.basicConfig()
def dictmerge(*args):
res = {}
for d in args:
for (k,v) in d.iteritems():
res[k] = v
return res
class GCal:
DEFAULT_BASE_PATH = '.'
DEFAULT_CALENDAR_NAME = 'Jobb'
DEFAULT_CREDENTIALS_FILE = 'client_credentials_storage.json'
DEFAULT_SECRETS_FILE = 'client_secrets.json'
def __init__(self, *args, **kwargs):
base_dir = path.expanduser(kwargs.get('base_path', GCal.DEFAULT_BASE_PATH))
self.calendar_name = kwargs.get('calendar_name', GCal.DEFAULT_CALENDAR_NAME)
self.credential_storage_file = kwargs.get('credential_storage_file', base_dir + GCal.DEFAULT_CREDENTIALS_FILE)
self.client_secrets_file = kwargs.get('client_secrets_file', base_dir + GCal.DEFAULT_SECRETS_FILE)
self._credentials = self._login()
self._service = build('calendar', 'v3', http=self._credentials.authorize(httplib2.Http()))
self._tz = 'Europe/Oslo'
def _login(self):
storage = Storage(self.credential_storage_file)
flow = flow_from_clientsecrets(self.client_secrets_file,
scope='https://www.googleapis.com/auth/calendar',
redirect_uri='https://www.hwikene.net/oauth2callback')
creds = storage.get()
# first time authentication
if creds is None:
print "This is your first time using this application, so you will"
print "have to give it permission to access your calendar first."
auth_uri = flow.step1_get_authorize_url()
print auth_uri
print "Click the link and paste the code found in the return URL here:",
code = stdin.readline().strip()
creds = flow.step2_exchange(code)
storage.put(creds)
# refresh an old access token
elif creds.access_token_expired:
print "Access token expired, trying to refresh"
creds.refresh(httplib2.Http())
storage.put(creds)
return creds
# should still be valid
else:
print "Token still valid, using stored access token"
return creds
def _extract_ical_data(self, raw_ical):
def get_rrules(ev):
if ev.get('rrule'):
return [ 'RRULE:' + ev.get('rrule').to_ical() ]
return []
cal = Calendar.from_ical(raw_ical)
for event in cal.walk('vevent'):
yield {
'body': {
'summary': event.get('summary').title(),
'description': unicode(event.get('description')),
'start': { 'dateTime' : event.get('dtstart').dt.strftime('%Y-%m-%dT%H:%M:%S'), 'timeZone': self._tz },
'end': { 'dateTime': event.get('dtend').dt.strftime('%Y-%m-%dT%H:%M:%S'), 'timeZone': self._tz },
'location': event.get('location').title(),
'status': event.get('status').lower(),
'id': event.get('uid').replace('-', '').lower(),
'recurrence': get_rrules(event)
}
}
def _find_calendar_by_name(self):
items = self._service.calendarList().list().execute()['items']
items_filtered = [e for e in items if e['summary'] == self.calendar_name]
if len(items_filtered) != 1:
return None
return items_filtered[0]
def _calendar_not_found(self):
items = self._service.calendarList().list().execute()['items']
print "Could not find a calendar with the name '%s'. Your options are: %s" % (
self.calendar_name, ', '.join([e['summary'] for e in items]))
def _create_gcal_event(self, event):
calendar_obj = self._find_calendar_by_name()
if calendar_obj is None:
self._calendar_not_found()
return
data = dictmerge({ 'calendarId': calendar_obj['id'] }, event)
self._service.events().insert(**data).execute()
print "Created event '%s'" % event['body']['summary']
def _update_gcal_event(self, found_event, new_event_data):
def merge_properties(new_obj, old_obj):
for key in new_obj.keys():
if not key in old_obj:
continue
if isinstance(new_obj[key], dict):
merge_properties(new_obj[key], old_obj[key])
elif isinstance(new_obj[key], basestring):
new_obj[key] = old_obj[key]
return new_obj
calendar_obj = self._find_calendar_by_name()
if calendar_obj is None:
self._calendar_not_found()
return
merged = merge_properties(found_event, new_event_data['body'])
obj = dictmerge({
'calendarId': calendar_obj['id'],
'eventId': found_event['id']
}, { 'body': merged })
self._service.events().update(**obj).execute()
print "Updated event '%s'" % merged['summary']
def _create_or_update_gcal_event(self, event):
calendar_obj = self._find_calendar_by_name()
data = {
'calendarId': calendar_obj['id'],
'eventId': event['body']['id']
}
found = None
try:
found = self._service.events().get(**data).execute()
except HttpError as error:
if error.resp.status != 404:
raise error
if found:
self._update_gcal_event(found, event)
else:
self._create_gcal_event(event)
def handle_event(self, raw_ical):
for event in self._extract_ical_data(raw_ical):
self._create_or_update_gcal_event(event)
class EMailParser:
def __init__(self, fd):
self._file = fd
def parse(self):
self._email = email.message_from_file(self._file)
return self._email
def walk_calendar_events(self):
for part in self._email.walk():
if part.get_content_type() == 'text/calendar':
if part['Content-Transfer-Encoding'] == 'base64':
yield base64.b64decode(part.get_payload())
else:
yield part.get_payload()
def cmdline_args():
parser = argparse.ArgumentParser(description='Extract calendar events from emails and put into Google Calendar.')
parser.add_argument('-p', '--path', default='~/.itera_calendar/',
help='The path where the script looks for credentials files. Defaults to ~/.itera_calendar/')
parser.add_argument('file', type=str, nargs='?', default=None, help='A raw email file to read')
return parser.parse_args()
if __name__ == '__main__':
args = cmdline_args()
if args.file is not None and path.exists(args.file):
mail = EMailParser(open(args.file, 'r'))
elif len(argv) == 2:
print "File '%s' does not exist!" % args.file
exit(1)
else:
mail = EMailParser(stdin)
mail.parse()
events = list(mail.walk_calendar_events())
if events:
cal = GCal(base_path=args.path)
for event in events:
cal.handle_event(event)
exit(0)