-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcal.py
More file actions
executable file
·174 lines (132 loc) · 4.34 KB
/
Copy pathcal.py
File metadata and controls
executable file
·174 lines (132 loc) · 4.34 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
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
#!/usr/bin/env python3
import os
import re
import json
import time
import urllib.request
from math import ceil
from dataclasses import dataclass
from datetime import datetime
from contextlib import contextmanager
from zoneinfo import ZoneInfo
with open('.calendar.json.env') as f:
CALENDARS = json.load(f)
COLORS = {
"uncategorized": "hsl(21.36, 25.11%, 66.08%)",
"work": "hsl(165, 76.92%, 45.49%)",
"contentcreation": "hsl(302.16, 49.33%, 64.12%)",
"chill": "hsl(338.62, 82.08%, 78.43%)",
"perso": "hsl(240, 100%, 85.1%)",
"commute": "hsl(230.07, 64.06%, 62.55%)",
"sleep": "hsl(118.8, 58.82%, 53.33%)",
}
assert COLORS.keys() == CALENDARS.keys()
FOLDER = "/tmp/proton-calendar"
os.makedirs(FOLDER, exist_ok=True)
FETCH_DELAY = 15*60 # 15 min (download, refetch, recreate list, sort list)
UPDATE_DELAY = 15 # 15 sec (list should be sorted, so really fast)
@contextmanager
def catch(act):
print(f"Trying to {act}")
try:
yield
except Exception as e:
print(f"Failed to {act}")
print(e)
@dataclass
class Event:
name: str
calendar: str
start: datetime
end: datetime
events: list[Event] = []
local_tz = datetime.now().astimezone().tzinfo
now = datetime.now(local_tz)
def parse_dt(dt_str, tz):
'''Manually parse YYYYMMDDTHHMMSS'''
return datetime(
year = int(dt_str[0:4]),
month = int(dt_str[4:6]),
day = int(dt_str[6:8]),
hour = int(dt_str[9:11]),
minute = int(dt_str[11:13]),
second = int(dt_str[13:15]),
tzinfo=tz
)
def format_delta(delta) -> str:
'''Format a timedelta into a human readable string'''
minutes = ceil(delta.total_seconds() / 60)
hours, minutes = divmod(minutes, 60)
if hours > 0:
return f"{hours}h {minutes}m"
return f"{minutes}m"
def download_calendars():
'''Download all calendars to local files'''
for cal_name, url in CALENDARS.items():
print(f"Downloading {cal_name}")
tmp_file = os.path.join(FOLDER, f"{cal_name}.ics")
urllib.request.urlretrieve(url, tmp_file)
def fetch_events():
'''Parse event from local files'''
global events
events.clear()
for cal_name in CALENDARS.keys():
tmp_file = os.path.join(FOLDER, f"{cal_name}.ics")
with open(tmp_file, "r") as f:
content = f.read()
for event in content.split("BEGIN:VEVENT")[1:]:
dtstart = re.search(r'DTSTART;TZID=([^:]+):(\d{8}T\d{6})', event)
dtend = re.search(r'DTEND;TZID=([^:]+):(\d{8}T\d{6})', event)
summary = re.search(r'SUMMARY:(.+)', event)
if dtstart and dtend and summary:
event_tz = ZoneInfo(dtstart.group(1))
start = datetime.strptime(dtstart.group(2), "%Y%m%dT%H%M%S").replace(tzinfo=event_tz)
end = datetime.strptime(dtend.group(2), "%Y%m%dT%H%M%S").replace(tzinfo=event_tz)
start_local = start.astimezone(local_tz)
end_local = end.astimezone(local_tz)
name = summary.group(1).strip()
events.append(Event(name, cal_name, start_local, end_local))
events.sort(key = lambda x: x.start)
events = [e for e in events if now <= e.end]
def update_msg():
global events
# Find current and next events across all calendars
current_events: list[Event] = []
next_event: list[Event] = []
closest: None|Event = None
for e in events:
if e.start <= now <= e.end:
current_events.append(e)
elif e.start > now:
if closest is None:
closest = e
if e.start == closest.start:
next_event.append(e)
msg = os.path.join(FOLDER, "msg")
with open(msg, "w") as f:
f.write(json.dumps({
'current': [
{ 'calendar': e.calendar, 'name': e.name, 'for': format_delta(e.end - now), 'color': COLORS[e.calendar]}
for e in current_events
] if current_events else [ None ],
'future': [
{ 'calendar': f.calendar, 'name': f.name, 'in': format_delta(f.start - now), 'color': COLORS[f.calendar]}
for f in next_event
]
}))
last_fetch = 0
last_update = 0
while True:
now = datetime.now(local_tz)
local_tz = datetime.now().astimezone().tzinfo
if now.timestamp() - last_fetch >= FETCH_DELAY:
with catch("download all calendars"):
download_calendars()
with catch("fetch all events"):
fetch_events()
last_fetch = now.timestamp()
if now.timestamp() - last_update >= UPDATE_DELAY:
with catch("update message"):
update_msg()
last_update = now.timestamp()
time.sleep(5)