Source code for s365b.modules.exchange.items

"""Calendars and contacts of a mailbox.

Graph (v1.0) has no change feed for every calendar (only the primary
calendar's date-windowed view), so both are backed up the same way: each
folder is listed with only IDs and change keys, compared with what the
catalog has, and only new or changed items are fetched in full. A folder's
first backup lists full items instead, 50 at a time.

Items are stored as Graph's JSON. Graph is asked for immutable IDs, so an
item keeps its ID when it moves between folders. An item missing from its
folder's listing is a deletion only if it is in none of the folders backed
up (a deleted item usually moves to Deleted Items, a mail folder).

Restore copies (Exchange's export, as for mail) are added by the core after
each mailbox's backup, like for messages.
"""

from __future__ import annotations

import asyncio
import json
from collections.abc import AsyncIterator
from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any

from s365b.core.concurrency import all_or_cancel
from s365b.graph.client import GraphError
from s365b.modules.exchange.ics import zone
from s365b.modules.paths import join
from s365b.modules.sdk import GroupChange, ItemVersion, ModuleContext

[docs] IMMUTABLE = {"Prefer": 'IdType="ImmutableId"'}
[docs] LIST_PAGE = "100"
[docs] FETCH_PARALLEL = 4 # Exchange allows four concurrent requests per mailbox and app
[docs] DEFAULT_CONTACTS = "Contacts"
@dataclass(frozen=True, slots=True)
[docs] class Kind: """Calendars or contacts: where Graph keeps them and how they are stored. Attributes: item_type: Item type of the items. state_key: Key of the folder list in the mailbox's sync state. label: Progress text. """
[docs] item_type: str
[docs] state_key: str
[docs] label: str
[docs] def items_url(self, user: str, fid: str, default: bool) -> str: """The collection holding a folder's items.""" if self.item_type == "event": return f"/users/{user}/calendars/{fid}/events" if default: return f"/users/{user}/contacts" return f"/users/{user}/contactFolders/{fid}/contacts"
[docs] def item_url(self, user: str, key: str) -> str: """One item, wherever it is.""" kind = "events" if self.item_type == "event" else "contacts" return f"/users/{user}/{kind}/{key}"
[docs] def in_folder_url(self, user: str, fid: str, key: str) -> str: """One item, only if it is in this folder (404 otherwise).""" if self.item_type == "event": return f"/users/{user}/calendars/{fid}/events/{key}" return f"/users/{user}/contactFolders/{fid}/contacts/{key}"
[docs] CALENDARS = Kind("event", "calendars", "Calendars")
[docs] CONTACTS = Kind("contact", "contact_folders", "Contacts")
[docs] def normalise(item: dict[str, Any]) -> bytes: """Graph JSON without request context, with sorted keys. Args: item: An event or contact from Graph. Returns: UTF-8 JSON. """ clean = {k: v for k, v in item.items() if k not in ("@odata.context", "@odata.etag")} return json.dumps(clean, sort_keys=True, indent=2, ensure_ascii=False).encode()
def _address(value: dict[str, Any] | None) -> str: ea = (value or {}).get("emailAddress") or {} return str(ea.get("address") or ea.get("name") or "")
[docs] def when(value: dict[str, Any] | None, *, date_only: bool = False) -> str | None: """A Graph date and time with zone, for the browse view. Args: value: A Graph ``dateTimeTimeZone``. date_only: Return just the date (``YYYY-MM-DD``): for all-day events and To Do due dates, which are days, not instants. Returns: The date, or the instant in UTC as ISO 8601 (``...Z``). """ if not value or not value.get("dateTime"): return None stamp = str(value["dateTime"]).split(".")[0] if date_only: return stamp[:10] try: local = datetime.fromisoformat(stamp).replace(tzinfo=zone(value.get("timeZone"))) except ValueError: return stamp return local.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
[docs] def event_metadata(event: dict[str, Any], folder_id: str) -> dict[str, Any]: """Fields shown and searched in the browse view. Args: event: Event from Graph. folder_id: Its calendar. Returns: Metadata for the item version. """ meta: dict[str, Any] = { "folder_id": folder_id, "change_key": event.get("changeKey"), "start": when(event.get("start"), date_only=bool(event.get("isAllDay"))), "end": when(event.get("end"), date_only=bool(event.get("isAllDay"))), "organizer": _address(event.get("organizer")), } location = (event.get("location") or {}).get("displayName") if location: meta["location"] = location if event.get("isAllDay"): meta["all_day"] = True if event.get("type") == "seriesMaster": meta["recurring"] = True if event.get("isCancelled"): meta["cancelled"] = True return meta
[docs] def contact_metadata(contact: dict[str, Any], folder_id: str) -> dict[str, Any]: """Fields shown and searched in the browse view. Args: contact: Contact from Graph. folder_id: Its contact folder. Returns: Metadata for the item version. """ emails = [ str(e.get("address")) for e in contact.get("emailAddresses") or [] if e.get("address") ] phones = [ *([contact["mobilePhone"]] if contact.get("mobilePhone") else []), *(contact.get("businessPhones") or []), *(contact.get("homePhones") or []), ] meta: dict[str, Any] = {"folder_id": folder_id, "change_key": contact.get("changeKey")} if emails: meta["mail"] = emails[0] if phones: meta["phone"] = str(phones[0]) if contact.get("companyName"): meta["company"] = contact["companyName"] return meta
def _name(kind: Kind, item: dict[str, Any]) -> str: if kind.item_type == "event": return str(item.get("subject") or "(no subject)") return str( item.get("displayName") or item.get("fileAs") or " ".join(p for p in (item.get("givenName"), item.get("surname")) if p) or "(no name)" )
[docs] def modified(item: dict[str, Any]) -> datetime | None: """An item's ``lastModifiedDateTime``, if it has a readable one.""" value = item.get("lastModifiedDateTime") if not value: return None try: return datetime.fromisoformat(str(value).replace("Z", "+00:00")) except ValueError: return None
[docs] def version(kind: Kind, item: dict[str, Any], fid: str, path: str) -> ItemVersion: """The item version for an event or contact. Args: kind: Calendars or contacts. item: The full item from Graph. fid: Its folder. path: The folder's path. Returns: The version to store. """ meta = (event_metadata if kind.item_type == "event" else contact_metadata)(item, fid) return ItemVersion( item_key=str(item["id"]), item_type=kind.item_type, name=_name(kind, item), path=path, modified_at=modified(item), metadata=meta, content=normalise(item), )
[docs] async def calendars(ctx: ModuleContext, user: str, mail: str | None) -> dict[str, str]: """The mailbox's own calendars: ID → name. Calendars shared by other people, which appear in the list, are theirs to back up and are left out. Args: ctx: Module context. user: The mailbox's user ID. mail: The mailbox's address, to recognise its own calendars. Returns: Calendar names by ID. """ out: dict[str, str] = {} async for c in ctx.graph.paginate( f"/users/{user}/calendars", params={"$select": "id,name,owner", "$top": LIST_PAGE}, headers=IMMUTABLE, ): owner = str(((c.get("owner") or {}).get("address")) or "").casefold() if mail and owner and owner != mail.casefold(): continue out[str(c["id"])] = join("", str(c.get("name") or "Calendar")) return out
[docs] async def contact_folders(ctx: ModuleContext, user: str) -> tuple[dict[str, str], str | None]: """The mailbox's contact folders: ID → path, and the default folder's ID. The default folder ("Contacts") holds the other folders; its own contacts are read from ``/users/{id}/contacts``. Args: ctx: Module context. user: The mailbox's user ID. Returns: Paths by folder ID, and the default folder's ID if known. """ root_name, root_id = DEFAULT_CONTACTS, None try: root = await ctx.graph.get_json( f"/users/{user}/contactFolders/contacts", params={"$select": "id,displayName"}, headers=IMMUTABLE, ) root_name = join("", str(root.get("displayName") or DEFAULT_CONTACTS)) root_id = str(root["id"]) except GraphError as exc: if exc.status not in (400, 404): raise out: dict[str, str] = {} if root_id: out[root_id] = root_name queue: list[tuple[str, str]] = [(f"/users/{user}/contactFolders", root_name)] while queue: url, prefix = queue.pop(0) async for f in ctx.graph.paginate( url, params={"$select": "id,displayName", "$top": LIST_PAGE}, headers=IMMUTABLE ): fid = str(f["id"]) if fid == root_id: continue path = join(prefix, str(f.get("displayName") or "")) out[fid] = path queue.append((f"/users/{user}/contactFolders/{fid}/childFolders", path)) return out, root_id
[docs] def folder_changes(folders: dict[str, str], saved: dict[str, Any]) -> list[GroupChange]: """Folders removed or renamed since the last run; ``saved`` is updated. Args: folders: The folders now, ID → path. saved: The folders at the last run, ID → path; updated in place. Returns: A removal or rename for each. """ out = [] for fid in sorted(set(saved) - set(folders)): out.append(GroupChange("folder_id", fid, deleted=True)) del saved[fid] for fid, path in folders.items(): if fid in saved and saved[fid] != path: out.append(GroupChange("folder_id", fid, path=path)) saved[fid] = path return out
[docs] async def backup_folders( ctx: ModuleContext, user: str, kind: Kind, folders: dict[str, str], saved: dict[str, Any], default: str | None = None, ) -> AsyncIterator[ItemVersion | GroupChange | None]: """Back up calendars or contact folders. ``None`` means "checkpoint now". Args: ctx: Module context (with ``current_items``). user: The mailbox's user ID. kind: Calendars or contacts. folders: The folders now, ID → path. saved: The folders at the last run, ID → path; updated in place. default: The default contact folder's ID (its contacts are read from ``/users/{id}/contacts``). Yields: New and changed items, deletions, folder renames and removals. """ for change in folder_changes(folders, saved): yield change yield None for fid, path in sorted(folders.items(), key=lambda f: f[1].casefold()): ctx.check_cancelled() ctx.progress(message=f"{kind.label}: {path}", unit="items") async for record in _folder(ctx, user, kind, fid, path, fid == default, set(folders)): yield record yield None if default is None and kind is CONTACTS: # The default folder's ID was not readable: back up its contacts # under the folder ID they report. async for record in _default_contacts(ctx, user, set(folders)): yield record yield None
async def _folder( ctx: ModuleContext, user: str, kind: Kind, fid: str, path: str, default: bool, backed_up: set[str], ) -> AsyncIterator[ItemVersion]: """One folder: what is new or changed, and what was deleted.""" known = await ctx.current_items("folder_id", fid) if ctx.current_items else {} url = kind.items_url(user, fid, default) if not known: # First backup of this folder: full items in pages. async for item in ctx.graph.paginate(url, params={"$top": "50"}, headers=IMMUTABLE): yield version(kind, item, fid, path) return listed: set[str] = set() changed: list[str] = [] async for item in ctx.graph.paginate( url, params={"$select": "id,changeKey", "$top": LIST_PAGE}, headers=IMMUTABLE ): key = str(item["id"]) listed.add(key) stored = known.get(key) if stored is None or stored.get("change_key") != item.get("changeKey"): changed.append(key) for start in range(0, len(changed), FETCH_PARALLEL * 4): batch = changed[start : start + FETCH_PARALLEL * 4] for full in await _fetch(ctx, user, kind, batch): if full is not None: yield version(kind, full, fid, path) missing = sorted(set(known) - listed) for key in await _really_gone(ctx, user, kind, missing, backed_up): yield ItemVersion(item_key=key, item_type=kind.item_type, name="", deleted=True) async def _default_contacts( ctx: ModuleContext, user: str, backed_up: set[str] ) -> AsyncIterator[ItemVersion]: """Contacts of the default folder when its ID could not be read up front. Every contact is listed in full (no change keys to compare without the folder); the catalog stores only what changed. Contacts last seen in a folder listed now but missing from it are deletions. If the folder has become empty, its ID is not learnt and those deletions wait for a run that can read it. """ listed: set[str] = set() seen: set[str] = set() async for item in ctx.graph.paginate( f"/users/{user}/contacts", params={"$top": "50"}, headers=IMMUTABLE ): fid = str(item.get("parentFolderId") or "") listed.add(str(item["id"])) seen.add(fid) yield version(CONTACTS, item, fid, DEFAULT_CONTACTS) if ctx.current_items is None: return known: set[str] = set() for fid in sorted(seen - {""}): known |= set(await ctx.current_items("folder_id", fid)) gone = await _really_gone(ctx, user, CONTACTS, sorted(known - listed), backed_up | seen) for key in gone: yield ItemVersion(item_key=key, item_type=CONTACTS.item_type, name="", deleted=True) async def _fetch( ctx: ModuleContext, user: str, kind: Kind, keys: list[str] ) -> list[dict[str, Any] | None]: """Full items, a few at a time; ``None`` for one deleted meanwhile.""" limit = asyncio.Semaphore(FETCH_PARALLEL) async def one(key: str) -> dict[str, Any] | None: async with limit: try: return await ctx.graph.get_json(kind.item_url(user, key), headers=IMMUTABLE) except GraphError as exc: if exc.status in (400, 404): return None raise return await all_or_cancel(one(k) for k in keys) async def _really_gone( ctx: ModuleContext, user: str, kind: Kind, keys: list[str], backed_up: set[str] ) -> list[str]: """Items missing from their folder that are in no folder backed up. A moved item turns up in its new folder's listing (same ID). A deleted one is gone, or in Deleted Items, which is not a calendar or contact folder. """ limit = asyncio.Semaphore(FETCH_PARALLEL) async def somewhere(key: str) -> bool: for fid in sorted(backed_up): async with limit: try: await ctx.graph.get_json( kind.in_folder_url(user, fid, key), params={"$select": "id"}, headers=IMMUTABLE, ) return True except GraphError as exc: if exc.status not in (400, 404): raise return False found = await all_or_cancel(somewhere(k) for k in keys) return [k for k, there in zip(keys, found, strict=True) if not there]