-
Notifications
You must be signed in to change notification settings - Fork 0
/
meetings.py
255 lines (189 loc) · 6.67 KB
/
meetings.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
####################
# CALENDEE
import os
import sys
from dotenv import load_dotenv
load_dotenv()
USER_PATH = os.getenv("USER_PATH")
import pprint
pp = pprint.PrettyPrinter(indent=4)
from datetime import datetime, time, timezone, timedelta
from googleapiclient.discovery import build
from google.oauth2.credentials import Credentials
from google.oauth2 import service_account
import subprocess
# for pasting
from pynput.keyboard import Key, Controller
keyb = Controller()
# Email addresses of calendars to check
EMAIL_BB = os.getenv("EMAIL_BB")
EMAIL_DV = os.getenv("EMAIL_DV")
print()
####################
# GLOBAL VARIABLES
test = True
blacklist = os.getenv("BLACKLIST_MEETINGS_PARTICIPANTS").split(",")
met_with = set()
meetings = []
meetings_ids = []
####################
# CLASSES
class Meeting:
def __init__(self):
self.id = '' # from Google
self.summary = ''
self._date = '' # from Google 'start'
self.htmlLink = ''
self.attendees = set() # unique emails from both 'attendees' and 'organiser'
self.description = ''
self.domain = '' # WARNING: this caters only for 1 domain per meeting
@property
def date(self):
return self._date
@date.setter
def date(self, value):
if isinstance(value, str) and len(value) == 10 and value[4] == '-' and value[7] == '-':
year, month, day = value.split('-')
try:
year = int(year)
month = int(month)
day = int(day)
if 1 <= month <= 12 and 1 <= day <= 31:
self._date = value
else:
raise ValueError("Invalid date value")
except ValueError:
raise ValueError("Invalid date format. Should be YYYY-MM-DD")
else:
raise ValueError("Invalid date format. Should be YYYY-MM-DD")
# Print attributes in output to help with coding & debugging
empty_meeting = Meeting()
print(f"\nMeeting attributes:")
print(" ".join([f"{key}={value}" for key, value in empty_meeting.__dict__.items()]))
print()
####################
# FUNCTIONS
def get_all_events(calendar_id, token, test=False):
# Set up Google API credentials
SCOPES = ['https://www.googleapis.com/auth/calendar']
credentials = service_account.Credentials.from_service_account_file(token, scopes=SCOPES)
creds = credentials.with_subject(calendar_id)
# Build the Google Calendar API client
service = build('calendar', 'v3', credentials=creds)
# Initialize an empty list to store all events
all_events = []
# Initialize the page token
page_token = None
# Get the current time in UTC
now = datetime.utcnow()
now_formatted = now.isoformat() + 'Z'
# Set the maximum time to be 1 month in the future (covers potential holidays)
# max_time = now + timedelta(days=30)
# max_time_formatted = max_time.isoformat() + 'Z'
# Set the maximum time to be today, for only past events
max_time = now
max_time_formatted = max_time.isoformat() + 'Z'
# Call the Google Calendar API to get events and handle pagination
while True:
events_result = service.events().list(
calendarId=calendar_id,
# timeMin=now_formatted,
timeMax=max_time_formatted,
singleEvents=True,
orderBy='startTime',
pageToken=page_token
).execute()
events = events_result.get('items', [])
all_events.extend(events)
# Check if there is a next page token, if not break the loop
page_token = events_result.get('nextPageToken')
if not page_token:
break
if test:
for event in all_events:
print(f"\n========\n")
pp.pprint(event)
return all_events
def construct_meeting(event, test=False):
global blacklist
m = Meeting()
m.id = event['id']
m._date = '' # from Google 'start'
try:
m._date = event['start']['dateTime'].split('T')[0]
except KeyError:
m.date = event['start']['date']
m.htmlLink = event['htmlLink']
if 'description' in event:
m.description = event['description']
# Attendees / only if not in blacklist
if 'attendees' in event:
attendees = event['attendees']
if len(attendees) > 1:
for attendee in attendees:
attendee_email = attendee['email']
if attendee_email not in blacklist:
m.attendees.add(attendee_email)
organiser = event['organizer']['email']
if organiser not in blacklist:
m.attendees.add(organiser)
m.attendees = list(m.attendees)
if len(m.attendees) > 0:
# Domain
for attendee in m.attendees:
m.domain = attendee.split('@')[1]
if test:
print(f"{m.attendees=} on {m.date} from domain {m.domain}")
m.summary = event['summary']
return m
else:
return None # no attendees meeting
def process_events(all_events_from_one_calendar, test=False):
global met_with
global meetings
global meetings_ids
for event in all_events_from_one_calendar:
m = construct_meeting(event, test=test)
if m != None:
if m.id not in meetings_ids:
meetings.append(m)
meetings_ids.append(m.id)
met_with = met_with.union(set(m.attendees))
else:
print(f"\n\nDuplicate meeting: {m.uid=}")
# MAIN FUNCTION
def get_meetings(test=False):
global meetings
global met_with
global meetings_ids
## BB
all_future_events_bb = get_all_events(EMAIL_BB, f'{USER_PATH}creds_bb/service_key.json')
process_events(all_future_events_bb, test=test)
## DV
all_future_events_dv = get_all_events(EMAIL_DV, f'{USER_PATH}creds_dv/service_key.json')
process_events(all_future_events_dv, test=test)
print(f"\n\n{len(meetings)} meetings:")
for meeting in meetings:
attendees = ",".join(meeting.attendees)
print(f" - {meeting.summary} on {meeting.date} with {attendees}")
print(f"\n\nMet with {len(met_with)} people:")
for met in sorted(met_with):
# print(f"\"{met}\",")
print(f" - {met}")
print(f"\n\n")
return meetings
########################################################################################################
if __name__ == '__main__':
print()
arguments = sys.argv
get_meetings()
# Get timezone argument, if passed
# if len(sys.argv) > 1:
# tz = sys.argv[1].upper()
# else:
# tz = "CET"
# print(f"tz: {tz}")
# Write to clipboard
# write_to_clipboard(my_availabilities)
# Paste availabilities
# paste()