Source code for s365b.modules.exchange.module

"""The Exchange Online backup module: mail, calendars and contacts.

Each mailbox is a protected object. Messages are stored as their original
MIME (``.eml``), which keeps headers, body and attachments exactly as
Exchange has them and opens in any mail program.

Incremental backups use one delta query per folder. Graph is asked for
immutable IDs (``Prefer: IdType="ImmutableId"``), so a message keeps its ID
when it moves between folders: a move becomes a new version with the new
folder instead of a deletion plus a new item.

Each message also gets a restore copy: Exchange's own export of it
(mailbox import/export API), which restores with full fidelity (read state,
dates, flags, not a draft). It is fetched after each mailbox's backup for
every message that lacks one, so older backups get it too. Restore imports
it (:mod:`s365b.modules.exchange.restore`).

Calendars, contacts and tasks (Microsoft To Do) are stored as Graph's JSON,
with restore copies like messages (:mod:`s365b.modules.exchange.items`,
:mod:`s365b.modules.exchange.tasks`).

Not covered by Graph (v1.0), and so not backed up: in-place archive
mailboxes, the Recoverable Items folder, public folders.
"""

from __future__ import annotations

import asyncio
import base64
import json
from collections import deque
from collections.abc import AsyncIterator
from dataclasses import dataclass
from datetime import datetime
from typing import Any, ClassVar

from pydantic import BaseModel, Field

from s365b.core.concurrency import all_or_cancel
from s365b.graph.client import BatchRequest, DeltaExpiredError, GraphError
from s365b.modules.exchange.ics import to_ics
from s365b.modules.exchange.items import (
    CALENDARS,
    CONTACTS,
    backup_folders,
    calendars,
    contact_folders,
)
from s365b.modules.exchange.tasks import STATE_KEY as TASK_STATE
from s365b.modules.exchange.tasks import backup_tasks, task_lists
from s365b.modules.exchange.vcf import to_vcf
from s365b.modules.paths import file_path, join
from s365b.modules.sdk import (
    BackupModule,
    Checkpoint,
    Column,
    ExportFile,
    ExportRequest,
    ExtraWanted,
    GroupChange,
    ItemTypeInfo,
    ItemVersion,
    ModuleContext,
    ModuleError,
    NotSupportedError,
    ProtectedObject,
    RestoreRequest,
    RestoreResult,
    SyncState,
)

[docs] READ_PERMISSIONS = frozenset( {"User.Read.All", "Mail.Read", "MailboxSettings.Read", "MailboxItem.Export.All"} )
[docs] CALENDAR_PERMISSION = "Calendars.Read"
[docs] CONTACTS_PERMISSION = "Contacts.Read"
[docs] TASKS_PERMISSION = "Tasks.Read.All"
# Restore imports Exchange's own export of each message into a folder.
[docs] RESTORE_PERMISSIONS = frozenset( {"User.Read.All", "MailboxFolder.ReadWrite.All", "MailboxItem.ImportExport.All"} )
# The restore copy: Exchange's full-fidelity export of a message (an opaque # "fast transfer stream"), which only Exchange can import again.
[docs] FTS = "fts"
[docs] EXPORT_MAX_ITEMS = 20 # Graph's limit per exportItems request
[docs] EXPORT_MAX_BYTES = 24 * 1024 * 1024 # keep each response a manageable size
[docs] IMMUTABLE = {"Prefer": 'IdType="ImmutableId"'}
[docs] PAGE = {"Prefer": 'IdType="ImmutableId", odata.maxpagesize=50'}
[docs] MESSAGE_FIELDS = ",".join( ( "subject", "from", "toRecipients", "receivedDateTime", "sentDateTime", "lastModifiedDateTime", "hasAttachments", "internetMessageId", "parentFolderId", "isDraft", # Read state and flag are part of what a restore brings back: a # change to them is a new version, with a new restore copy. "isRead", "flag", ) )
[docs] FOLDER_FIELDS = "id,displayName,parentFolderId,childFolderCount,totalItemCount"
# Exchange allows 4 concurrent requests per mailbox per app; mailboxes are # throttled separately, so several are backed up at once.
[docs] DOWNLOAD_AHEAD = 4
[docs] PARALLEL_MAILBOXES = 4
[docs] NO_MAILBOX = ( "MailboxNotEnabledForRESTAPI", "MailboxNotFound", "ErrorInvalidUser", "ResourceNotFound", )
[docs] Folder = dict[str, Any]
@dataclass(frozen=True, slots=True)
[docs] class FolderInfo: """A mail folder to back up."""
[docs] path: str
[docs] count: int
[docs] class ExchangeConfig(BaseModel): """Exchange module settings."""
[docs] include_shared_mailboxes: bool = Field( True, title="Shared mailboxes", description="Back up shared mailboxes as well as users'." )
[docs] include_resource_mailboxes: bool = Field( False, title="Room and equipment mailboxes", description="Mostly meeting requests; usually not worth keeping.", )
[docs] include_junk_email: bool = Field( False, title="Junk Email folder", description="Back up the Junk Email folder." )
[docs] include_deleted_items: bool = Field( True, title="Deleted Items folder", description="Back up what users have deleted but not yet emptied.", )
[docs] include_calendar: bool = Field( True, title="Calendars", description="Back up each mailbox's own calendars (meetings and appointments).", )
[docs] include_contacts: bool = Field( True, title="Contacts", description="Back up each mailbox's contacts and contact folders." )
[docs] include_tasks: bool = Field( True, title="Tasks", description="Back up each mailbox's Microsoft To Do lists and tasks." )
def _address(recipient: dict[str, Any] | None) -> str: ea = (recipient or {}).get("emailAddress") or {} name, addr = ea.get("name") or "", ea.get("address") or "" return f"{name} <{addr}>" if name and addr and name != addr else addr or name
[docs] def message_metadata(msg: dict[str, Any], folder_id: str) -> dict[str, Any]: """Pick the fields shown and searched in the browse view. Args: msg: Message from Graph. folder_id: The folder it is in. Returns: Metadata for the item version. """ to = [_address(r) for r in msg.get("toRecipients") or []] meta: dict[str, Any] = { "folder_id": folder_id, "from": _address(msg.get("from")), "to": ", ".join(to[:5]) + (f" (+{len(to) - 5})" if len(to) > 5 else ""), "received": msg.get("receivedDateTime") or msg.get("sentDateTime"), "attachments": bool(msg.get("hasAttachments")), } if msg.get("internetMessageId"): meta["message_id"] = msg["internetMessageId"] if msg.get("isDraft"): meta["draft"] = True if "isRead" in msg: meta["read"] = bool(msg["isRead"]) flag = (msg.get("flag") or {}).get("flagStatus") if flag and flag != "notFlagged": meta["flag"] = flag # "flagged" or "complete" return meta
def _when(value: str | None) -> datetime | None: if not value: return None try: return datetime.fromisoformat(value.replace("Z", "+00:00")) except ValueError: return None
[docs] class ExchangeModule(BackupModule): """Backs up mail in Exchange Online mailboxes."""
[docs] id: ClassVar[str] = "exchange"
[docs] display_name: ClassVar[str] = "Exchange Online"
[docs] description: ClassVar[str] = ( "Email, calendars and contacts in user and shared mailboxes; email as original .eml files." )
[docs] version: ClassVar[str] = "0.1.0"
[docs] config_model: ClassVar[type[BaseModel]] = ExchangeConfig
[docs] object_noun: ClassVar[tuple[str, str]] = ("mailbox", "mailboxes")
[docs] parallel_objects: ClassVar[int] = PARALLEL_MAILBOXES
[docs] async def estimate(self, ctx: ModuleContext, obj: ProtectedObject, state: SyncState) -> int: """Count the messages in folders that have no finished first backup. Folders already backed up only send changes, which are few and not counted. Args: ctx: Module context. obj: The mailbox. state: Its saved state. Returns: Expected number of messages to process. """ cfg = ctx.config assert isinstance(cfg, ExchangeConfig) # noqa: S101 - set by the registry folders = await self._folders(ctx, obj.external_id, cfg) return _expected(folders, state.data.get("folders", {}))
[docs] def state_for_new_repository(self, state: SyncState) -> SyncState: """Re-list every mail folder; keep the folder lists. Each mail folder restarts its delta query as a re-listing, which afterwards finds the messages deleted meanwhile. Calendars, contacts and tasks are always listed in full; their saved folder names still find renames and removed folders. Args: state: The state saved by the backup into the other repository. Returns: The state to start from. """ data = dict(state.data) data["folders"] = { fid: {"path": f.get("path", ""), "resync": True} for fid, f in (state.data.get("folders") or {}).items() } return SyncState(data)
[docs] def required_permissions(self, config: BaseModel, *, restore: bool) -> set[str]: """Return the Graph application permissions needed. Args: config: Module settings. restore: True for the Restore app. Returns: Read and export permissions for backup (calendars and contacts when included); folder and import permissions for restore. """ if restore: return set(RESTORE_PERMISSIONS) assert isinstance(config, ExchangeConfig) # noqa: S101 - set by the registry perms = set(READ_PERMISSIONS) if config.include_calendar: perms.add(CALENDAR_PERMISSION) if config.include_contacts: perms.add(CONTACTS_PERMISSION) if config.include_tasks: perms.add(TASKS_PERMISSION) return perms
[docs] def optional_permissions(self, config: BaseModel) -> set[str]: """Back up without the export permission (no restore copies). Args: config: Module settings. Returns: The export permission. """ return {"MailboxItem.Export.All"}
[docs] def extra_copies(self, config: BaseModel) -> tuple[str, ...]: """Keep Exchange's export of every message, for restore. Args: config: Module settings. Returns: The restore copy. """ return (FTS,)
[docs] def extra_label(self, name: str) -> str: """Progress text while fetching restore copies. Args: name: Copy name. Returns: Text for the progress line. """ return "Restore copies"
[docs] async def fetch_extras( self, ctx: ModuleContext, obj: ProtectedObject, name: str, items: list[ExtraWanted] ) -> AsyncIterator[tuple[str, bytes]]: """Export messages with Exchange's mailbox export API. Args: ctx: Module context. obj: The mailbox. name: ``"fts"``. items: Messages (immutable IDs) to export. Yields: ``(message ID, export stream)`` for each message exported. Raises: ModuleError: If the Backup app may not export. """ try: mailbox = await mailbox_id(ctx, obj.external_id) for batch in export_batches(items): ctx.check_cancelled() resp = await ctx.graph.request( "POST", f"/admin/exchange/mailboxes/{mailbox}/exportItems", json={"itemIds": [i.item_key for i in batch]}, headers=IMMUTABLE, ) for key, data in exported(batch, resp.json().get("value") or [], ctx): yield key, data except GraphError as exc: if exc.status == 403: raise ModuleError( "The Backup app may not export mail yet, so this mailbox has no restore" " copies. In Microsoft 365 tenant, choose Update permissions." ) from exc raise
[docs] async def restore(self, ctx: ModuleContext, request: RestoreRequest) -> RestoreResult: """Import messages' restore copies into a mailbox. See :func:`s365b.modules.exchange.restore.restore_mail` for the options. Args: ctx: Module context (Restore app). request: Messages and where to put them. Returns: The outcome. """ from s365b.modules.exchange.restore import restore_mail return await restore_mail(ctx, request, mailbox_id)
[docs] def item_types(self) -> list[ItemTypeInfo]: """Describe the item types. Returns: Email messages, calendar events and contacts. """ return [ ItemTypeInfo( id="message", label="Email", icon="mail", columns=(Column("from", "From"), Column("received", "Received", "datetime")), preview=True, media_type="message/rfc822", extension="eml", exports=("eml",), ), ItemTypeInfo( id="event", label="Calendar event", icon="calendar", columns=( Column("start", "Starts", "datetime"), Column("organizer", "Organizer"), Column("location", "Location"), ), preview=True, exports=("ics",), ), ItemTypeInfo( id="contact", label="Contact", icon="contact", columns=( Column("mail", "Email address"), Column("phone", "Phone"), Column("company", "Company"), ), preview=True, exports=("vcf",), ), ItemTypeInfo( id="task", label="Task", icon="task", columns=( Column("due", "Due", "datetime"), Column("completed", "Completed", "bool"), ), preview=True, exports=("ics",), ), ]
[docs] async def export(self, config: BaseModel, request: ExportRequest) -> AsyncIterator[ExportFile]: """Events and tasks as one iCalendar file, contacts as vCards, messages as .eml. Options: ``name``, the file's name, and for ``ics`` the calendar's name in it (e.g. the calendar or To Do list exported). Args: config: Module settings. request: The items; only events and tasks (``ics``), contacts (``vcf``) or messages (``eml``) are exported. Yields: One ``.ics`` or ``.vcf`` file, or an ``.eml`` file per message in its folder (read when the file is written). Raises: NotSupportedError: For another format. """ types = {"ics": ("event", "task"), "vcf": ("contact",), "eml": ("message",)}.get( request.format ) if types is None: raise NotSupportedError(f"Exchange does not export to {request.format}") if request.format == "eml": taken: set[str] = set() for item in request.items: if item.version.item_type == "message": v = item.version path = file_path(v.path, v.name or "message", "eml", taken) yield ExportFile(path, item.read()) return pairs: list[tuple[str, dict[str, Any]]] = [] for item in request.items: if item.version.item_type not in types: continue data = b"".join([piece async for piece in item.read()]) pairs.append((item.version.item_type, json.loads(data))) name = str(request.options.get("name") or "") or None if request.format == "vcf": yield ExportFile(f"{name or 'contacts'}.vcf", to_vcf([c for _, c in pairs])) return yield ExportFile(f"{name or 'calendar'}.ics", to_ics(pairs, name))
[docs] async def discover(self, ctx: ModuleContext) -> AsyncIterator[ProtectedObject]: """Yield every mailbox the settings include. Users without a mailbox (no licence, guests) are left out. Args: ctx: Module context. Yields: Mailboxes. Raises: ModuleError: If mailbox settings cannot be read at all. """ cfg = ctx.config assert isinstance(cfg, ExchangeConfig) # noqa: S101 - set by the registry users = [ u async for u in ctx.graph.paginate( "/users", params={ "$select": "id,displayName,userPrincipalName,mail,accountEnabled,userType", "$top": "999", }, ) if u.get("mail") and u.get("userType") != "Guest" ] responses = await ctx.graph.batch( [BatchRequest(u["id"], "GET", f"/users/{u['id']}/mailboxSettings") for u in users] ) denied = 0 wanted = {"user", "linked"} if cfg.include_shared_mailboxes: wanted.add("shared") if cfg.include_resource_mailboxes: wanted |= {"room", "equipment"} for user, resp in zip(users, responses, strict=True): if resp.status != 200: code = str((resp.body.get("error") or {}).get("code", "")) if resp.status == 403 and code not in NO_MAILBOX: denied += 1 continue purpose = str(resp.body.get("userPurpose") or "user") if purpose not in wanted: continue yield ProtectedObject( "mailbox", user["id"], str(user.get("displayName") or user["mail"]), {"mail": user["mail"], "upn": user.get("userPrincipalName"), "type": purpose}, ) if users and denied == len(users): raise ModuleError( "Access to mailboxes was denied. Re-run Connect tenant so the Backup app gets the" " Exchange permissions." )
[docs] async def backup( self, ctx: ModuleContext, obj: ProtectedObject, state: SyncState ) -> AsyncIterator[ItemVersion | GroupChange | Checkpoint]: """Back up one mailbox incrementally. State: ``{"folders": {folder_id: {"path", "delta", "next"}}}``. Args: ctx: Module context. obj: The mailbox. state: Saved state. Yields: Messages, folder renames/removals and checkpoints. Raises: ModuleError: If the mailbox cannot be read. """ cfg = ctx.config assert isinstance(cfg, ExchangeConfig) # noqa: S101 - set by the registry user = obj.external_id try: folders = await self._folders(ctx, user, cfg) except GraphError as exc: if exc.status == 403: raise ModuleError( f"Access to {obj.display_name}'s mailbox was denied ({exc}). Re-run Connect" " tenant so the Backup app gets Mail.Read." ) from exc raise saved: dict[str, dict[str, Any]] = { k: dict(v) for k, v in state.data.get("folders", {}).items() } saved_calendars: dict[str, Any] = dict(state.data.get(CALENDARS.state_key) or {}) saved_contacts: dict[str, Any] = dict(state.data.get(CONTACTS.state_key) or {}) saved_tasks: dict[str, Any] = dict(state.data.get(TASK_STATE) or {}) def snapshot() -> SyncState: """The whole mailbox's state: every checkpoint saves all of it.""" data: dict[str, Any] = {"folders": _copy(saved)} if saved_calendars: data[CALENDARS.state_key] = dict(saved_calendars) if saved_contacts: data[CONTACTS.state_key] = dict(saved_contacts) if saved_tasks: data[TASK_STATE] = dict(saved_tasks) return SyncState(data) # Folders renamed, moved or gone since the last run. for fid in sorted(set(saved) - set(folders)): yield GroupChange("folder_id", fid, deleted=True) del saved[fid] for fid, info in folders.items(): if fid in saved and saved[fid].get("path") != info.path: yield GroupChange("folder_id", fid, path=info.path) saved[fid]["path"] = info.path expected = _expected(folders, saved) yield Checkpoint(snapshot()) done = 0 order = sorted(folders.items(), key=lambda f: f[1].path.lower()) for fid, info in order: ctx.check_cancelled() ctx.progress(done=done, total=expected or None, message=info.path, unit="items") fstate = saved.setdefault(fid, {"path": info.path}) async for record in self._folder(ctx, user, fid, info.path, fstate, set(folders)): if record is None: ctx.progress(done=done, total=expected or None, message=info.path, unit="items") yield Checkpoint(snapshot()) else: done += 1 yield record try: if cfg.include_calendar: found = await calendars(ctx, user, obj.metadata.get("mail")) async for item in backup_folders(ctx, user, CALENDARS, found, saved_calendars): yield Checkpoint(snapshot()) if item is None else item if cfg.include_contacts: folders_now, default = await contact_folders(ctx, user) async for item in backup_folders( ctx, user, CONTACTS, folders_now, saved_contacts, default ): yield Checkpoint(snapshot()) if item is None else item if cfg.include_tasks: lists = await self._task_lists(ctx, obj) if lists is not None: async for item in backup_tasks(ctx, user, lists, saved_tasks): yield Checkpoint(snapshot()) if item is None else item except GraphError as exc: if exc.status == 403: raise ModuleError( f"Mail was backed up, but access to {obj.display_name}'s calendars, contacts" " or tasks was denied. In Microsoft 365 tenant, choose Update permissions so" " the Backup app gets Calendars.Read, Contacts.Read and Tasks.Read.All." ) from exc raise
async def _task_lists(self, ctx: ModuleContext, obj: ProtectedObject) -> dict[str, str] | None: """The mailbox's To Do lists, or ``None`` where To Do is not available. To Do belongs to people: a shared, room or equipment mailbox may have no To Do, which is not an error. A user's mailbox refusing access is (a missing permission). """ try: return await task_lists(ctx, obj.external_id) except GraphError as exc: personal = obj.metadata.get("type", "user") in ("user", "linked") if exc.status == 404 or (exc.status == 403 and not personal): ctx.log.info("exchange.no_todo", mailbox=obj.external_id, status=exc.status) return None raise async def _folders( self, ctx: ModuleContext, user: str, cfg: ExchangeConfig ) -> dict[str, FolderInfo]: """Return every mail folder to back up, by ID.""" skip: set[str] = set() for name, include in ( ("junkemail", cfg.include_junk_email), ("deleteditems", cfg.include_deleted_items), ): if not include: try: f = await ctx.graph.get_json( f"/users/{user}/mailFolders/{name}", params={"$select": "id"}, headers=IMMUTABLE, ) skip.add(str(f["id"])) except GraphError as exc: if exc.status != 404: raise params = {"$select": FOLDER_FIELDS, "$top": "250"} result: dict[str, FolderInfo] = {} queue: deque[tuple[str, str]] = deque([(f"/users/{user}/mailFolders", "")]) while queue: url, prefix = queue.popleft() async for f in ctx.graph.paginate(url, params=params, headers=IMMUTABLE): fid = str(f["id"]) if fid in skip or "mailSearchFolder" in str(f.get("@odata.type", "")): continue path = join(prefix, str(f.get("displayName", ""))) result[fid] = FolderInfo(str(path), int(f.get("totalItemCount") or 0)) if f.get("childFolderCount"): queue.append((f"/users/{user}/mailFolders/{fid}/childFolders", str(path))) return result async def _folder( self, ctx: ModuleContext, user: str, fid: str, path: str, fstate: dict[str, Any], backed_up: set[str], ) -> AsyncIterator[ItemVersion | None]: """Run one folder's delta query. ``None`` means "checkpoint now".""" url = f"/users/{user}/mailFolders/{fid}/messages/delta" resume = fstate.get("next") or fstate.get("delta") try: async for page in self._delta(ctx, url, resume, fstate): present = [m for m in page.items if "@removed" not in m] removed = [str(m["id"]) for m in page.items if "@removed" in m] async for version in self._download(ctx, user, fid, path, present): yield version for key in await self._really_gone(ctx, user, removed, backed_up): yield ItemVersion(item_key=key, item_type="message", name="", deleted=True) if page.delta_link: fstate["delta"], fstate["next"] = page.delta_link, None else: fstate["next"] = page.next_link yield None if fstate.get("resync") and fstate.get("delta") and not fstate.get("next"): # A full re-listing does not report what was deleted meanwhile. for key in await self._missing(ctx, user, fid, backed_up): yield ItemVersion(item_key=key, item_type="message", name="", deleted=True) fstate.pop("resync", None) yield None except GraphError as exc: if exc.status == 404: # folder deleted during the run; next run cleans up ctx.log.info("exchange.folder_gone", folder=path) return raise async def _missing( self, ctx: ModuleContext, user: str, fid: str, backed_up: set[str] ) -> list[str]: """After a re-listing: messages the catalog has in a folder that are gone. Compares the folder's message IDs with the catalog's current items in it; each one missing is checked like a delta removal (it may have moved to another folder that is backed up). """ if ctx.current_items is None: return [] known = set(await ctx.current_items("folder_id", fid)) if not known: return [] present: set[str] = set() async for m in ctx.graph.paginate( f"/users/{user}/mailFolders/{fid}/messages", params={"$select": "id", "$top": "1000"}, headers=IMMUTABLE, ): present.add(str(m["id"])) candidates = sorted(known - present) gone = await self._really_gone(ctx, user, candidates, backed_up) ctx.log.info( "exchange.resync_reconciled", folder=fid, checked=len(candidates), gone=len(gone) ) return gone async def _delta( self, ctx: ModuleContext, url: str, resume: str | None, fstate: dict[str, Any] ) -> AsyncIterator[Any]: """Delta pages, restarting from scratch if the saved link expired. A restart is marked in ``fstate["resync"]``: when the new listing is complete, deletions it cannot report are found by comparison. """ try: async for page in ctx.graph.delta( url, delta_link=resume, params={"$select": MESSAGE_FIELDS}, headers=PAGE ): yield page except DeltaExpiredError: if not resume: raise ctx.log.info("exchange.delta_expired", url=url) fstate["resync"], fstate["next"] = True, None async for page in ctx.graph.delta( url, params={"$select": MESSAGE_FIELDS}, headers=PAGE ): yield page async def _download( self, ctx: ModuleContext, user: str, fid: str, path: str, messages: list[dict[str, Any]] ) -> AsyncIterator[ItemVersion]: """Fetch MIME for messages, a few at a time, yielding in order.""" async def mime(msg: dict[str, Any]) -> bytes | None: try: parts = [ p async for p in ctx.graph.stream( f"/users/{user}/messages/{msg['id']}/$value", headers=IMMUTABLE ) ] except GraphError as exc: if exc.status == 404: # deleted since the delta page was read return None raise return b"".join(parts) window: deque[tuple[dict[str, Any], asyncio.Task[bytes | None]]] = deque() def version(msg: dict[str, Any], content: bytes) -> ItemVersion: return ItemVersion( item_key=str(msg["id"]), item_type="message", name=str(msg.get("subject") or "(no subject)"), path=path, modified_at=_when(msg.get("lastModifiedDateTime")), metadata=message_metadata(msg, fid), content=content, ) try: for msg in messages: window.append((msg, asyncio.create_task(mime(msg)))) if len(window) >= DOWNLOAD_AHEAD: m, task = window.popleft() if (content := await task) is not None: yield version(m, content) while window: m, task = window.popleft() if (content := await task) is not None: yield version(m, content) finally: for _, task in window: task.cancel() async def _really_gone( self, ctx: ModuleContext, user: str, removed: list[str], backed_up: set[str] ) -> list[str]: """Filter delta removals down to real deletions. A message moved to another folder is "removed" from the old folder's delta. With immutable IDs it still exists under the same ID; the new folder's delta reports it there. It counts as deleted only if it is gone, or now in a folder that is not backed up. """ async def gone(key: str) -> bool: try: msg = await ctx.graph.get_json( f"/users/{user}/messages/{key}", params={"$select": "parentFolderId"}, headers=IMMUTABLE, ) except GraphError as exc: if exc.status == 404: return True raise return str(msg.get("parentFolderId")) not in backed_up limit = asyncio.Semaphore(DOWNLOAD_AHEAD) async def checked(key: str) -> bool: async with limit: return await gone(key) results = await all_or_cancel(checked(k) for k in removed) return [k for k, g in zip(removed, results, strict=True) if g]
[docs] async def mailbox_id(ctx: ModuleContext, user: str) -> str: """Return a user's mailbox ID for the mailbox import/export API. Args: ctx: Module context. user: User ID. Returns: The primary mailbox ID, e.g. ``MBX:…@…``. """ settings = await ctx.graph.get_json(f"/users/{user}/settings/exchange") return str(settings["primaryMailboxId"])
[docs] def export_batches(items: list[ExtraWanted]) -> list[list[ExtraWanted]]: """Group messages into export requests: at most 20, and not too large. Args: items: Messages with their sizes. Returns: Batches; a message larger than the size limit goes alone. """ batches: list[list[ExtraWanted]] = [] current: list[ExtraWanted] = [] size = 0 for item in items: if current and (len(current) >= EXPORT_MAX_ITEMS or size + item.size > EXPORT_MAX_BYTES): batches.append(current) current, size = [], 0 current.append(item) size += item.size if current: batches.append(current) return batches
[docs] def exported( batch: list[ExtraWanted], results: list[dict[str, Any]], ctx: ModuleContext ) -> list[tuple[str, bytes]]: """Match an export response to the messages asked for. Results carry the item ID; if Exchange returns IDs in another format, they are matched by position (one result per ID asked for, in order). Args: batch: Messages asked for. results: The response's ``value``. ctx: Module context, for logging. Returns: ``(message ID, export stream)`` for each message exported. """ asked = {i.item_key: i for i in batch} by_position = len(results) == len(batch) and any( str(r.get("itemId")) not in asked for r in results ) out: list[tuple[str, bytes]] = [] same, differ = 0, 0 for i, r in enumerate(results): key = batch[i].item_key if by_position else str(r.get("itemId")) if r.get("error") or not r.get("data"): ctx.log.info("exchange.export_item_failed", item=key, error=r.get("error")) continue if key in asked: out.append((key, base64.b64decode(r["data"]))) # Whether the copy is of the stored version (events, contacts). # Logged only, until real exports show that both change keys # are written the same way. ours, theirs = asked[key].change_key, r.get("changeKey") if ours and theirs: if ours == theirs: same += 1 else: differ += 1 ctx.log.info( "exchange.export_change_key_differs", item=key, ours=ours, theirs=theirs ) if same or differ: ctx.log.info("exchange.export_change_keys", same=same, differ=differ) return out
def _copy(folders: dict[str, dict[str, Any]]) -> dict[str, dict[str, Any]]: return {k: dict(v) for k, v in folders.items()} def _expected(folders: dict[str, FolderInfo], saved: dict[str, Any]) -> int: """Messages in folders whose first backup has not finished.""" return sum(f.count for fid, f in folders.items() if not (saved.get(fid) or {}).get("delta"))