~kris/dots

srice

ref: e9b48d06a8541f3eda5c4db90382ab3c77183afb srice/.local/bin/academic/countdown.py -rw-r--r-- 6.6 KiB
e9b48d06 — Kris Yotam xprofile: systemd-aware pipewire start + blueman-applet; sb-internet: tolerate missing /proc/net/wireless 2 months ago
                                                                                
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
#!/usr/bin/env python3
"""
===============================================================
 Script: countdown.py
 Author: Kris Yotam (aka. khr1st)
 Date:   2025-09-29
 License: MIT License
 Description:
   Hooks into Google Calendar to display upcoming/current lecture
   info. Updates the active course when matching an event.
   Designed for use with polybar or similar status bars.

 Inspiration:
   Adapted and extended from Gilles Castel's lecture note workflow.
===============================================================
"""

import os
import sys
import re
import math
import sched
import time
import pickle
import datetime
import pytz
import http.client as httplib
from dateutil.parser import parse

from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

from courses import Courses
from config import USERCALENDARID

# Global: list of courses
courses = Courses()


# -----------------------------
# Google Calendar Authentication
# -----------------------------

def authenticate():
    """
    Authenticate with Google Calendar API, return service object.
    Caches token in token.pickle for reuse.
    """
    SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"]
    creds = None

    if os.path.exists("token.pickle"):
        with open("token.pickle", "rb") as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            print("Refreshing credentials")
            creds.refresh(Request())
        else:
            print("Authorizing new credentials")
            flow = InstalledAppFlow.from_client_secrets_file("credentials.json", SCOPES)
            creds = flow.run_local_server(port=0)
        with open("token.pickle", "wb") as token:
            pickle.dump(creds, token)

    return build("calendar", "v3", credentials=creds)


# -----------------------------
# Formatting helpers
# -----------------------------

def join(*args):
    return " ".join(str(e) for e in args if e)


def truncate(string, length):
    ellipsis = " ..."
    return string if len(string) < length else string[: length - len(ellipsis)] + ellipsis


def summary(text):
    return truncate(re.sub(r"X[0-9A-Za-z]+", "", text).strip(), 50)


def gray(text):
    return "%{F#999999}" + text + "%{F-}"


def formatdd(begin, end):
    """
    Format a time delta into minutes or hours string.
    """
    minutes = math.ceil((end - begin).seconds / 60)

    if minutes == 1:
        return "1 minuut"
    if minutes < 60:
        return f"{minutes} min"

    hours = math.floor(minutes / 60)
    rest_minutes = minutes % 60

    if hours > 5 or rest_minutes == 0:
        return f"{hours} uur"

    return f"{hours}:{rest_minutes:02d} uur"


def location(text):
    if not text:
        return ""
    match = re.search(r"\((.*)\)", text)
    return f"{gray('in')} {match.group(1)}" if match else ""


# -----------------------------
# Event processing
# -----------------------------

def event_text(events, now):
    """
    Produce status string based on current and next events.
    """
    current = next((e for e in events if e["start"] < now < e["end"]), None)

    if not current:
        nxt = next((e for e in events if now <= e["start"]), None)
        if nxt:
            return join(
                summary(nxt["summary"]),
                gray("over"),
                formatdd(now, nxt["start"]),
                location(nxt["location"]),
            )
        return ""

    nxt = next((e for e in events if e["start"] >= current["end"]), None)
    if not nxt:
        return join(gray("Einde over"), formatdd(now, current["end"]) + "!")

    if current["end"] == nxt["start"]:
        return join(
            gray("Einde over"),
            formatdd(now, current["end"]) + gray("."),
            gray("Hierna"),
            summary(nxt["summary"]),
            location(nxt["location"]),
        )

    return join(
        gray("Einde over"),
        formatdd(now, current["end"]) + gray("."),
        gray("Hierna"),
        summary(nxt["summary"]),
        location(nxt["location"]),
        gray("na een pauze van"),
        formatdd(current["end"], nxt["start"]),
    )


def activate_course(event):
    """
    Match event summary with course title and set current course.
    """
    course = next(
        (c for c in courses if c.info["title"].lower() in event["summary"].lower()),
        None,
    )
    if course:
        courses.current = course


# -----------------------------
# Event fetching
# -----------------------------

def get_events(service, calendar, morning, evening):
    """
    Fetch all events for a given calendar between morning and evening.
    """
    events_result = service.events().list(
        calendarId=calendar,
        timeMin=morning.isoformat(),
        timeMax=evening.isoformat(),
        singleEvents=True,
        orderBy="startTime",
    ).execute()

    return [
        {
            "summary": e["summary"],
            "location": e.get("location", None),
            "start": parse(e["start"]["dateTime"]),
            "end": parse(e["end"]["dateTime"]),
        }
        for e in events_result.get("items", [])
        if "dateTime" in e["start"]
    ]


# -----------------------------
# Network helper
# -----------------------------

def wait_for_internet_connection(url, timeout=5):
    """
    Block until an internet connection is available.
    """
    while True:
        conn = httplib.HTTPConnection(url, timeout=timeout)
        try:
            conn.request("HEAD", "/")
            conn.close()
            return True
        except Exception:
            conn.close()


# -----------------------------
# Main
# -----------------------------

def main():
    scheduler = sched.scheduler(time.time, time.sleep)

    tz = pytz.timezone(os.environ.get("TZ", "Europe/Brussels"))

    service = authenticate()

    now = datetime.datetime.now(tz=tz)
    morning = now.replace(hour=6, minute=0, microsecond=0)
    evening = now.replace(hour=23, minute=59, microsecond=0)

    events = get_events(service, USERCALENDARID, morning, evening)

    DELAY = 60

    def print_message():
        now = datetime.datetime.now(tz=tz)
        print(event_text(events, now))
        if now < evening:
            scheduler.enter(DELAY, 1, print_message)

    for event in events:
        scheduler.enterabs(
            event["start"].timestamp(), 1, activate_course, argument=(event,)
        )

    scheduler.enter(0, 1, print_message)
    scheduler.run()


if __name__ == "__main__":
    os.chdir(sys.path[0])
    print("Waiting for connection...")
    wait_for_internet_connection("www.google.com")
    main()