Source code for s365b.modules.exchange.restore

"""Restoring mail, calendar events, contacts and tasks with Exchange's import API.

Each item's restore copy (Exchange's own export, see the module) is
imported into a folder of the target mailbox, so it comes back as it was:
read state, dates, flags and attachments, and not as a draft. Imported
meetings send no invitations.

Folders are found by name along the item's backed-up path and created when
missing, either where they were ("original folders") or under a new folder
named by the person restoring. Mail goes into mail folders, events into
calendars, contacts into contact folders and tasks into task folders (To Do
lists). Calendars and task lists other than the default ones are looked for
at the top of the mailbox and under the default calendar or task folder,
and created under it (as Outlook does). A "new folder" restore puts events
in a new calendar under the default calendar, tasks in a new list under the
default task folder, and contacts in a new folder under the default contacts
folder, so they do not clash with the new mail folder of the same name.
The import API identifies folders by its own IDs
(``/admin/exchange/mailboxes/{id}/folders``), not by the Outlook API's.
"""

from __future__ import annotations

import asyncio
import base64
from collections.abc import Awaitable, Callable
from datetime import UTC, datetime, timedelta
from typing import Any

import httpx

from s365b.core.concurrency import all_or_cancel
from s365b.graph.client import GraphClient, GraphError
from s365b.modules.exchange.items import CALENDARS, CONTACTS
from s365b.modules.paths import names as folder_names
from s365b.modules.sdk import (
    ItemVersion,
    ModuleContext,
    ModuleError,
    RestoreRequest,
    RestoreResult,
    StoredItem,
)

[docs] FTS = "fts"
[docs] IMMUTABLE = {"Prefer": 'IdType="ImmutableId"'}
[docs] FOLDER_TYPE = "IPF.Note"
# The kind of folder each item type is restored into.
[docs] FOLDER_TYPES = { "message": FOLDER_TYPE, "event": "IPF.Appointment", "contact": "IPF.Contact", "task": "IPF.Task", }
# Exchange allows four concurrent requests per mailbox and app.
[docs] IMPORT_PARALLEL = 4
# Items handed to the import loop at a time (keeps memory flat and makes a # stop request take effect quickly).
[docs] CHUNK = 100
# Renew the import session this long before Exchange says it expires.
[docs] SESSION_MARGIN = timedelta(minutes=2)
[docs] SESSION_FALLBACK = timedelta(minutes=10)
[docs] FALLBACK_FOLDER = "Inbox"
[docs] PERMISSION_HINT = ( "The Restore app may not write to this mailbox. In Microsoft 365 tenant, choose" " Update permissions." )
[docs] def split_path(path: str) -> tuple[str, ...]: """Folder names along a backed-up path ("Inbox/Projects" → two names).""" return folder_names(path) or (FALLBACK_FOLDER,)
[docs] class Folders: """A mailbox's folders, read as needed, created when missing. Args: ctx: Module context (Restore app). mailbox: Mailbox ID for the import API. folder_type: The kind of folder: ``IPF.Note`` (mail), ``IPF.Appointment`` (calendar), ``IPF.Contact`` or ``IPF.Task``. Folders of other kinds are ignored, and new folders are of this kind. default_name: Returns the name of the mailbox's default folder of this kind (e.g. "Calendar", or its translation), or ``None`` if it cannot be read. """ def __init__( self, ctx: ModuleContext, mailbox: str, folder_type: str = FOLDER_TYPE, default_name: Callable[[], Awaitable[str | None]] | None = None, ) -> None:
[docs] self.ctx = ctx
[docs] self.base = f"/admin/exchange/mailboxes/{mailbox}/folders"
[docs] self.folder_type = folder_type
[docs] self.default_name = default_name
self._children: dict[str, dict[str, str]] = {} # parent ID ("" = top) → name → ID self._default: str | None = None self._top: list[tuple[str, str]] = [] # top folders of exactly this kind: (name, ID) self._labels: dict[str, str] = {} # folder ID → name, for the folders listed self._ids: dict[tuple[str, ...], str] = {} self._lock = asyncio.Lock()
[docs] self.created: list[str] = []
def _url(self, parent: str) -> str: return f"{self.base}/{parent}/childFolders" if parent else self.base async def _list(self, parent: str) -> dict[str, str]: if parent not in self._children: names: dict[str, str] = {} async for f in self.ctx.graph.paginate(self._url(parent)): kind = str(f.get("type") or FOLDER_TYPE) if not kind.startswith(self.folder_type): continue # another kind of folder with the same name if not parent and kind == self.folder_type: self._top.append((str(f.get("displayName") or ""), str(f["id"]))) label = str(f.get("displayName") or "") self._labels[str(f["id"])] = label names.setdefault(label.casefold(), str(f["id"])) self._children[parent] = names return self._children[parent] async def _create(self, parent: str, name: str) -> str: """Create a folder; if the answer is lost, find it rather than make two.""" try: resp = await self.ctx.graph.request( "POST", self._url(parent), json={"displayName": name, "type": self.folder_type}, idempotent=False, ) return str(resp.json()["id"]) except (GraphError, httpx.TransportError): self._children.pop(parent, None) found = (await self._list(parent)).get(name.casefold()) if found is None: raise return found
[docs] async def default(self) -> str: """The default folder of this kind, e.g. Calendar. The folder at the top with the default folder's name; without that name, the first one at the top. Returns: Its import API ID. Raises: ModuleError: If the mailbox has none. """ if self._default is None: await self._list("") if not self._top: raise ModuleError(f"The mailbox has no {self.folder_type} folder to restore into.") name = await self.default_name() if self.default_name else None wanted = (name or "").casefold() named = [fid for label, fid in self._top if wanted and label.casefold() == wanted] self._default = named[0] if named else self._top[0][1] return self._default
[docs] async def named(self, name: str) -> str: """A calendar or task list by name: at the top, else under the default one. One that is missing is created under the default folder. Args: name: The calendar's or list's name. Returns: Its import API ID. """ if not name: return await self.default() found = (await self._list("")).get(name.casefold()) if found is not None: return found return await self.ensure((name,), under=await self.default())
[docs] async def ensure(self, parts: tuple[str, ...], under: str = "") -> str: """Return the ID of the folder at ``parts``, creating what is missing. Args: parts: Folder names from the top of the mailbox, or from ``under``. under: The folder to start from (default: the top). Returns: The import API's ID of the last folder. """ async with self._lock: # never create the same folder twice parent = under for i, name in enumerate(parts): key = (under, *parts[: i + 1]) known = self._ids.get(key) if known is None: children = await self._list(parent) known = children.get(name.casefold()) if known is None: known = await self._create(parent, name) children[name.casefold()] = known start = [self._labels.get(under, "")] if under else [] self.created.append("/".join([*start, *parts[: i + 1]])) self._ids[key] = known parent = known return parent
[docs] class ImportSession: """An import session's pre-authenticated URL, renewed before it expires. Args: ctx: Module context (Restore app). mailbox: Mailbox ID. """ def __init__(self, ctx: ModuleContext, mailbox: str) -> None:
[docs] self.ctx = ctx
[docs] self.mailbox = mailbox
self._url: str | None = None self._expires = datetime.min.replace(tzinfo=UTC) self._lock = asyncio.Lock()
[docs] async def url(self, *, renew: bool = False) -> str: """The current import URL (a new session when needed).""" async with self._lock: now = datetime.now(UTC) if renew or self._url is None or now >= self._expires - SESSION_MARGIN: resp = await self.ctx.graph.request( "POST", f"/admin/exchange/mailboxes/{self.mailbox}/createImportSession" ) body = resp.json() self._url = str(body["importUrl"]) self._expires = _when(body.get("expirationDateTime")) or now + SESSION_FALLBACK return self._url
[docs] async def put(self, folder_id: str, data: bytes) -> str: """Import one item into a folder. Args: folder_id: Import API folder ID. data: The item's export stream. Returns: The new item's ID. """ body = {"FolderId": folder_id, "Mode": "create", "Data": base64.b64encode(data).decode()} url = await self.url() try: # The URL carries its own token; Exchange rejects an Authorization header. resp = await self.ctx.graph.request( "POST", url, json=body, authenticate=False, idempotent=False ) except GraphError as exc: if exc.status not in (401, 403): raise # The session ran out early: once more with a new one. url = await self.url(renew=True) resp = await self.ctx.graph.request( "POST", url, json=body, authenticate=False, idempotent=False ) return str(resp.json().get("itemId") or "")
[docs] async def still_in_place(reader: GraphClient, user: str, item: StoredItem) -> bool: """Whether an item is still in the mailbox as it was backed up. A message counts as still there in the folder it was backed up in. An event, contact or task must also be unchanged: restoring last week's version of an event edited since adds that version back. An item that was moved (e.g. to Deleted Items) or deleted is restored. Args: reader: Graph client with read access (the Backup app). user: The mailbox's user ID. item: The backed-up message, event, contact or task. Returns: True if it is still there, unchanged. """ v = item.version folder = v.metadata.get("folder_id") key, item_type = v.item_key, v.item_type lookups = { "event": lambda f: CALENDARS.in_folder_url(user, f, key), "contact": lambda f: CONTACTS.in_folder_url(user, f, key), "task": lambda f: f"/users/{user}/todo/lists/{f}/tasks/{key}", } if item_type in lookups: if not folder: return False # To Do tasks have no change key (and $select of one fails). fields = "id,lastModifiedDateTime" if item_type == "task" else "id,changeKey" try: now = await reader.get_json( lookups[item_type](str(folder)), params={"$select": fields}, headers=IMMUTABLE, ) except GraphError as exc: if exc.status in (400, 404): return False raise if v.metadata.get("change_key"): # events and contacts return bool(now.get("changeKey") == v.metadata["change_key"]) changed = _when(now.get("lastModifiedDateTime")) # tasks have no change key return changed is not None and changed == v.modified_at try: msg = await reader.get_json( f"/users/{user}/messages/{item.version.item_key}", params={"$select": "parentFolderId"}, headers=IMMUTABLE, ) except GraphError as exc: if exc.status in (400, 404): # gone (or an ID Exchange no longer knows) return False raise return folder is None or str(msg.get("parentFolderId")) == str(folder)
[docs] def default_names( reader: GraphClient | None, user: str ) -> dict[str, Callable[[], Awaitable[str | None]]]: """How to learn the names of a mailbox's default calendar, contacts and tasks folders. Read with the Backup app (the import API does not mark them); ``None`` if it cannot. Args: reader: Graph client with read access, if any. user: The mailbox's user ID. Returns: A name reader by item type. """ async def calendar() -> str | None: """The default calendar's name.""" found = await _read(reader, f"/users/{user}/calendar", "name") return str(found["name"]) if found else None async def contacts() -> str | None: """The default contacts folder's name.""" found = await _read(reader, f"/users/{user}/contactFolders/contacts", "displayName") return str(found["displayName"]) if found else None async def tasks() -> str | None: """The default To Do list's name (the Tasks folder).""" if reader is None: return None try: async for t in reader.paginate(f"/users/{user}/todo/lists"): if t.get("wellknownListName") == "defaultList": return str(t.get("displayName") or "") or None except GraphError: return None return None return {"event": calendar, "contact": contacts, "task": tasks}
async def _read(reader: GraphClient | None, url: str, field: str) -> dict[str, Any] | None: if reader is None: return None try: found = await reader.get_json(url, params={"$select": field}, headers=IMMUTABLE) except GraphError: return None return found if found.get(field) else None
[docs] async def restore_mail( ctx: ModuleContext, request: RestoreRequest, mailbox_id: Any ) -> RestoreResult: """Import messages', events' and contacts' restore copies into a mailbox. Options: ``destination`` is ``"original"`` (the folders they were in) or ``"folder"`` (under a new folder named ``folder_name``, keeping the folder structure; see the module for events and contacts). Restoring to the original folders of the same mailbox skips items that are still where they were. Args: ctx: Module context with the Restore app's client (and ``reader``). request: Messages and where to put them. mailbox_id: Coroutine function returning a user's mailbox ID. Returns: The outcome. Raises: ModuleError: If the options are wrong or the Restore app lacks permissions. """ result = RestoreResult() if not request.items: return result source = request.items[0].object target = request.target or source destination = request.options.get("destination") root: tuple[str, ...] = () if destination == "folder": name = str(request.options.get("folder_name") or "").strip().strip("/") if not name: raise ModuleError("Name the folder to restore into.") root = (name,) elif destination != "original": raise ModuleError("Choose whether to restore into the original folders or a new folder.") skip_present = ( destination == "original" and target.external_id == source.external_id and ctx.reader is not None ) try: mailbox = await mailbox_id(ctx, target.external_id) names = default_names(ctx.reader, target.external_id) folders = {t: Folders(ctx, mailbox, f, names.get(t)) for t, f in FOLDER_TYPES.items()} session = ImportSession(ctx, mailbox) await session.url() # fail early if the app may not import except GraphError as exc: if exc.status == 403: raise ModuleError(PERMISSION_HINT) from exc raise items = sorted( request.items, key=lambda i: (i.version.item_type, i.version.path.casefold(), i.version.name), ) async def folder_for(v: ItemVersion) -> str: """The import API ID of the folder an item goes into.""" kind = v.item_type if v.item_type in FOLDER_TYPES else "message" where = folders[kind] parts = folder_names(v.path) if kind == "message": return await where.ensure(root + split_path(v.path)) if kind in ("event", "task"): if root: # one new calendar or list under the default one return await where.ensure(root, under=await where.default()) return await where.named(parts[0] if parts else "") if not parts: # a contact: the default folder, or the path within it return await where.ensure(root, under=await where.default()) return await where.ensure((parts[0], *root, *parts[1:])) total, done = len(items), 0 limit = asyncio.Semaphore(IMPORT_PARALLEL) async def one(item: StoredItem) -> None: """Restore one message; a failure is recorded, except a lost permission. A :class:`ModuleError` (the app may no longer import) ends the whole restore: the other messages of the chunk are cancelled. """ nonlocal done v = item.version async with limit: if ctx.cancel.is_set(): return try: if FTS not in item.extras or item.read_extra is None: result.fail(f"{v.name} ({v.path}): no restore copy was kept for this version") return reader = ctx.reader if skip_present else None if reader is not None and await still_in_place(reader, source.external_id, item): result.skipped += 1 return folder = await folder_for(v) data = b"".join([chunk async for chunk in item.read_extra(FTS)]) await session.put(folder, data) result.restored += 1 except GraphError as exc: if exc.status == 403: raise ModuleError(PERMISSION_HINT) from exc result.fail(f"{v.name} ({v.path}): {exc.message or exc.code or exc.status}") except ModuleError: raise except Exception as exc: ctx.log.warning("exchange.restore_item_failed", item=v.item_key, exc_info=exc) result.fail(f"{v.name} ({v.path}): {type(exc).__name__}") finally: done += 1 ctx.progress(done=done, total=total, message=v.path, unit="items") try: for start in range(0, total, CHUNK): if ctx.cancel.is_set(): break await all_or_cancel(one(i) for i in items[start : start + CHUNK]) finally: result.folders_created = [p for f in folders.values() for p in f.created] return result
def _when(value: str | None) -> datetime | None: if not value: return None try: parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)