-
Notifications
You must be signed in to change notification settings - Fork 0
/
booking_calendar.py
351 lines (309 loc) · 12.8 KB
/
booking_calendar.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
from __future__ import print_function
from datetime import datetime
import time
import json
from os import name
import os.path
import base64
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar',
'https://www.googleapis.com/auth/gmail.readonly']
vattnas_email = '[email protected]'
soderakra_email = '[email protected]'
month = {
'jan': '01',
'feb': '02',
'mar': '03',
'apr': '04',
'maj': '05',
'may': '05',
'jun': '06',
'jul': '07',
'aug': '08',
'sep': '09',
'okt': '10',
'oct': '10',
'nov': '11',
'dec': '12',
'JAN': '01',
'FEB': '02',
'MAR': '03',
'APR': '04',
'MAJ': '05',
'MAY': '05',
'JUN': '06',
'JUL': '07',
'AUG': '08',
'SEP': '09',
'OKT': '10',
'OCT': '10',
'NOV': '11',
'DEC': '12',
}
def get_booking_name(body, email):
if email == soderakra_email:
return "Okänd"
split_line = []
first_name = []
last_name = []
for line in body.splitlines():
split_line = line.split()
if split_line:
if split_line[0] == 'Förnamn:':
first_name = list(split_line[1:])
elif split_line[0] == 'Efternamn:':
last_name = list(split_line[1:])
name_list = list(first_name)
for ln in last_name:
name_list.append(ln)
return " ".join(name_list)
def get_start_and_end_dates(body, email):
if email == vattnas_email:
if 'Datum:' not in body:
return None, None
for line in body.splitlines():
split_line = line.split()
if split_line and split_line[0] == 'Datum:':
start = f"{split_line[5]}-{month[split_line[4]]}-{split_line[3]}"
end = f"{split_line[9]}-{month[split_line[8]]}-{split_line[7]}"
return start, end
elif email == soderakra_email:
if 'Period:' not in body:
return None, None
words = body.split()
for i, word in enumerate(words):
if word and word == 'Period:':
start_date_obj = datetime.strptime(
words[i+1], '%d/%m-%Y').date()
end_date_obj = datetime.strptime(
words[i+3], '%d/%m-%Y').date()
start = start_date_obj.strftime("%Y-%m-%d")
end = end_date_obj.strftime("%Y-%m-%d")
return start, end
return None, None
def get_booking_id(body, email):
if email == vattnas_email:
split_line = []
for line in body.splitlines():
split_line = line.split()
if split_line and split_line[0] == 'Bokningsnummer:':
return split_line[1]
elif email == soderakra_email:
words = body.split()
for index, word in enumerate(words):
if word and (word == 'Reservationsnummer' or word == 'Bokning'):
return words[index+1]
return "0"
def get_booking_date(body, email):
if email == vattnas_email:
split_line = []
for line in body.splitlines():
split_line = line.split()
if split_line and split_line[0] == 'Bokningsdatum:':
return f"20{split_line[1][5] + split_line[1][6]}-{month[split_line[1][2] + split_line[1][3] + split_line[1][4]]}-{split_line[1][0] + split_line[1][1]}"
elif email == soderakra_email:
words = body.split()
for i, word in enumerate(words):
if word == 'Bokningen' and words[i+1] == 'gjordes' and words[i+2] == 'den':
booking_date_obj = datetime.strptime(
words[i+3], '%d/%m-%Y').date()
return booking_date_obj.strftime("%Y-%m-%d")
return "0"
def setup_creds():
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
creds = None
if os.path.exists('token.json'):
creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.json', 'w') as token:
token.write(creds.to_json())
return creds
def scan_and_get_message_bodies(service_gmail, email):
if email == vattnas_email:
print("==== Vattnäs ====")
else:
print("==== Söderåkra ====")
print("Fetching all messages matching the query...")
results = service_gmail.users().messages().list(
userId='me', q=f'from:{email}').execute()
messages = results.get('messages', [])
message_bodies_new = []
message_bodies_changed = []
message_bodies_canceled = []
if not messages:
print('No messages found.')
else:
print(f"{len(messages)} messages found. Looking for bookings...")
for message in messages:
msg = service_gmail.users().messages().get(
userId='me', id=message['id']).execute()
for header in msg['payload']['headers']:
if header['name'] != 'Subject':
continue
if 'NY BOKNING' in header['value']:
body = base64.urlsafe_b64decode(msg['payload'].get(
"body").get("data").encode("ASCII")).decode("utf-8")
message_bodies_new.append(body)
elif 'Ny bokning av ditt hus' in header['value']:
message_bodies_new.append(msg.get("snippet"))
elif 'ÄNDRAD BOKNING' in header['value']:
body = base64.urlsafe_b64decode(msg['payload'].get(
"body").get("data").encode("ASCII")).decode("utf-8")
message_bodies_changed.append(body)
elif 'AVBOKAD BOKNING' in header['value']:
body = base64.urlsafe_b64decode(msg['payload'].get(
"body").get("data").encode("ASCII")).decode("utf-8")
message_bodies_canceled.append(body)
elif 'Afbestilling af booking på dit hus' in header['value']:
message_bodies_canceled.append(msg.get("snippet"))
print(f"{len(message_bodies_new)} new bookings found.")
print(f"{len(message_bodies_changed)} changed bookings found.")
print(f"{len(message_bodies_canceled)} canceled bookings found.")
return message_bodies_new, message_bodies_changed, message_bodies_canceled
def add_or_change_events(message_bodies, events, email):
for body in message_bodies:
start_date, end_date = get_start_and_end_dates(body, email)
desc = "".join(line + "\n" for line in body.splitlines())
booking_name = get_booking_name(body, email)
booking_id = get_booking_id(body, email)
booking_date = get_booking_date(body, email)
place = 'SÖDERÅKRA' if email == soderakra_email else 'VATTNÄS'
event = {
'booking_id': booking_id,
'booking_date': booking_date,
'start': {'date': start_date},
'end': {'date': end_date},
'summary': f"{place}: {booking_name}, {booking_id}",
'description': desc
}
if booking_id in events:
if event['booking_date'] > events[booking_id]['booking_date']:
events[booking_id] = event
print("c", end="")
else:
print(".", end="")
else:
events[booking_id] = event
print("a", end="")
print()
return events
def cancel_event(message_bodies_canceled, events, email):
for body in message_bodies_canceled:
booking_id = get_booking_id(body, email)
if events.pop(booking_id, None):
print("d", end="")
else:
print(".", end="")
print()
return events
def update_db(message_bodies_new, message_bodies_changed, message_bodies_canceled, email):
print("Opening json file...")
events = {}
if email == vattnas_email:
with open('events_vattnas.json') as events_file:
if json_str := events_file.read():
events = json.loads(json_str)
print("Adding new events to json if not already in json...")
events = add_or_change_events(message_bodies_new, events, email)
print("Replacing events that were changed...")
events = add_or_change_events(message_bodies_changed, events, email)
print("Removing events that were canceled...")
events = cancel_event(message_bodies_canceled, events, email)
print("Updating json...")
with open('events_vattnas.json', 'w') as events_file:
events_file.write(json.dumps(events))
print("Done")
elif email == soderakra_email:
with open('events_soderakra.json') as events_file:
if json_str := events_file.read():
events = json.loads(json_str)
print("Adding new events to json if not already in json...")
events = add_or_change_events(message_bodies_new, events, email)
print("Replacing events that were changed...")
events = add_or_change_events(message_bodies_changed, events, email)
print("Removing events that were canceled...")
events = cancel_event(message_bodies_canceled, events, email)
print("Updating json...")
with open('events_soderakra.json', 'w') as events_file:
events_file.write(json.dumps(events))
print("Done")
return events
def get_booking_events(cal_events_all, email):
cal_events = {}
place = "VATTNÄS" if email == vattnas_email else "SÖDERÅKRA"
for cal_event in cal_events_all['items']:
if place in cal_event['summary']:
cal_events[get_booking_id(
cal_event['description'], email)] = cal_event
return cal_events
def update_calendar(service, events, email):
print('Fetching all calendar events...')
cal_events_all = service.events().list(calendarId='primary').execute()
cal_events = get_booking_events(cal_events_all, email)
print(
f"{len(cal_events_all['items'])} calendar events found. Looking for bookings...")
print(f"{len(cal_events)} booking calendar events found.")
exists = False
changed = False
print('Updating calendar according to json...')
for event in events.values():
booking_id = event['booking_id']
if booking_id in cal_events:
exists = True
if event['description'] != cal_events[booking_id]['description']:
service.events().delete(calendarId='primary',
eventId=cal_events[booking_id]['id']).execute()
changed = True
if not exists:
print("a", end="")
e = service.events().insert(calendarId='primary', body=event).execute()
print(f'''*** {e['summary'].encode('utf-8')} event added:
Start: {e['start']['date']}
End: {e['end']['date']}''')
elif changed:
print("c", end="")
e = service.events().insert(calendarId='primary', body=event).execute()
print(f'''*** {e['summary'].encode('utf-8')} event updated:
Start: {e['start']['date']}
End: {e['end']['date']}''')
else:
print(".", end="")
exists = False
changed = False
print('\nRemoving canceled events from calendar...')
for booking_id in cal_events.keys():
if booking_id not in events:
print("d")
service.events().delete(calendarId='primary',
eventId=cal_events[booking_id]['id']).execute()
print(f"*** {cal_events[booking_id]['summary']} event removed")
else:
print(".", end="")
print('Done')
def main():
creds = setup_creds()
service_cal = build('calendar', 'v3', credentials=creds)
service_gmail = build('gmail', 'v1', credentials=creds)
emails = [vattnas_email, soderakra_email]
for email in emails:
message_bodies_new, message_bodies_changed, message_bodies_canceled = scan_and_get_message_bodies(
service_gmail, email)
events = update_db(message_bodies_new, message_bodies_changed,
message_bodies_canceled, email)
update_calendar(service_cal, events, email)
if __name__ == '__main__':
main()