Source code for s365b.modules.exchange.tasks

"""Tasks (Microsoft To Do) of a mailbox.

Read with the To Do API (``/users/{id}/todo/lists``), which allows reading
with an application permission (``Tasks.Read.All``) but not writing. Each
run lists every task of the mailbox's own lists, with their checklist
steps, as Graph's JSON; the catalog stores only what changed. A task found
in none of the lists is a deletion. Moving a task to another list changes
its ID (Microsoft's default for To Do), so its history starts again there:
the old task shows as deleted from its list, and both can be restored.

Left out: lists other people share with the mailbox (theirs to back up)
and "Flagged email", which only mirrors flagged messages (backed up with
the mail). Restore imports the task's restore copy (as for mail) into a
task folder; see :mod:`s365b.modules.exchange.restore`.
"""

from __future__ import annotations

from collections.abc import AsyncIterator
from typing import Any

from s365b.graph.client import GraphError
from s365b.modules.exchange.items import folder_changes, modified, normalise, when
from s365b.modules.paths import join
from s365b.modules.sdk import GroupChange, ItemVersion, ModuleContext

[docs] ITEM_TYPE = "task"
[docs] STATE_KEY = "task_lists"
[docs] PAGE = "100"
[docs] async def task_lists(ctx: ModuleContext, user: str) -> dict[str, str]: """The mailbox's own To Do lists: ID → name. Args: ctx: Module context. user: The mailbox's user ID. Returns: List names by ID. """ out: dict[str, str] = {} async for t in ctx.graph.paginate(f"/users/{user}/todo/lists", params={"$top": PAGE}): if t.get("wellknownListName") == "flaggedEmails" or t.get("isOwner") is False: continue out[str(t["id"])] = join("", str(t.get("displayName") or "Tasks")) return out
[docs] def task_metadata(task: dict[str, Any], list_id: str) -> dict[str, Any]: """Fields shown and searched in the browse view. Args: task: Task from Graph. list_id: Its list. Returns: Metadata for the item version. """ meta: dict[str, Any] = { "folder_id": list_id, "completed": task.get("status") == "completed", "due": when(task.get("dueDateTime"), date_only=True), # To Do has due days } if task.get("importance") == "high": meta["important"] = True return meta
[docs] def task_version(task: dict[str, Any], list_id: str, path: str) -> ItemVersion: """The item version for a task. Args: task: The task from Graph. list_id: Its list. path: The list's name. Returns: The version to store. """ return ItemVersion( item_key=str(task["id"]), item_type=ITEM_TYPE, name=str(task.get("title") or "(no title)"), path=path, modified_at=modified(task), metadata=task_metadata(task, list_id), content=normalise(task), )
async def _tasks(ctx: ModuleContext, user: str, list_id: str) -> AsyncIterator[dict[str, Any]]: """A list's tasks with their checklist steps. The steps come with the tasks (``$expand``); if Graph refuses that, they are read task by task. """ url = f"/users/{user}/todo/lists/{list_id}/tasks" params = {"$top": PAGE, "$expand": "checklistItems"} try: async for task in ctx.graph.paginate(url, params=params): yield task return except GraphError as exc: if exc.status != 400: raise async for task in ctx.graph.paginate(url, params={"$top": PAGE}): steps = f"{url}/{task['id']}/checklistItems" task["checklistItems"] = [s async for s in ctx.graph.paginate(steps)] yield task
[docs] async def backup_tasks( ctx: ModuleContext, user: str, lists: dict[str, str], saved: dict[str, Any] ) -> AsyncIterator[ItemVersion | GroupChange | None]: """Back up To Do lists. ``None`` means "checkpoint now". Args: ctx: Module context (with ``current_items``). user: The mailbox's user ID. lists: The lists now, ID → name. saved: The lists at the last run, ID → name; updated in place. Yields: Every task (unchanged ones are recognised by the catalog), deletions, list renames and removals. """ for change in folder_changes(lists, saved): yield change yield None listed: set[str] = set() known: set[str] = set() for list_id, name in sorted(lists.items(), key=lambda t: t[1].casefold()): ctx.check_cancelled() ctx.progress(message=f"Tasks: {name}", unit="items") if ctx.current_items is not None: known |= set(await ctx.current_items("folder_id", list_id)) async for task in _tasks(ctx, user, list_id): listed.add(str(task["id"])) yield task_version(task, list_id, name) yield None # In no list: deleted. To Do gives a task moved to another list a new # ID, so a move is recorded as this deletion plus a new task there. for key in sorted(known - listed): yield ItemVersion(item_key=key, item_type=ITEM_TYPE, name="", deleted=True) yield None