"""iCalendar (``.ics``) export of backed-up events and tasks.
Events become ``VEVENT`` and tasks ``VTODO`` components (RFC 5545), which
Outlook, Apple Calendar, Google Calendar and Thunderbird import.
Graph stores times in UTC (``Prefer: outlook.timezone`` is not sent), with
the zone the organizer used (``originalStartTimeZone``, usually a Windows
name such as "Pacific Standard Time"). Times are written in that zone, as
an IANA name with its ``VTIMEZONE``, so a weekly 09:00 meeting stays at
09:00 across daylight saving time. All-day events and due dates are plain
dates.
Not in the export: single occurrences of a recurring meeting that were
changed or cancelled (Graph's backup has the series only), attachments,
and To Do checklist steps as separate items (they are listed in the
description).
"""
from __future__ import annotations
from datetime import UTC, date, datetime, timedelta
from typing import Any
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from icalendar import Alarm, Calendar, Component, Event, Todo, vCalAddress, vText
from icalendar.timezone.windows_to_olson import WINDOWS_TO_OLSON
from s365b.core.mailview import html_to_text
[docs]
PRODID = "-//Mail Safehouse//Backup export//EN"
[docs]
DAYS = {
"sunday": "SU",
"monday": "MO",
"tuesday": "TU",
"wednesday": "WE",
"thursday": "TH",
"friday": "FR",
"saturday": "SA",
}
[docs]
POSITION = {"first": 1, "second": 2, "third": 3, "fourth": 4, "last": -1}
[docs]
PARTSTAT = {
"accepted": "ACCEPTED",
"declined": "DECLINED",
"tentativelyAccepted": "TENTATIVE",
"none": "NEEDS-ACTION",
"notResponded": "NEEDS-ACTION",
}
[docs]
ROLE = {"required": "REQ-PARTICIPANT", "optional": "OPT-PARTICIPANT", "resource": "NON-PARTICIPANT"}
[docs]
TODO_STATUS = {
"notStarted": "NEEDS-ACTION",
"inProgress": "IN-PROCESS",
"completed": "COMPLETED",
"waitingOnOthers": "NEEDS-ACTION",
"deferred": "NEEDS-ACTION",
}
[docs]
PRIORITY = {"high": 1, "normal": 5, "low": 9}
[docs]
def zone(name: str | None) -> ZoneInfo:
"""The IANA zone for a Graph time zone name (Windows or IANA); UTC if unknown.
Args:
name: E.g. "Pacific Standard Time" or "Europe/Paris".
Returns:
The zone.
"""
if not name:
return ZoneInfo("UTC")
for candidate in (WINDOWS_TO_OLSON.get(name), name):
if candidate:
try:
return ZoneInfo(candidate)
except (ZoneInfoNotFoundError, ValueError):
continue
return ZoneInfo("UTC")
def _utc(value: dict[str, Any] | None) -> datetime | None:
"""A Graph ``dateTimeTimeZone`` as an aware datetime."""
if not value or not value.get("dateTime"):
return None
try:
naive = datetime.fromisoformat(str(value["dateTime"]).split(".")[0])
except ValueError:
return None
return naive.replace(tzinfo=zone(value.get("timeZone")))
def _stamp(value: Any) -> datetime | None:
"""A Graph ``DateTimeOffset`` string as an aware UTC datetime."""
if not value:
return None
try:
parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00"))
except ValueError:
return None
return (parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)).astimezone(UTC)
def _text(body: dict[str, Any] | None) -> str:
"""A Graph ``itemBody`` as plain text."""
if not body or not body.get("content"):
return ""
content = str(body["content"])
text = html_to_text(content) if body.get("contentType") == "html" else content
return text.strip()
[docs]
def rrule(recurrence: dict[str, Any] | None, start: datetime | date) -> dict[str, Any] | None:
"""A Graph ``patternedRecurrence`` as an iCalendar ``RRULE``.
Args:
recurrence: The recurrence from Graph.
start: The first occurrence (a date for all-day events and tasks).
Returns:
The rule's parts, or ``None`` if there is no (supported) recurrence.
"""
if not recurrence:
return None
pattern = recurrence.get("pattern") or {}
rng = recurrence.get("range") or {}
kind = pattern.get("type")
rule: dict[str, Any] = {"interval": int(pattern.get("interval") or 1)}
days = [DAYS[d] for d in pattern.get("daysOfWeek") or [] if d in DAYS]
position = POSITION.get(str(pattern.get("index") or "first"), 1)
if kind == "daily":
rule["freq"] = "DAILY"
elif kind == "weekly":
rule["freq"] = "WEEKLY"
if days:
rule["byday"] = days
if pattern.get("firstDayOfWeek") in DAYS:
rule["wkst"] = DAYS[pattern["firstDayOfWeek"]]
elif kind == "absoluteMonthly":
rule.update(freq="MONTHLY", bymonthday=int(pattern.get("dayOfMonth") or 1))
elif kind == "relativeMonthly":
rule.update(freq="MONTHLY", byday=days, bysetpos=position)
elif kind == "absoluteYearly":
rule.update(
freq="YEARLY",
bymonth=int(pattern.get("month") or 1),
bymonthday=int(pattern.get("dayOfMonth") or 1),
)
elif kind == "relativeYearly":
rule.update(
freq="YEARLY", bymonth=int(pattern.get("month") or 1), byday=days, bysetpos=position
)
else:
return None
if rng.get("type") == "numbered" and rng.get("numberOfOccurrences"):
rule["count"] = int(rng["numberOfOccurrences"])
elif rng.get("type") == "endDate" and rng.get("endDate"):
last = date.fromisoformat(str(rng["endDate"]))
if isinstance(start, datetime):
# The whole last day, in the series' zone, as UTC (RFC 5545 3.3.10).
end = datetime.combine(last, start.timetz()).replace(tzinfo=start.tzinfo)
rule["until"] = end.astimezone(UTC)
else:
rule["until"] = last
return rule
def _alarm(trigger: timedelta | datetime, summary: str) -> Alarm:
alarm = Alarm()
alarm.add("action", "DISPLAY")
alarm.add("description", summary or "Reminder")
alarm.add("trigger", trigger)
return alarm
def _person(value: dict[str, Any] | None) -> vCalAddress | None:
ea = (value or {}).get("emailAddress") or {}
if not ea.get("address"):
return None
person = vCalAddress(f"mailto:{ea['address']}")
if ea.get("name"):
person.params["cn"] = vText(str(ea["name"]))
return person
[docs]
def event_component(event: dict[str, Any]) -> Event:
"""A backed-up event as a ``VEVENT``.
Args:
event: The event as Graph returned it.
Returns:
The component.
"""
out = Event()
out.add("uid", str(event.get("iCalUId") or event.get("id")))
summary = str(event.get("subject") or "")
out.add("summary", summary)
tz = zone(event.get("originalStartTimeZone"))
start, end = _utc(event.get("start")), _utc(event.get("end"))
first: datetime | date | None = None
if event.get("isAllDay") and start is not None:
# Graph gives all-day events as midnight-to-midnight dates labelled
# UTC, whatever the event's zone (seen in real backups): the dates
# are taken as they are, not converted.
first = start.date()
out.add("dtstart", first)
if end is not None:
out.add("dtend", end.date())
elif start is not None:
first = start.astimezone(tz)
out.add("dtstart", first)
if end is not None:
end_zone = event.get("originalEndTimeZone") or event.get("originalStartTimeZone")
out.add("dtend", end.astimezone(zone(end_zone)))
if first is not None and (rule := rrule(event.get("recurrence"), first)):
out.add("rrule", rule)
stamp = _stamp(event.get("lastModifiedDateTime")) or datetime.now(UTC)
out.add("dtstamp", stamp)
out.add("last-modified", stamp)
if created := _stamp(event.get("createdDateTime")):
out.add("created", created)
if text := _text(event.get("body")):
out.add("description", text)
location = (event.get("location") or {}).get("displayName")
if location:
out.add("location", str(location))
if organizer := _person(event.get("organizer")):
out.add("organizer", organizer)
for attendee in event.get("attendees") or []:
person = _person(attendee)
if person is None:
continue
person.params["role"] = ROLE.get(str(attendee.get("type")), "REQ-PARTICIPANT")
response = str((attendee.get("status") or {}).get("response") or "none")
person.params["partstat"] = PARTSTAT.get(response, "NEEDS-ACTION")
out.add("attendee", person, encode=False)
out.add("status", "CANCELLED" if event.get("isCancelled") else "CONFIRMED")
out.add("transp", "TRANSPARENT" if event.get("showAs") == "free" else "OPAQUE")
if event.get("sensitivity") in ("private", "confidential"):
out.add("class", str(event["sensitivity"]).upper())
if event.get("categories"):
out.add("categories", [str(c) for c in event["categories"]])
join = (event.get("onlineMeeting") or {}).get("joinUrl")
if join:
out.add("url", str(join))
if event.get("isReminderOn") and event.get("reminderMinutesBeforeStart") is not None:
minutes = int(event["reminderMinutesBeforeStart"])
out.add_component(_alarm(timedelta(minutes=-minutes), summary))
return out
def _day_or_time(value: dict[str, Any] | None) -> datetime | date | None:
"""A To Do date: a plain date when it is midnight (how To Do stores dates)."""
when = _utc(value)
if when is None:
return None
if (when.hour, when.minute, when.second) == (0, 0, 0):
return when.date()
return when.astimezone(UTC)
[docs]
def task_component(task: dict[str, Any]) -> Todo:
"""A backed-up To Do task as a ``VTODO``.
Args:
task: The task as Graph returned it (with ``checklistItems`` if any).
Returns:
The component.
"""
out = Todo()
out.add("uid", str(task.get("id")))
summary = str(task.get("title") or "")
out.add("summary", summary)
stamp = _stamp(task.get("lastModifiedDateTime")) or datetime.now(UTC)
out.add("dtstamp", stamp)
out.add("last-modified", stamp)
if created := _stamp(task.get("createdDateTime")):
out.add("created", created)
status = str(task.get("status") or "notStarted")
out.add("status", TODO_STATUS.get(status, "NEEDS-ACTION"))
out.add("priority", PRIORITY.get(str(task.get("importance") or "normal"), 5))
start = _day_or_time(task.get("startDateTime"))
due = _day_or_time(task.get("dueDateTime"))
if start is not None:
out.add("dtstart", start)
if due is not None:
out.add("due", due)
if (completed := _utc(task.get("completedDateTime"))) is not None:
out.add("completed", completed.astimezone(UTC))
first = start or due
if first is not None and (rule := rrule(task.get("recurrence"), first)):
out.add("rrule", rule)
lines = [_text(task.get("body"))]
steps = task.get("checklistItems") or []
if steps:
lines.append(
"\n".join(
f"[{'x' if s.get('isChecked') else ' '}] {s.get('displayName') or ''}"
for s in steps
)
)
description = "\n\n".join(line for line in lines if line)
if description:
out.add("description", description)
if task.get("categories"):
out.add("categories", [str(c) for c in task["categories"]])
if task.get("isReminderOn") and (remind := _utc(task.get("reminderDateTime"))) is not None:
out.add_component(_alarm(remind.astimezone(UTC), summary))
return out
[docs]
def to_ics(items: list[tuple[str, dict[str, Any]]], name: str | None = None) -> bytes:
"""Events and tasks as one iCalendar file.
Args:
items: ``(item type, Graph JSON)`` pairs; types other than
``event`` and ``task`` are left out.
name: Calendar name shown by some programs (e.g. the calendar's).
Returns:
The ``.ics`` file.
"""
cal = Calendar()
cal.add("prodid", PRODID)
cal.add("version", "2.0")
if name:
cal.add("x-wr-calname", name)
builders = {"event": event_component, "task": task_component}
for item_type, data in items:
build = builders.get(item_type)
if build is not None:
component: Component = build(data)
cal.add_component(component)
cal.add_missing_timezones()
return bytes(cal.to_ical())