-
Notifications
You must be signed in to change notification settings - Fork 1
/
helperFunctions.py
582 lines (509 loc) · 21.2 KB
/
helperFunctions.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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
from datetime import datetime, timedelta
from pytz import timezone, utc
from setup import *
from apiConnections import *
########################
### HELPER FUNCTIONS ###
########################
def nowToDateTimeString():
"""Returns the current date and time as a string"""
# Note: Adding the timedelta of +1 minute prevents events in both Google Calendar and Notion Calendar from having
# last updated times that are greater than the last synced time.
now = datetime.now() + timedelta(minutes=1)
return now.strftime('%Y-%m-%dT%H:%M:%S')
def dateTimeToString(dateTime):
"""
Returns dateTime as a string
Required: dateTime is a datetime object
"""
return dateTime.strftime('%Y-%m-%dT%H:%M:%S')
def dateToString(date):
"""
Returns date as a string
Required: date is a datetime object
"""
return date.strftime('%Y-%m-%d')
def parseDateTimeString(dateTimeString, format):
"""
Returns dateTimeString as a datetime object with date and time
Required: dateTimeString follows the specified format
"""
return datetime.strptime(dateTimeString, format)
def parseDateString(dateString, format):
"""
Returns dateString as a datetime object with date only
Required: dateString follows the specified format
"""
return datetime.strptime(dateString, format)
def addTimeZoneForNotion(dateTimeString):
"""Adds timezone indicator to dateTimeString (for ET this will be -04:00 or -05:00)"""
return dateTimeString + TIMEZONE_OFFSET_FROM_GMT
def convertTimeZone(dateTime, newTimeZone=TIMEZONE):
"""
Convert dateTime from UTC to newTimeZone
Requires: dateTime is a datetime object of the form '%Y-%m-%dT%H:%M:%S'
"""
return utc.localize(dateTime).astimezone(timezone(newTimeZone)).replace(tzinfo=None)
def getGoogleMeetId(link):
"""Returns the Google Meet ID (everything after https://meet.google.com/)"""
link.split('https://meet.google.com/', 1)[1]
def makeNotionPageURL(pageId, urlRoot):
"""Returns a URL to the Notion page"""
urlId = pageId.replace('-', '')
return urlRoot + urlId
def makeDescription(richText):
"""Returns a plain text description from Notion's rich text field"""
description = ""
for item in richText:
description += item['text']['content']
return description
def makeOneLinePlainText(richText):
"""Returns a single line of plain text from Notion's rich text field"""
return richText[0]['plain_text']
def makeLink(richText):
"""Returns a Python List with the following format: [Display text, URL]"""
return [richText[0]['text']['content'], richText[0]['text']['link']['url']]
def makeGCalEvent(eventName, eventDescription, eventStartTime, sourceUrl, eventEndTime, gCalId, eventLocation, eventCallLink, eventAttendees):
"""Creates a new Google Calendar event and returns the event"""
event = {
'summary': eventName,
'description': eventDescription,
'source': {
'title': 'From Notion',
'url': sourceUrl
},
'location': eventLocation,
'attendees': [{'email': attendee} for attendee in eventAttendees]
}
# Three cases for the start/end dates:
# 1. The Notion Calendar event has one date without time
# 2. The Notion Calendar event has two dates without times (i.e. start date and end date are different)
# 3. The Notion Calendar event has two dates with times, or a single date with time
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime == eventStartTime:
eventStartTime = datetime.combine(eventStartTime, datetime.min.time())
eventEndTime = eventEndTime + timedelta(days=1)
event['start'] = {
'date': eventStartTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
event['end'] = {
'date': eventEndTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
elif eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0 and eventStartTime != eventEndTime:
eventEndTime = eventEndTime + timedelta(days=1)
event['start'] = {
'date': eventStartTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
event['end'] = {
'date': eventEndTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
else:
event['start'] = {
'dateTime': eventStartTime.strftime('%Y-%m-%dT%H:%M:%S'),
'timeZone': TIMEZONE
}
event['end'] = {
'dateTime': eventEndTime.strftime('%Y-%m-%dT%H:%M:%S'),
'timeZone': TIMEZONE
}
# TODO: get Notion-to-Google conference link working
#if len(eventCallLink) == 2:
# event['hangoutLink'] = eventCallLink[1]
# event['conferenceData'] = {
# 'entryPoints': [
# {
# 'entryPointType': 'video',
# 'uri': eventCallLink[1],
# 'label': eventCallLink[0]
# }
# ],
# 'conferenceSolution': {
# 'key': {
# 'type': 'hangoutsMeet'
# },
# 'name': 'Google Meet',
# 'iconUri': 'https://fonts.gstatic.com/s/i/productlogos/meet_2020q4/v6/web-512dp/logo_meet_2020q4_color_2x_web_512dp.png'
# },
# 'conferenceId': getGoogleMeetId(eventCallLink[1])
# }
print(f'Adding this event to Google Calendar: {eventName}\n')
newEvent = service.events().insert(calendarId=gCalId, body=event).execute()
return newEvent
def makeNotionCalEvent(eventName, eventStartTime, eventEndTime, eventDescription, eventLocation, eventCallLink, eventCreator, eventAttendees, gCalEventId, gCalCalendarId, notionCalendarName):
"""Creates a new Notion Calendar event and returns the event"""
newNotionEvent = notion.pages.create(
**{
'parent': {
'database_id': NOTION_DATABASE_ID
},
'properties': {
NOTION_EVENT_NAME: {
'title': [
{
'text': {
'content': eventName
}
}
]
},
NOTION_CALENDAR_NAME: {
'select': {
'name': notionCalendarName
}
},
NOTION_CREATOR: {
'select': {
'name': eventCreator,
'color': 'default'
}
},
NOTION_ATTENDEES: {
'multi_select': [{'name': eventAttendees[i], 'color': 'default'} for i in range(len(eventAttendees))]
},
NOTION_LOCATION: {
'rich_text': [{
'text': {
'content': eventLocation
}
}]
},
NOTION_DESCRIPTION: {
'rich_text': [{
'text': {
'content': eventDescription
}
}]
},
NOTION_SYNCED: {
'checkbox': True
},
NOTION_GCAL_EVENT_ID: {
'rich_text': [{
'text': {
'content': gCalEventId
}
}]
},
NOTION_GCAL_CALENDAR_ID: {
'rich_text': [{
'text': {
'content': gCalCalendarId
}
}]
},
NOTION_LAST_SYNCED: {
'date': {
'start': addTimeZoneForNotion(nowToDateTimeString()),
'end': None
}
}
}
}
)
if eventCallLink != '':
notionEventUpdate = notion.pages.update(
**{
'page_id': newNotionEvent['id'],
'properties': {
NOTION_VIDEO_CALL_LINK: {
'rich_text': [{
'text': {
'content': eventCallLink,
'link': {
'url': eventCallLink
}
}
}]
}
}
}
)
# Four cases for the start and end dates:
# 1. The Google Calendar event is an all-day event, so Notion only needs start date
# 2. The Google Calendar event is a multi-day event (with dates only, not times), so Notion needs start and end dates
# 3. The Google Calendar event start date & time is the same as the end date & time, so Notion only needs start date & time
# 4. The Google Calendar event has start date & time and end date & time, so Notion needs everything
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0 and (eventStartTime == eventEndTime or eventStartTime == eventEndTime - timedelta(days=1)):
notionEventUpdate = notion.pages.update(
**{
'page_id': newNotionEvent['id'],
'properties': {
NOTION_DATE: {
'date': {
'start': dateToString(eventStartTime),
'end': None
}
}
}
}
)
elif eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0:
eventEndTime = eventEndTime - timedelta(days=1) # The end date is 00:00 the next day so this must be adjusted
notionEventUpdate = notion.pages.update(
**{
'page_id': newNotionEvent['id'],
'properties': {
NOTION_DATE: {
'date': {
'start': dateToString(eventStartTime),
'end': dateToString(eventEndTime)
}
}
}
}
)
elif eventStartTime == eventEndTime:
notionEventUpdate = notion.pages.update(
**{
'page_id': newNotionEvent['id'],
'properties': {
NOTION_DATE: {
'date': {
'start': addTimeZoneForNotion(dateTimeToString(eventStartTime)),
'end': None
}
}
}
}
)
else:
notionEventUpdate = notion.pages.update(
**{
'page_id': newNotionEvent['id'],
'properties': {
NOTION_DATE: {
'date': {
'start': addTimeZoneForNotion(dateTimeToString(eventStartTime)),
'end': addTimeZoneForNotion(dateTimeToString(eventEndTime))
}
}
}
}
)
print(f'Adding this event to Notion Calendar: {eventName}\n')
return newNotionEvent
def updateGCalEvent(eventName, eventDescription, eventStartTime, eventEndTime, gCalEventId, currentGCalId, newGCalId, eventLocation, eventCallLink, eventAttendees):
"""Updates the Google Calendar event and returns the event"""
event = {
'summary': eventName,
'description': eventDescription,
'location': eventLocation,
'attendees': [{'email': attendee} for attendee in eventAttendees]
}
# Three cases for the start/end dates:
# 1. The Notion Calendar event has one date without time
# 2. The Notion Calendar event has two dates without times (i.e. start date and end date are different)
# 3. The Notion Calendar event has two dates with times, or a single date with time
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime == eventStartTime:
eventStartTime = datetime.combine(eventStartTime, datetime.min.time())
eventEndTime = eventEndTime + timedelta(days=1)
event['start'] = {
'date': eventStartTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
event['end'] = {
'date': eventEndTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
elif eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0 and eventStartTime != eventEndTime:
eventEndTime = eventEndTime + timedelta(days=1)
event['start'] = {
'date': eventStartTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
event['end'] = {
'date': eventEndTime.strftime('%Y-%m-%d'),
'timeZone': TIMEZONE
}
else:
event['start'] = {
'dateTime': eventStartTime.strftime('%Y-%m-%dT%H:%M:%S'),
'timeZone': TIMEZONE
}
event['end'] = {
'dateTime': eventEndTime.strftime('%Y-%m-%dT%H:%M:%S'),
'timeZone': TIMEZONE
}
# TODO: get Notion-to-Google conference link working
#if len(eventCallLink) == 2:
# event['hangoutLink'] = eventCallLink[1]
# event['conferenceData'] = {
# 'entryPoints': [
# {
# 'entryPointType': 'video',
# 'uri': eventCallLink[1],
# 'label': eventCallLink[0]
# }
# ],
# 'conferenceSolution': {
# 'key': {
# 'type': 'hangoutsMeet'
# },
# 'name': 'Google Meet',
# 'iconUri': 'https://fonts.gstatic.com/s/i/productlogos/meet_2020q4/v6/web-512dp/logo_meet_2020q4_color_2x_web_512dp.png'
# },
# 'conferenceId': getGoogleMeetId(eventCallLink[1])
# }
print(f'Updating this event in Google Calendar: {eventName}\n')
# Notes:
# 1. currentGCalId is the Google Calendar ID saved in the 'GCal Calendar ID' field in Notion
# 2. newGCalId is the Google Calendar ID associated with the 'Calendar' field in Notion
# 3. If the 'Calendar' field in Notion is changed, then its associated Google Calendar ID will not match the 'GCal Calendar ID' field
if currentGCalId == newGCalId and currentGCalId != UNKNOWN_CALENDAR_ID:
updatedEvent = service.events().update(calendarId=currentGCalId, eventId=gCalEventId, body=event).execute()
else: # The 'Calendar' field has been changed in Notion
# The 'Calendar' field was changed to or from 'Unknown', or was 'Unknown' in the first place. Do not change the calendar.
if newGCalId == UNKNOWN_CALENDAR_ID or (newGCalId != UNKNOWN_CALENDAR_ID and currentGCalId not in CALENDAR_DICTIONARY.values()):
updatedEvent = service.events().update(calendarId=currentGCalId, eventId=gCalEventId, body=event).execute()
# The 'Calendar' field was changed to a valid calendar. First move the Google Calendar event to the new calendar, then update the information.
else:
updatedEvent = service.events().move(calendarId=currentGCalId , eventId=gCalEventId, destination=newGCalId).execute()
updatedEvent = service.events().update(calendarId=newGCalId, eventId=gCalEventId, body=event).execute()
return updatedEvent
def updateNotionCalEvent(eventName, eventStartTime, eventEndTime, eventDescription, eventLocation, eventCallLink, eventCreator, eventAttendees, gCalCalendarId, notionCalendarName, notionPageId):
"""Updates the Notion Calendar event and returns the event"""
updatedNotionEvent = notion.pages.update(
**{
'page_id': notionPageId,
'properties': {
NOTION_EVENT_NAME: {
'title': [
{
'text': {
'content': eventName
}
}
]
},
NOTION_CALENDAR_NAME: {
'select': {
'name': notionCalendarName
}
},
NOTION_CREATOR: {
'select': {
'name': eventCreator,
'color': 'default'
}
},
NOTION_ATTENDEES: {
'multi_select': [{'name': eventAttendees[i], 'color': 'default'} for i in range(len(eventAttendees))]
},
NOTION_LOCATION: {
'rich_text': [{
'text': {
'content': eventLocation
}
}]
},
NOTION_DESCRIPTION: {
'rich_text': [{
'text': {
'content': eventDescription
}
}]
},
NOTION_SYNCED: {
'checkbox': True
},
NOTION_GCAL_CALENDAR_ID: {
'rich_text': [{
'text': {
'content': gCalCalendarId
}
}]
},
NOTION_LAST_SYNCED: {
'date': {
'start': addTimeZoneForNotion(nowToDateTimeString()),
'end': None
}
}
}
}
)
if eventCallLink != '':
notionEventUpdate = notion.pages.update(
**{
'page_id': notionPageId,
'properties': {
NOTION_VIDEO_CALL_LINK: {
'rich_text': [{
'text': {
'content': eventCallLink,
'link': {
'url': eventCallLink
}
}
}]
}
}
}
)
# Four cases for the start and end dates:
# 1. The Google Calendar event is an all-day event, so Notion only needs start date
# 2. The Google Calendar event is a multi-day event (with dates only, not times), so Notion needs start and end dates
# 3. The Google Calendar event start date & time is the same as the end date & time, so Notion only needs start date & time
# 4. The Google Calendar event has start date & time and end date & time, so Notion needs everything
if eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0 and (eventStartTime == eventEndTime or eventStartTime == eventEndTime - timedelta(days=1)):
updatedNotionEventUpdate = notion.pages.update(
**{
'page_id': notionPageId,
'properties': {
NOTION_DATE: {
'date': {
'start': dateToString(eventStartTime),
'end': None
}
}
}
}
)
elif eventStartTime.hour == 0 and eventStartTime.minute == 0 and eventEndTime.hour == 0 and eventEndTime.minute == 0:
eventEndTime = eventEndTime - timedelta(days=1) # The end date is 00:00 the next day so this must be adjusted
updatedNotionEventUpdate = notion.pages.update(
**{
'page_id': notionPageId,
'properties': {
NOTION_DATE: {
'date': {
'start': dateToString(eventStartTime),
'end': dateToString(eventEndTime)
}
}
}
}
)
elif eventStartTime == eventEndTime:
updatedNotionEventUpdate = notion.pages.update(
**{
'page_id': notionPageId,
'properties': {
NOTION_DATE: {
'date': {
'start': addTimeZoneForNotion(dateTimeToString(eventStartTime)),
'end': None
}
}
}
}
)
else:
updatedNotionEventUpdate = notion.pages.update(
**{
'page_id': notionPageId,
'properties': {
NOTION_DATE: {
'date': {
'start': addTimeZoneForNotion(dateTimeToString(eventStartTime)),
'end': addTimeZoneForNotion(dateTimeToString(eventEndTime))
}
}
}
}
)
print(f'Updating this event in Notion Calendar: {eventName}\n')
return updatedNotionEvent