From d7b842288aad804eab783131e0fb1f875974964d Mon Sep 17 00:00:00 2001
From: Adeel Ahmad
Date: Thu, 15 Oct 2026 11:17:07 +0000
Subject: [PATCH] feat(sources): Google Calendar as a sensor, as a service
account or a connected Google account
A new source type, gcal, reads Google Calendar through the Calendar API with
read-only access: each calendar is a folder and each event a file
/.ics, read as text exactly as an iCal feed's events
are, so browsing, choosing events, watching and importing work unchanged.
It signs in as a service account (its key file; acting as a Workspace user
through domain-wide delegation with impersonate) or as a connected Google
account (an OAuth client's authorized user JSON). google_auth.py is the shared
sign-in layer for Google sources: JWT bearer and refresh-token access tokens,
cached in memory, every call to Google a row in the activity ledger, and
Google's own token endpoint whatever a key file says.
Events carry cancelled occurrences (EXDATE) and their video call, which the
event text now shows for iCal feeds too. The web app's connection dialog gains
the Google Calendar form; docs, changelog and threat model describe it.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01CGVfwJfXV4MiUhSyusia64
---
CHANGELOG.md | 8 +-
README.md | 2 +-
docs/assistant-email.md | 2 +-
docs/processing.md | 29 +-
docs/sensors.md | 2 +-
fastapi_backend/app/domain/calendars.py | 16 +-
fastapi_backend/app/domain/feeds.py | 19 +-
fastapi_backend/app/domain/gcal.py | 403 ++++++++++++++++++
fastapi_backend/app/domain/google_auth.py | 218 ++++++++++
fastapi_backend/app/domain/sources.py | 29 +-
fastapi_backend/app/schemas/sources.py | 2 +-
.../tests/api/test_google_calendar_source.py | 284 ++++++++++++
fastapi_backend/tests/fake_google.py | 162 +++++++
.../__tests__/sources-model.test.ts | 48 +++
.../app/openapi-client/types.gen.ts | 4 +-
.../components/sources/connection-fields.tsx | 130 ++++--
.../components/sources/source-icons.tsx | 2 +
.../components/sources/source-model.ts | 59 ++-
nextjs-frontend/openapi.json | 6 +-
threat-model.json | 10 +
threat-model.md | 1 +
threat-model.yaml | 12 +-
22 files changed, 1380 insertions(+), 68 deletions(-)
create mode 100644 fastapi_backend/app/domain/gcal.py
create mode 100644 fastapi_backend/app/domain/google_auth.py
create mode 100644 fastapi_backend/tests/api/test_google_calendar_source.py
create mode 100644 fastapi_backend/tests/fake_google.py
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1d7513f7c..1f2363a43 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,12 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version
## Unreleased
+- **Google Calendar as a sensor.** Add a Google Calendar connection on the Sources page (or `POST /api/v1/sources`
+ with type `gcal`): each calendar is a folder and each event becomes text, as an iCal feed's do, read-only through
+ Google's Calendar API. It signs in as a Google account (an OAuth client's authorized user JSON) or as a service
+ account, which reads the calendars shared with it or, in Google Workspace, a user's calendars through domain-wide
+ delegation. Calls to Google show in the activity ledger
+ ([Google Calendar](docs/processing.md#email-imap-calendar-feeds-ical-and-google-calendar)).
- **The assistant always answers.** When a question used up its tool steps (`ai.max_steps`), the assistant used to stop
with "I ran out of steps before finishing". Now it's asked to answer from what it found, with the tools off, and says
what it didn't get to check; a reply with nothing in it is asked again the same way. It also knows its step budget up
@@ -828,7 +834,7 @@ The backend (`fastapi_backend`) and the frontend (`nextjs-frontend`) are version
`POST …/{tid}/secret` and `GET …/{tid}/deliveries` (docs/api.md).
- **Email and calendars as sources.** Sources can now be an email account (IMAP) or a calendar feed (iCal), next to
S3, Drive, SFTP and the rest. Browse them, import chosen messages or events, or watch them like a folder
- (docs/processing.md#email-imap-and-calendar-feeds-ical).
+ (docs/processing.md#email-imap-calendar-feeds-ical-and-google-calendar).
- IMAP: mailboxes are folders and messages are `.eml` files named by their subjects. Each message becomes an
email document, titled by its subject and dated when it was sent, and its attachments are kept and become
resources of their own. Watching the whole account skips the bin, junk, drafts and Gmail's All Mail, Starred
diff --git a/README.md b/README.md
index a1c189969..1f6d68b5c 100644
--- a/README.md
+++ b/README.md
@@ -80,7 +80,7 @@ Everything below is built and merged. Work that is still in a pull request is li
([Extending the assistant](docs/assistant.md#extending-the-assistant-tools-skills-hooks-and-plugins),
[the MCP runner](docs/assistant.md#the-mcp-runner))
- **Bring in everything.** Watched folders on S3, Dropbox, Google Drive, OneDrive, SFTP, SMB, WebDAV or local disks
- (a local folder in four clicks); IMAP mail and iCal calendars; a built-in MQTT broker, syslog and webhook streams;
+ (a local folder in four clicks); IMAP mail, iCal calendars and Google Calendar; a built-in MQTT broker, syslog and webhook streams;
import webhooks for scanners and phone shortcuts. Upload audio, video, PDFs, Office files, photos, JSON and zip or
tar archives, and, with an Apache Tika server (an opt-in extra), documents nothing else here can read; capture web
pages one at a time, from a link list or a bookmarks file, by API or by asking the assistant, from private networks
diff --git a/docs/assistant-email.md b/docs/assistant-email.md
index b6c44e689..0e954b8ce 100644
--- a/docs/assistant-email.md
+++ b/docs/assistant-email.md
@@ -71,7 +71,7 @@ subject: newsletter = skip
A rule's conditions are on `from`, `to` (To, Cc and the address it arrived at), `subject`, `list` (List-Id) and
`mailbox`, joined by `;`, with patterns joined by `,`. Patterns work as in an email watch's routing rules
-([Processing](processing.md#email-imap-and-calendar-feeds-ical)): one without `*` or `?` matches anywhere in the
+([Processing](processing.md#email-imap-calendar-feeds-ical-and-google-calendar)): one without `*` or `?` matches anywhere in the
text. `skip` leaves the email unanswered. When no rule matches, or a rule names a namespace that doesn't exist, Lens
picks the namespace for each question, as in an open chat room ([Chat rooms](chat-rooms.md)).
diff --git a/docs/processing.md b/docs/processing.md
index adbfa7260..73875f7de 100644
--- a/docs/processing.md
+++ b/docs/processing.md
@@ -289,7 +289,7 @@ A folder scan and a routine run are each claimed first, so several processes doi
## Storage sources
Admins add sources in the app (`/api/v1/sources`): S3 or S3-compatible, Dropbox, Google Drive, OneDrive, SFTP, SMB,
-WebDAV, or a folder on this machine; or an email account (IMAP) or a calendar feed (iCal), below. A watched folder maps a path on a source to a namespace, with include/exclude
+WebDAV, or a folder on this machine; or an email account (IMAP), a calendar feed (iCal) or Google Calendar, below. A watched folder maps a path on a source to a namespace, with include/exclude
patterns, audio and/or transcripts, a polling interval, how long a file must be unchanged before it is picked up, and
whether files already there are imported (backfill). New audio is queued for the full pipeline; new transcripts are
imported and analysed. Audio stays where it is: it is copied to a cache for processing and streamed from the source for
@@ -311,9 +311,9 @@ files, then Import (`POST /api/v1/import/source`). The listing marks files that
- Folders on this machine can only be watched inside `sources.local_roots`, and the rclone binary can only be set in
archive.yaml: the web app can neither open up the server's disk nor choose what runs.
-### Email (IMAP) and calendar feeds (iCal)
+### Email (IMAP), calendar feeds (iCal) and Google Calendar
-Two kinds of source aren't storage and don't use rclone; their messages and events are shown as files, so browsing,
+Three kinds of source aren't storage and don't use rclone; their messages and events are shown as files, so browsing,
importing chosen ones and watching work as above.
- **Email (IMAP)**: host, port, security (SSL/TLS, STARTTLS or none), user and password (an app password where the
@@ -344,6 +344,29 @@ importing chosen ones and watching work as above.
attendees, how it repeats, and its description), dated when it starts: an all-day event on its date, wherever you
are. Time zones are read as IANA names, Windows' names (as Outlook writes them), or the calendar's own VTIMEZONE. An event that changes (its LAST-MODIFIED,
or its size) is read again into the resource it already is, rather than made a second one.
+- **Google Calendar** (`gcal`): read through Google's Calendar API with read-only access (`calendar.readonly`), so
+ nothing in the calendar is changed. Each calendar is a folder and each event a file `/.ics`,
+ named by its date and title, and read as text exactly as an iCal feed's events are; it also says which occurrences
+ of a repeating event were cancelled and the event's video call. A changed occurrence of a repeating event is an event
+ of its own, as Google keeps it; working-location entries ("Home", "Office") are left out. It signs in one of two ways,
+ each kept encrypted like a password and never shown again:
+
+ - **Google account** (`token`): the "authorized user" JSON (`client_id`, `client_secret`, `refresh_token`) of an
+ OAuth client of your own Google Cloud project, with the Calendar API turned on there. `gcloud auth
+ application-default login --client-id-file=client.json --scopes=https://www.googleapis.com/auth/calendar.readonly,https://www.googleapis.com/auth/cloud-platform`
+ writes one (to `application_default_credentials.json` in gcloud's folder).
+ - **Service account** (`service_account_credentials`, its .json key file). On its own it reads the calendars shared
+ with its address: share them, and give their IDs in `calendars` (Google Calendar › Settings › Integrate
+ calendar). In Google Workspace it can read a user's calendars instead (`impersonate`), once an admin gave it
+ domain-wide delegation for the `calendar.readonly` scope (Admin console › Security › API controls).
+
+ `calendars` (IDs, comma separated) limits the source to those; empty, it reads every calendar in the account's
+ list, and watching the whole account (no path) leaves out Google's own (holidays, birthdays, week numbers). Events
+ that ended more than `days_back` days ago (365) are left out; empty takes every event. A watch lists each calendar
+ again every poll (`events.list`, 2,500 events a call). Every call to Google is a row in the activity ledger
+ (`google.token`, `google.calendar`); Google throttling the account shows as working, slowly, and a scan it
+ interrupts is tried again at the next poll. The token endpoint is always Google's own, whatever a key file says. Without a Google Cloud project,
+ a Google calendar's secret address in iCal format (Settings › Integrate calendar) works as a calendar feed.
- `.eml` and `.ics` files in any source, and uploaded through Import, can be read as text this way too.
## Pipelines and templates
diff --git a/docs/sensors.md b/docs/sensors.md
index edce29e9d..727286793 100644
--- a/docs/sensors.md
+++ b/docs/sensors.md
@@ -4,7 +4,7 @@ A **sensor** is anything that feeds Lens. There are two families, in one list (`
| Family | Kinds | Channels | What it reports becomes |
| --- | --- | --- | --- |
-| Files | S3, Dropbox, Google Drive, OneDrive, SFTP, SMB, WebDAV, a local folder (through rclone); email (IMAP); calendar feeds (iCal) | the folders it watches | resources, run through their pipelines (as sources always have) |
+| Files | S3, Dropbox, Google Drive, OneDrive, SFTP, SMB, WebDAV, a local folder (through rclone); email (IMAP); calendar feeds (iCal); Google Calendar | the folders it watches | resources, run through their pipelines (as sources always have) |
| Streams | MQTT devices, syslog senders, webhooks | streams: an MQTT topic, a syslog program, a webhook's stream name | readings, kept with retention, and hourly summaries of anything numeric |
File sensors are the storage sources: they are added and changed as sources (`/api/v1/sources`), and nothing about
diff --git a/fastapi_backend/app/domain/calendars.py b/fastapi_backend/app/domain/calendars.py
index cacc0c6cb..8203be6b0 100644
--- a/fastapi_backend/app/domain/calendars.py
+++ b/fastapi_backend/app/domain/calendars.py
@@ -350,18 +350,28 @@ def _span(event):
return f"{_shown(s)} to {_shown(end)}"
+def _skipped(event):
+ """The occurrences of a repeating event that don't happen (its EXDATEs), in order."""
+ out = [when(p, x, event.get("zones")) for p, v in all_of(event, "EXDATE") for x in (v or "").split(",")]
+ return sorted((t for t in out if t is not None), key=iso)
+
+
def event_text(event):
- """An event as Markdown: its summary as the heading, when and where, who, how it repeats, then its description.
- The details are 'Label — value' lines, so the transcript reader doesn't take them for speakers."""
+ """An event as Markdown: its summary as the heading, when and where, who, how it repeats (and the occurrences that
+ don't happen), its video call, then its description. The details are 'Label — value' lines, so the transcript
+ reader doesn't take them for speakers."""
title = summary(event) or "(no title)"
rows = [("When", _span(event))]
rows.append(("Where", unescape(first(event, "LOCATION")[1] or "").strip()))
p, v = first(event, "ORGANIZER")
rows.append(("Organizer", _person(p, v) if v else ""))
rows.append(("Attendees", ", ".join(_person(p, v) for p, v in all_of(event, "ATTENDEE"))))
- rows.append(("Repeats", (first(event, "RRULE")[1] or "").strip()))
+ rule = (first(event, "RRULE")[1] or "").strip()
+ rows.append(("Repeats", rule))
+ rows.append(("Except", "; ".join(_shown(t) for t in _skipped(event)) if rule else ""))
status = (first(event, "STATUS")[1] or "").strip().lower()
rows.append(("Status", status if status and status != "confirmed" else ""))
+ rows.append(("Meeting", (first(event, "CONFERENCE")[1] or "").strip()))
rows.append(("Link", (first(event, "URL")[1] or "").strip()))
head = [f"{k} — {v}" for k, v in rows if v]
desc = unescape(first(event, "DESCRIPTION")[1] or "").strip()
diff --git a/fastapi_backend/app/domain/feeds.py b/fastapi_backend/app/domain/feeds.py
index 6560b0eb0..b02ead6e8 100644
--- a/fastapi_backend/app/domain/feeds.py
+++ b/fastapi_backend/app/domain/feeds.py
@@ -1,5 +1,5 @@
-"""Sources that aren't file storage: IMAP mailboxes and iCalendar feeds, shown as folders of files so browsing,
-choosing files, watching and importing work for them as they do for rclone's storage (sources.py).
+"""Sources that aren't file storage: IMAP mailboxes, iCalendar feeds and Google Calendar (gcal.py), shown as folders of
+files so browsing, choosing files, watching and importing work for them as they do for rclone's storage (sources.py).
- An IMAP account's folders are its mailboxes, and each message is a file, `/-.eml`: a
UID stands for one message only while the mailbox's UIDVALIDITY stays the same, so a mailbox the server rebuilt
@@ -34,8 +34,10 @@
import urllib.request
from email import policy
-from . import calendars, netguard
+from . import calendars, gcal, netguard
+# sources a module of their own handles: browse, list_files, fetch, immutable and test, as below
+OWN = {"gcal": gcal}
TYPES = {
"imap": {
"label": "Email (IMAP)",
@@ -47,6 +49,7 @@
"fields": {"user": ""},
"secrets": ["url", "pass"],
},
+ **{k: m.TYPE for k, m in OWN.items()},
}
SECURITY = ("ssl", "starttls", "none")
# not taken when a whole account is watched: what can't be opened, the bin, junk and drafts, and the mailboxes that
@@ -487,6 +490,8 @@ def check_path(path):
def browse(cfg, src, path=""):
+ if src["type"] in OWN:
+ return OWN[src["type"]].browse(cfg, src, check_path(path))
return (_imap_browse if src["type"] == "imap" else _ical_browse)(cfg, src, check_path(path))
@@ -494,6 +499,8 @@ def list_files(cfg, src, path="", cursor=None):
"""Every file under `path`; for IMAP with a watch's `cursor` (a list of {mailbox, validity, uid}), only messages
after it."""
path = check_path(path)
+ if src["type"] in OWN:
+ return OWN[src["type"]].list_files(cfg, src, path, cursor)
if src["type"] == "imap":
return _imap_files(cfg, src, path, {c["mailbox"]: c for c in cursor or []})
return _ical_browse(cfg, src, path)
@@ -501,13 +508,19 @@ def list_files(cfg, src, path="", cursor=None):
def fetch(cfg, src, path):
"""The file's bytes: a message as the server keeps it, an event as an .ics of its own."""
+ if src["type"] in OWN:
+ return OWN[src["type"]].fetch(cfg, src, check_path(path))
return (_imap_fetch if src["type"] == "imap" else _ical_fetch)(cfg, src, check_path(path))
def immutable(src):
"""Whether a file, once fetched, never changes (an IMAP message), so a cached copy can be kept."""
+ if src["type"] in OWN:
+ return OWN[src["type"]].immutable(src)
return src["type"] == "imap"
def test(cfg, src):
+ if src["type"] in OWN:
+ return OWN[src["type"]].test(cfg, src)
(_imap_test if src["type"] == "imap" else _ical_test)(cfg, src)
diff --git a/fastapi_backend/app/domain/gcal.py b/fastapi_backend/app/domain/gcal.py
new file mode 100644
index 000000000..676663787
--- /dev/null
+++ b/fastapi_backend/app/domain/gcal.py
@@ -0,0 +1,403 @@
+"""Google Calendar as a source (a file sensor, as feeds.py's iCal feeds are), through the Calendar API: each calendar is
+a folder and each event a file `/.ics`, so browsing, choosing events, watching and importing
+work as they do for any source.
+
+It signs in as a service account or a connected Google account (google_auth.py), with read-only access
+(calendar.readonly): nothing is changed in the calendar. `calendars` (calendar ids, comma separated) limits it to
+those; otherwise it reads the account's own calendar list, which a service account only has when it acts as a
+Workspace user (`impersonate`): share a calendar with the service account's address and give its id instead.
+Watching the whole account (no path) takes every calendar in it but Google's own (holidays, birthdays, week
+numbers). Events that ended more than `days_back` days ago are left out (empty: all of them).
+
+An event is written as an iCalendar event of its own (its title, when and where, organizer and attendees with their
+answers, how it repeats and the occurrences cancelled, status, video call, its page in Google Calendar, and when it
+was created and changed), so it is read as text exactly as an iCal feed's events are (calendars.py). A changed
+occurrence of a repeating event is an event of its own, as Google keeps it. Working-location entries ("Home",
+"Office") aren't events and are left out.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import html
+import re
+import time
+import urllib.parse
+from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+from . import calendars, google_auth
+
+API = "https://www.googleapis.com/calendar/v3"
+SCOPES = ("https://www.googleapis.com/auth/calendar.readonly",)
+TYPE = {
+ "label": "Google Calendar",
+ "fields": {"calendars": "", "impersonate": "", "days_back": "365"},
+ "secrets": ["token", "service_account_credentials"],
+ "google": True, # signs in through google_auth.py
+}
+SYSTEM = "group.v.calendar.google.com" # Google's own calendars (holidays, birthdays, week numbers) end so
+SKIP_TYPES = {"workingLocation"}
+PAGE = 2500 # the most events.list gives at once
+MAX_PAGES = 40
+LIST_SECONDS = 60 # a calendar listed for a scan is reused this long (the scan then reads each of its events)
+EPOCH = "1970-01-01T00:00:00+00:00"
+_LISTED: dict = {} # (source id, calendar id) -> (monotonic time, {event id.ics: (entry, body)})
+_CALENDARS: dict = {} # source id -> (monotonic time, its calendars)
+PARTSTAT = {"needsAction": "NEEDS-ACTION", "accepted": "ACCEPTED", "declined": "DECLINED", "tentative": "TENTATIVE"}
+
+
+def _params(src):
+ return {k: str(v).strip() for k, v in (src.get("params") or {}).items() if v is not None}
+
+
+def _call(cfg, src, path, params=None, what=None):
+ creds = google_auth.credentials(cfg, src)
+ return google_auth.get(cfg, creds, SCOPES, API + path, params, api="calendar", what=what)
+
+
+def _q(cal_id):
+ return urllib.parse.quote(cal_id, safe="@")
+
+
+# ---------- calendars ----------
+def _chosen(src):
+ return [c.strip() for c in re.split(r"[,\s]+", _params(src).get("calendars", "")) if c.strip()]
+
+
+def calendars_of(cfg, src):
+ """[{id, name, zone}] of the calendars this source reads: the chosen ones, else the account's calendar list (those
+ it can read events of), reused for LIST_SECONDS."""
+ hit = _CALENDARS.get(src["id"])
+ if hit and time.monotonic() - hit[0] < LIST_SECONDS and hit[1] == _chosen(src):
+ return hit[2]
+ out = _calendars(cfg, src)
+ _CALENDARS[src["id"]] = (time.monotonic(), _chosen(src), out)
+ return out
+
+
+def _calendars(cfg, src):
+ chosen = _chosen(src)
+ if chosen:
+ out = []
+ for cid in chosen:
+ try:
+ c = _call(cfg, src, f"/calendars/{_q(cid)}", what="calendars.get")
+ except FileNotFoundError:
+ raise ValueError(
+ f"there's no calendar {cid}, or it isn't shared with {google_auth.who(google_auth.credentials(cfg, src))}"
+ ) from None
+ out.append({"id": c.get("id") or cid, "name": c.get("summary") or cid, "zone": c.get("timeZone")})
+ return out
+ out, token = [], None
+ for _ in range(MAX_PAGES):
+ q = {"minAccessRole": "reader", "maxResults": 250, **({"pageToken": token} if token else {})}
+ page = _call(cfg, src, "/users/me/calendarList", q, what="calendarList.list")
+ for c in page.get("items") or []:
+ if c.get("id") and not c.get("deleted"):
+ out.append(
+ {
+ "id": c["id"],
+ "name": c.get("summaryOverride") or c.get("summary") or c["id"],
+ "zone": c.get("timeZone"),
+ "primary": bool(c.get("primary")),
+ }
+ )
+ token = page.get("nextPageToken")
+ if not token:
+ break
+ return sorted(out, key=lambda c: (not c.get("primary"), c["name"].lower()))
+
+
+# ---------- an event as iCalendar ----------
+def _plain(v):
+ """A value written as it is (an address, a link, a rule): on one line, without control characters."""
+ return re.sub(r"[\x00-\x1f\x7f]", "", str(v)).strip()
+
+
+def _escape(v):
+ return (
+ re.sub(r"[\x00-\x09\x0b-\x1f\x7f]", "", str(v))
+ .replace("\\", "\\\\")
+ .replace(";", "\\;")
+ .replace(",", "\\,")
+ .replace("\r\n", "\n")
+ .replace("\n", "\\n")
+ )
+
+
+def _param(v):
+ v = re.sub(r'[\x00-\x1f"]', "", str(v))
+ return f'"{v}"' if re.search(r"[;:,]", v) else v
+
+
+def _fold(line):
+ """A content line folded at 75 characters, continuations starting with a space (RFC 5545 §3.1)."""
+ out = [line[:75]]
+ rest = line[75:]
+ while rest:
+ out.append(" " + rest[:74])
+ rest = rest[74:]
+ return "\r\n".join(out)
+
+
+def _zone(name):
+ try:
+ return ZoneInfo(name) if name else None
+ except (ZoneInfoNotFoundError, ValueError):
+ return None
+
+
+def _instant(v):
+ try:
+ t = dt.datetime.fromisoformat(re.sub(r"(\.\d{6})\d+", r"\1", v.replace("Z", "+00:00")))
+ except (ValueError, AttributeError):
+ return None
+ return t if t.tzinfo else t.replace(tzinfo=dt.timezone.utc)
+
+
+def _when(name, t, zone):
+ """'DTSTART;TZID=Europe/Berlin:20261002T100000', 'DTSTART;VALUE=DATE:20261017' or 'DTSTART:20261002T080000Z'
+ for Google's {dateTime, timeZone} or {date}; None when there's neither."""
+ t = t or {}
+ if t.get("date"):
+ return f"{name};VALUE=DATE:{t['date'].replace('-', '')}"
+ at = _instant(t.get("dateTime"))
+ if at is None:
+ return None
+ z = _zone(t.get("timeZone")) or _zone(zone)
+ if z is not None and str(z) not in ("UTC", "Etc/UTC"):
+ return f"{name};TZID={z}:{at.astimezone(z):%Y%m%dT%H%M%S}"
+ return f"{name}:{at.astimezone(dt.timezone.utc):%Y%m%dT%H%M%SZ}"
+
+
+def _stamp(v):
+ at = _instant(v)
+ return at.astimezone(dt.timezone.utc).strftime("%Y%m%dT%H%M%SZ") if at else None
+
+
+def _text(desc):
+ """A description as text: Google Calendar's web app writes some as HTML (line breaks, links, lists)."""
+ if not re.search(r"<(br|/?p|/?div|/?ul|/?ol|li|a|b|i|u|span)\b", desc or "", re.I):
+ return desc or ""
+ t = re.sub(
+ r"]*href=\"([^\"]*)\"[^>]*>(.*?)",
+ lambda m: m.group(2) if html.unescape(m.group(1)) in (m.group(2), "") else f"{m.group(2)} ({m.group(1)})",
+ desc,
+ flags=re.I | re.S,
+ )
+ t = re.sub(r" |