-
Notifications
You must be signed in to change notification settings - Fork 2
/
calendar_manager.py
114 lines (99 loc) · 4.9 KB
/
calendar_manager.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
__author__ = "Sadman Ahmed Shanto"
__email__ = "[email protected]"
import os
import pickle
from datetime import datetime, timedelta
from dateutil.parser import parse
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
class CalendarManager:
def __init__(self, email_notifier, client_secret_file="client_secret.json", token_file='token.pickle', scopes=['https://www.googleapis.com/auth/calendar']):
self.credentials = None
self.email_notifier = email_notifier
self.client_secret_file = client_secret_file
self.token_file = token_file
self.scopes = scopes
if os.path.exists(token_file):
with open(token_file, 'rb') as token:
self.credentials = pickle.load(token)
# If there are no valid credentials available, let the user log in.
self.__athenticate_via_browser() #old method
self.service = build('calendar', 'v3', credentials=self.credentials)
def __athenticate_via_browser(self):
if not self.credentials or not self.credentials.valid:
if self.credentials and self.credentials.expired and self.credentials.refresh_token:
self.credentials.refresh(Request())
else:
self.email_notifier.send_email([__email__], 'Re-authentication Required', 'Please re-authenticate your app.')
self.initiate_new_authentication_flow()
def initiate_new_authentication_flow(self):
flow = InstalledAppFlow.from_client_secrets_file(self.client_secret_file, scopes=self.scopes)
self.credentials = flow.run_local_server(port=0)
with open(self.token_file, 'wb') as token:
pickle.dump(self.credentials, token)
def create_event(self, title, description, start_date, end_date, attendees, all_day=False, location="SSC 319"):
"""Create a calendar event without attendees."""
time_zone = 'America/Los_Angeles'
if all_day:
#* For all-day events, use 'date' instead of 'dateTime'
start = {'date': start_date}
end = {'date': end_date}
colorId = "2"
else:
#* For timed events, use 'dateTime'
start = {'dateTime': start_date, 'timeZone': time_zone}
end = {'dateTime': end_date, 'timeZone': time_zone}
colorId = "4"
#* Add location if provided
event_body = {
'summary': title,
'description': description,
'colorId': colorId, # '2' for all-day, '4' for timed
'start': start,
'end': end,
'attendees': [{'email': attendee} for attendee in attendees],
'location': location,
'reminders': {
'useDefault': False,
'overrides': [{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10}],
},
}
try:
event = self.service.events().insert(calendarId='primary', body=event_body).execute()
print('Event created: %s' % (event.get('htmlLink')))
except HttpError as e:
error_message = f"An error occurred in CalendarManager: {e}"
self.email_notifier.send_email([__email__], "CalendarManager Error", error_message)
print(error_message)
raise
def create_timed_event(self, title, date, start_time_str, attendees, calendar_id='primary', location="SSC 319"):
"""Create a calendar event based on a start time string."""
time_zone = 'America/Los_Angeles'
# Parse the start time string and set it to the provided date
start_time = parse(start_time_str)
start_datetime = datetime.combine(date.date(), start_time.time())
# Add one hour to get the end time
end_datetime = start_datetime + timedelta(hours=1)
event_body = {
'summary': title,
"colorId": "10",
'start': {'dateTime': start_datetime.isoformat(), 'timeZone': time_zone},
'end': {'dateTime': end_datetime.isoformat(), 'timeZone': time_zone},
'attendees': [{'email': attendee} for attendee in attendees],
'location': location,
'reminders': {
'useDefault': False,
'overrides': [{'method': 'email', 'minutes': 24 * 60}, {'method': 'popup', 'minutes': 10}],
},
}
try:
event = self.service.events().insert(calendarId=calendar_id, body=event_body).execute()
print('Event created: %s' % (event.get('htmlLink')))
except HttpError as e:
error_message = f"An error occurred in CalendarManager: {e}"
self.email_notifier.send_email([__email__], "CalendarManager Error", error_message)
print(error_message)
raise