-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcalutils.py
345 lines (306 loc) · 12.4 KB
/
gcalutils.py
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
'''
module : Google Calendar API Utilities
provides classes/functions helpful for managing our Google
calendars via their API
'''
from __future__ import print_function
import httplib2
import os
from apiclient import discovery
import oauth2client
from oauth2client import client
from oauth2client import tools
import datetime
try:
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
flags = None
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/calendar-python-webapp.json
SCOPES = 'https://www.googleapis.com/auth/calendar'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'COS 333 Assignment Calendars'
'''
function : get_credentials()
-Gets valid user credentials from storage.
-If nothing has been stored, or if the stored credentials are invalid,
the OAuth2 flow is completed to obtain the new credentials.
Returns:
Credentials, the obtained credential.
'''
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,
'calendar-python-webapp.json')
store = oauth2client.file.Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
if flags:
credentials = tools.run_flow(flow, store, flags)
else: # Needed only for compatibility with Python 2.6
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
'''
function : new_calendar()
creates a new Google Calendar on the account associated with
our credentials (should be [email protected] /p chrismoretti)
inputs :
title : title (typically a String like "MAE 433")
descr : description (typically a String like "Problem Set
Calendar for MAE 433")
outputs :
new_created_cal : a dictionary representation of the newly
created calendar, or None if title already
taken
'''
def new_calendar(title, descr):
#princeton_orange = "#FF8F00"
new_created_cal = None
if (get_calendar(title) == None):
new_cal = {
"kind": "calendar#calendar", # Type of the resource ("calendar#calendar").
"description": descr, # Description of the calendar. Optional.
"summary": title, # Title of the calendar.
#"etag": "A String", # ETag of the resource.
"location": "Princeton, NJ, USA", # Geographic location of the calendar as free-form text. Optional.
"timeZone": "America/New_York", # The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) Optional.
#"id": "A String", # Identifier of the calendar. To retrieve IDs call the calendarList.list() method.
}
#Programtically create a new calendar using the insert()
# from calendars() request
#FORMAT MUST BE A DICT, NOT JSON, AND THEREFORE NO COMMENTS
new_cal_req = service.calendars().insert(body=new_cal)
new_created_cal = new_cal_req.execute()
return new_created_cal
'''
function : get_calendar()
retrieve an existing Google Calendar on the account associated with
our credentials (should be [email protected] /p chrismoretti)
inputs :
title : title (typically a String like "MAE 433")
outputs :
cal : a dictionary representation of the located
calendar, or None if no calendar with this title
exists
'''
def get_calendar(title):
#HTTP request for a list of the user's calendars
usr_cals_req = service.calendarList().list()
#Execute the request, returns data in an object we call usr_cals
usr_cals = usr_cals_req.execute()
#Extract a particular calendar id by name
calid = None
calname = title
for i in usr_cals['items']:
if (i['summary'] == calname):
calid = i['id']
break
#Use the extracted id to get the calender object via the get() request
if (calid != None):
cal_byid_req = service.calendarList().get(calendarId=calid)
cal = cal_byid_req.execute()
return cal
else:
return None
'''
function : add_event()
adds an event with the specified information to a particular
calendar
inputs:
calname : name of calendar to add event to (string)
title : title of event (string)
location : location of event (string)
descr : description of event (string)
start : start time (formatted string)
end : end time (formatted string)
outputs:
event : dictionary representation of the newly created
event, or None if calendar does not exist
'''
def add_event(calname,title,location, descr, start, end):
event = None
calendar = get_calendar(calname)
if (calendar != None):
new_event = {
'summary': title,
'location': location,
'description': descr,
'start': {
'dateTime': start,
'timeZone': 'America/New_York',
},
'end': {
'dateTime': end,
'timeZone': 'America/New_York',
},
#'recurrence': [
# 'RRULE:FREQ=DAILY;COUNT=2'
#],
#'attendees': [
# {'email': '[email protected]'},
# {'email': '[email protected]'},
#],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
add_event_req = service.events().insert(calendarId=calendar['id'], body=new_event)
event = add_event_req.execute()
return event
'''
function main()
tester client that shows basic usage of the Google Calendar API.
Creates a Google Calendar API service object and outputs a list of the next
10 events on the user's calendar.
'''
def main():
#Creates a Google Calendar API service object from our
#credentials
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
service = discovery.build('calendar', 'v3', http=http)
#MY CHANGES
print ("--------------------------------")
print ("NAMES OF ALL THE USER'S CALENDARS")
print ("--------------------------------")
#HTTP request for a list of the user's calendars
usr_cals_req = service.calendarList().list()
#Execute the request, returns data in an object we call usr_cals
usr_cals = usr_cals_req.execute()
#Iterate over the "items" field of usr_cals and print the "summary"
#field of each item, which corresponds to printing the name of each
#calendar
for i in usr_cals['items']:
print (i['summary'])
print ("--------------------------------")
print ("FINDING/FETCHING A USER'S CALENDAR BY NAME/ID")
print ("--------------------------------")
#Extract a particular calendar id by name
calid = None
calname = 'new calendar'
for i in usr_cals['items']:
if (i['summary'] == calname):
calid = i['id']
break
#Use the extracted id to get the calender object via the get() request
if (calid != None):
cal_byid_req = service.calendarList().get(calendarId=calid)
cal_byid = cal_byid_req.execute()
print ("Found " + cal_byid['summary'] + " by id.")
print ("The time zone of " + cal_byid['summary'] + " is " + cal_byid['timeZone'])
else:
print ("Calendar with name : " + calname + " not found!")
#Programtically create a new calendar using the insert() from calendars() request
print ("--------------------------------")
print ("GENERATING A NEW CALENDAR AND VERIFYING ITS NAME AND ID")
print ("--------------------------------")
#princeton_orange = "#FF8F00"
new_cal = {
"kind": "calendar#calendar", # Type of the resource ("calendar#calendar").
"description": "This is a test of Programtically creating a new calendar", # Description of the calendar. Optional.
"summary": "A new calendar", # Title of the calendar.
#"etag": "A String", # ETag of the resource.
"location": "Princeton, NJ, USA", # Geographic location of the calendar as free-form text. Optional.
"timeZone": "America/New_York", # The time zone of the calendar. (Formatted as an IANA Time Zone Database name, e.g. "Europe/Zurich".) Optional.
#"id": "A String", # Identifier of the calendar. To retrieve IDs call the calendarList.list() method.
}
#FORMAT MUST BE A DICT, NOT JSON, AND THEREFORE NO COMMENTS
new_cal_req = service.calendars().insert(body=new_cal)
new_created_cal = new_cal_req.execute()
print ("Name of new calendar is " + new_created_cal['summary'])
print ("calendarId of new calendar is " + new_created_cal['id'])
print ("--------------------------------")
print ("DELETING THE JUST CREATED CALENDAR AND VERIFYING THAT IT IS GONE")
print ("--------------------------------")
del_cal_req = service.calendars().delete(calendarId=new_created_cal['id'])
del_cal_req.execute()
#HTTP request for a list of the user's calendars
usr_cals_req = service.calendarList().list()
#Execute the request, returns data in an object we call usr_cals
usr_cals = usr_cals_req.execute()
#Extract a particular calendar id by name
calid = None
calname = 'A new calendar'
for i in usr_cals['items']:
if (i['summary'] == calname):
calid = i['id']
break
#Use the extracted id to get the calender object via the get() request
if (calid != None):
cal_byid_req = service.calendarList().get(calendarId=calid)
cal_byid = cal_byid_req.execute()
print ("Found " + cal_byid['summary'] + " by id.")
print ("The time zone of " + cal_byid['summary'] + " is " + cal_byid['timeZone'])
else:
print ("Calendar with name : " + calname + " not found!")
print ("--------------------------------")
print ("ADDING A NEW EVENT TO AN EXISTING CALENDAR")
print ("--------------------------------")
new_event = {
'summary': 'COS 333 TEST EVENT',
'location': 'Princeton University, Princeton, NJ, 08544',
'description': 'Let\'s not fail cos 333 lol',
'start': {
'dateTime': '2016-03-20T09:00:00-05:00',
'timeZone': 'America/New_York',
},
'end': {
'dateTime': '2016-03-20T17:00:00-05:00',
'timeZone': 'America/New_York',
},
#'recurrence': [
# 'RRULE:FREQ=DAILY;COUNT=2'
#],
#'attendees': [
# {'email': '[email protected]'},
# {'email': '[email protected]'},
#],
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'email', 'minutes': 10},
],
},
}
#Extract a particular calendar id by name
calid = None
calname = 'new calendar'
for i in usr_cals['items']:
if (i['summary'] == calname):
calid = i['id']
print (calid)
print(i['accessRole'])
break
#Use the extracted id to get the calender object via the get() request
if (calid != None):
#Add new event request
add_event_req = service.events().insert(calendarId=calid, body=new_event)
add_event_req.execute()
else:
print ("Calendar with name : " + calname + " not found!")
#MY CHANGES
now = datetime.datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
print('Getting the upcoming 10 events')
eventsResult = service.events().list(
calendarId='primary', timeMin=now, maxResults=10, singleEvents=True,
orderBy='startTime').execute()
events = eventsResult.get('items', [])
if not events:
print('No upcoming events found.')
for event in events:
start = event['start'].get('dateTime', event['start'].get('date'))
print(start, event['summary'])
if __name__ == '__main__':
main()