-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevent_handler.py
More file actions
133 lines (110 loc) · 4.35 KB
/
event_handler.py
File metadata and controls
133 lines (110 loc) · 4.35 KB
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
#!/usr/bin/python3
import logging
import threading
from eassistant_connection import EAssistantService
from google_calendar_connection import GoogleCalendarService
from misc import gstrptime, datetime
logger = logging.getLogger(__name__)
def get_event_start(e: dict) -> str:
return e["start"].get("dateTime", e["start"].get("date", ""))
def events_start_at_same_time(e1: dict, e2: dict, no_timezone: bool = False) -> bool:
s1 = get_event_start(e1)
s2 = get_event_start(e2)
if no_timezone:
s1, s2 = s1[:19], s2[:19]
return s1 == s2
def _update_single_date(google_cal_service: GoogleCalendarService, date_construct: dict, date: str, logging_lock: threading.Lock, google_lock: threading.Lock) -> None:
"""
:param google_cal_service:
:param ea_service:
:param date_construct: dictionary with entries for time
:param date:
:return:
"""
"""
"08:15:00":{
"easistent":[events],
"google":[events]
},
...
"""
def list_safe_get(l: list, idx: int, default=None):
"""
:param l:
:param idx:
:param default:
:return: Safely return index from list or default
"""
try:
return l[idx]
except IndexError:
return default
with logging_lock:
logger.debug(f"Updating {date}")
for e_time, all_events in date_construct.items():
google_events = all_events.get("google", [])
easistent_events = all_events.get("easistent", [])
for i in range(max(len(google_events), len(easistent_events))):
g_ev, ea_ev = list_safe_get(google_events, i), list_safe_get(easistent_events, i)
if ea_ev and g_ev:
# patch google event
with google_lock:
google_cal_service.update_event(event_id=g_ev["id"], event_body=ea_ev)
with logging_lock:
logger.debug(get_event_start(ea_ev) + " Patched.")
elif ea_ev and not g_ev:
# create google event from ea_ev
with google_lock:
google_cal_service.add_event(ea_ev)
with logging_lock:
logger.debug(get_event_start(ea_ev) + " Added.")
elif not ea_ev and g_ev:
# remove google event
with google_lock:
google_cal_service.remove_event(event_id=g_ev["id"])
with logging_lock:
logger.debug(get_event_start(g_ev) + " Removed.")
with logging_lock:
logger.debug(f"Finished {date}")
def update_dates(google_cal_service: GoogleCalendarService, ea_service: EAssistantService, *dates_to_update: datetime.date, google_lock: threading.Lock, logging_lock: threading.Lock) -> list:
# Get school events
dates_to_update = sorted(dates_to_update)
if len(dates_to_update) == 1:
dates_to_update.append(dates_to_update[0])
eas_events = ea_service.get_school_events(dates_to_update[0], dates_to_update[1]+datetime.timedelta(days=1))
logger.info("Events time boundary: " + str(eas_events["time_boundary"]))
time_min, time_max = gstrptime(eas_events["time_boundary"]["min"]), gstrptime(eas_events["time_boundary"]["max"])
events_from_cal = google_cal_service.get_events_between((time_min, time_max), q="#school", orderBy="startTime", singleEvents=True)
events_to_enter = eas_events.get("events", [])
events_google = events_from_cal.get("items", [])
logger.debug("Retrieved google events: " + str(len(events_google)))
logger.debug("Easistent events: " + str(len(events_to_enter)))
# Create event list sorted by day
EVENTS_BY_DAY = {}
for event in events_to_enter:
etime = get_event_start(event)
etime, date = etime[11:19], etime[:10] # only the date part
if date not in EVENTS_BY_DAY:
EVENTS_BY_DAY[date] = {}
if etime not in EVENTS_BY_DAY[date]:
EVENTS_BY_DAY[date][etime] = {}
_, f_event = ea_service.ef.google_event_body_from_parsed_event(event)
if "easistent" not in EVENTS_BY_DAY[date][etime]:
EVENTS_BY_DAY[date][etime]["easistent"] = [f_event]
else:
EVENTS_BY_DAY[date][etime]["easistent"].append(f_event)
for g_event in events_google:
etime = get_event_start(g_event)
etime, date = etime[11:19], etime[:10] # only the date part
if date not in EVENTS_BY_DAY:
EVENTS_BY_DAY[date] = {}
if etime not in EVENTS_BY_DAY[date]:
EVENTS_BY_DAY[date][etime] = {}
if "google" not in EVENTS_BY_DAY[date][etime]:
EVENTS_BY_DAY[date][etime]["google"] = [g_event]
else:
EVENTS_BY_DAY[date][etime]["google"].append(g_event)
threads = []
for date, construct in EVENTS_BY_DAY.items():
threads.append(threading.Thread(target=_update_single_date, daemon=True, args=(google_cal_service, construct, date, logging_lock, google_lock), name=f'thread_{date[5:]}'))
return threads