"""Restore files into a OneDrive.
Files go back into their folders (created where missing), in the drive
they came from or another user's, or under a new folder at the top of the
drive. A name already taken is not overwritten: OneDrive gives the restored
file a new name ("report 1.pdf"). Restoring into the original folders of
the same drive skips files that are still there unchanged.
Content is uploaded in pieces through an upload session, so a file is
never held in memory whole; its modification time is restored too. A file
counts as restored only when OneDrive confirms it complete at its size. A
stop request is honoured between files and between pieces of one; what was
restored by then is reported.
"""
from __future__ import annotations
import asyncio
import contextlib
from collections.abc import AsyncIterator
from typing import Any
from urllib.parse import quote
from s365b.graph import GraphClient
from s365b.graph.client import GraphError
from s365b.modules.paths import SLASH, names
from s365b.modules.sdk import (
ModuleContext,
ModuleError,
RestoreRequest,
RestoreResult,
StoredItem,
)
# Upload pieces must be multiples of 320 KiB (and under 60 MiB).
[docs]
PIECE = 320 * 1024 * 32 # 10 MiB
[docs]
RENAME = {"@microsoft.graph.conflictBehavior": "rename"}
[docs]
PERMISSION_HINT = (
"The Restore app may not write to OneDrive. In Microsoft 365 tenant, choose Update permissions."
)
[docs]
async def pieces(source: AsyncIterator[bytes], size: int = PIECE) -> AsyncIterator[bytes]:
"""Regroup a stream into pieces of exactly ``size`` bytes (the last shorter).
Args:
source: The content, in pieces of any size.
size: Piece size.
Yields:
The pieces.
"""
buf = bytearray()
async for part in source:
buf += part
while len(buf) >= size:
yield bytes(buf[:size])
del buf[:size]
if buf:
yield bytes(buf)
[docs]
class Stopped(Exception):
"""The run was asked to stop during an upload."""
[docs]
def onedrive_names(path: str) -> tuple[str, ...]:
"""A stored folder path as OneDrive folder names.
OneDrive names cannot hold ``/``, so a ``/`` after decoding stood for a
real division slash (U+2215) in the name, which goes back as it was.
Args:
path: The stored path.
Returns:
The folder names.
"""
return tuple(n.replace("/", SLASH) for n in names(path))
[docs]
class Folders:
"""Folders of a drive by path, created when missing."""
def __init__(self, graph: GraphClient, drive: str, created: list[str]) -> None:
"""Start with only the drive's root known.
Args:
graph: Client that may write to the drive.
drive: Drive ID.
created: Paths of folders created; appended to.
"""
self.graph, self.drive, self.created = graph, drive, created
[docs]
self.ids: dict[tuple[str, ...], str] = {}
[docs]
async def ensure(self, path: tuple[str, ...]) -> str:
"""Return the ID of the folder at ``path``, creating what is missing.
Args:
path: Folder names from the drive's root; empty for the root.
Returns:
The folder's item ID.
"""
if path in self.ids:
return self.ids[path]
if not path:
root = await self.graph.get_json(f"/drives/{self.drive}/root", params={"$select": "id"})
self.ids[()] = str(root["id"])
return self.ids[()]
parent = await self.ensure(path[:-1])
name = path[-1]
url = f"/drives/{self.drive}/items/{parent}:/{quote(name, safe='')}"
try:
found = await self.graph.get_json(url, params={"$select": "id,folder"})
except GraphError as exc:
if exc.status != 404:
raise
found = None
if found is not None and "folder" not in found:
# A file has the name: put the folder beside it, renamed.
found = None
body = {"name": name, "folder": {}, **RENAME}
else:
body = {"name": name, "folder": {}, "@microsoft.graph.conflictBehavior": "fail"}
if found is None:
try:
resp = await self.graph.request(
"POST",
f"/drives/{self.drive}/items/{parent}/children",
json=body,
idempotent=False,
)
found = resp.json()
self.created.append("/".join(path))
except GraphError as exc:
if exc.status != 409: # made meanwhile, e.g. by a retry
raise
found = await self.graph.get_json(url, params={"$select": "id"})
self.ids[path] = str(found["id"])
return self.ids[path]
[docs]
async def still_in_place(reader: GraphClient, drive: str, item: StoredItem) -> bool:
"""Whether a file is still where it was backed up, with the same content.
Looked up by its backed-up path, so a file whose folder (or a folder
above it) was renamed or moved since is not there, and is restored. The
file found there counts if it is the same item with the same content
tag, or (restored before, so with a new ID) has the same size and
content hash.
Args:
reader: Client with read access (the Backup app).
drive: The drive's ID.
item: The backed-up file.
Returns:
True if restoring it would only double it.
"""
v = item.version
place = "/".join(quote(n, safe="") for n in (*onedrive_names(v.path), v.name or "file"))
try:
there = await reader.get_json(
f"/drives/{drive}/root:/{place}", params={"$select": "id,cTag,size,file,deleted"}
)
except GraphError as exc:
if exc.status in (400, 404):
return False
raise
if "deleted" in there:
return False
ctag = v.metadata.get("ctag")
if there.get("id") == v.item_key and ctag and there.get("cTag") == ctag:
return True
digest = v.metadata.get("quick_xor_hash")
hashes = (there.get("file") or {}).get("hashes") or {}
return (
bool(digest)
and hashes.get("quickXorHash") == digest
and int(there.get("size") or 0) == item.size
)
[docs]
async def upload(
graph: GraphClient,
drive: str,
folder: str,
item: StoredItem,
cancel: asyncio.Event | None = None,
) -> None:
"""Upload one file into a folder, renamed if the name is taken.
Args:
graph: Client that may write to the drive.
drive: Drive ID.
folder: The folder's item ID.
item: The backed-up file.
cancel: Set when the run is asked to stop.
Raises:
Stopped: If the run was asked to stop; the upload is abandoned.
ModuleError: If OneDrive did not confirm the file complete.
"""
v = item.version
name = v.name or "file"
target = f"/drives/{drive}/items/{folder}:/{quote(name, safe='')}:"
times: dict[str, Any] = {}
if v.metadata.get("modified"):
times = {"fileSystemInfo": {"lastModifiedDateTime": v.metadata["modified"]}}
total = item.size
if total == 0:
# Upload sessions need at least one byte.
resp = await graph.request(
"PUT",
f"{target}/content",
content=b"",
params={"@microsoft.graph.conflictBehavior": "rename"},
idempotent=False,
)
if times:
await graph.request("PATCH", f"/drives/{drive}/items/{resp.json()['id']}", json=times)
return
session = await graph.request(
"POST",
f"{target}/createUploadSession",
json={"item": {**RENAME, **times}},
idempotent=False,
)
url = str(session.json()["uploadUrl"])
done = 0
last: dict[str, Any] = {}
status = 0
try:
async for piece in pieces(item.read(), PIECE):
if cancel is not None and cancel.is_set():
raise Stopped
end = done + len(piece) - 1
if end >= total:
raise ModuleError(f"{name}: the backup holds more than its {total} bytes")
# The URL carries its own credential: no token, and only its
# host is logged.
resp = await graph.request(
"PUT",
url,
content=piece,
headers={"Content-Range": f"bytes {done}-{end}/{total}"},
authenticate=False,
idempotent=False,
)
status, last = resp.status_code, resp.json() if resp.content else {}
done = end + 1
if done != total:
raise ModuleError(f"{name}: the backup holds {done} of {total} bytes")
# 202 means OneDrive still expects pieces; 200 or 201 carry the file.
if status not in (200, 201) or not last.get("id") or last.get("size", total) != total:
raise ModuleError(f"{name}: OneDrive did not confirm the upload complete")
except BaseException:
with contextlib.suppress(Exception): # the session expires by itself anyway
await graph.request("DELETE", url, authenticate=False)
raise
[docs]
async def restore_files(ctx: ModuleContext, request: RestoreRequest) -> RestoreResult:
"""Upload backed-up files into a drive.
Options: ``destination`` is ``"original"`` (the folders they were in)
or ``"folder"`` (under a new folder named ``folder_name`` at the top of
the drive, keeping the folder structure).
Args:
ctx: Module context with the Restore app's client (and ``reader``).
request: Files and where to put them.
Returns:
The outcome.
Raises:
ModuleError: If the options are wrong, the target has no OneDrive or
the Restore app may not write to it.
"""
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.")
try:
drive = str(
(
await ctx.graph.get_json(
f"/users/{target.external_id}/drive", params={"$select": "id"}
)
)["id"]
)
except GraphError as exc:
if exc.status == 404:
raise ModuleError(f"{target.display_name} has no OneDrive.") from exc
if exc.status == 403:
raise ModuleError(PERMISSION_HINT) from exc
raise
skip_present = (
destination == "original"
and target.external_id == source.external_id
and ctx.reader is not None
)
folders = Folders(ctx.graph, drive, result.folders_created)
items = sorted(request.items, key=lambda i: (i.version.path.casefold(), i.version.name))
for done, item in enumerate(items):
if ctx.cancel.is_set():
break # stopped: report what was restored so far
ctx.progress(done=done, total=len(items), message=item.version.path, unit="items")
v = item.version
try:
if (
skip_present
and ctx.reader is not None
and await still_in_place(ctx.reader, drive, item)
):
result.skipped += 1
continue
folder = await folders.ensure(root + onedrive_names(v.path))
await upload(ctx.graph, drive, folder, item, ctx.cancel)
result.restored += 1
except Stopped:
break
except GraphError as exc:
if exc.status == 403:
raise ModuleError(PERMISSION_HINT) from exc
ctx.log.info("onedrive.restore_failed", item=v.item_key, error=str(exc))
result.fail(f"{v.path}/{v.name}: {exc.message or exc}".lstrip("/"))
except ModuleError as exc:
result.fail(str(exc))
ctx.progress(done=len(items), total=len(items), unit="items")
return result