"""Offline course summary PDFs, rendered with Unicode shaping in Chromium.""" from __future__ import annotations import base64 import hashlib from html import escape from pathlib import Path import tempfile from urllib.parse import unquote from .models import MoodleError from .paths import _read_json_object, _relative_browser_path from .scan import scan_offline def summary_sources(public: Path, course: dict) -> list[tuple[str, str, Path]]: """Read summaries in manifest order, once per activity bundle.""" sources = [] seen = set() root = (public / "courses" / str(course["id"])).resolve() for section in course.get("sections", []): for item in section.get("items", []): url = item.get("artifacts", {}).get("summary", {}).get("url") if not url: continue path = (public / unquote(url)).resolve() if not path.is_relative_to(root): raise MoodleError(f"summary is outside its course directory: {url}") if path in seen or not path.is_file(): continue seen.add(path) if path.read_text(encoding="utf-8").strip(): sources.append((section.get("title") or section.get("name") or "", item.get("title") or "", path)) return sources def source_digest(course: dict, sources: list[tuple[str, str, Path]]) -> str: digest = hashlib.sha256(str(course.get("fullname", "")).encode()) for chapter, title, path in sources: digest.update((chapter + "\0" + title + "\0").encode()) digest.update(path.read_bytes()) return digest.hexdigest() def summary_pdf_artifact(public: Path, course: dict) -> dict | None: path = public / "courses" / str(course["id"]) / "artifacts" / "summaries.fa.pdf" if not path.is_file(): return None metadata = _read_json_object(path.with_suffix(".meta.json")) sources = summary_sources(public, course) return {"url": _relative_browser_path(path, public), "format": "pdf", "language": "fa", "summary_count": metadata.get("summary_count", 0), "state": "complete" if metadata.get("source_sha256") == source_digest(course, sources) else "stale"} def render_html(course: dict, sources: list[tuple[str, str, Path]]) -> str: from markdown_it import MarkdownIt markdown = MarkdownIt("commonmark", {"html": False}).enable("table") # No external resources or raw HTML from summaries are loaded by the renderer. markdown.disable("image") faces = [] for weight, name in ((400, "Regular"), (700, "Bold")): data = base64.b64encode((Path(__file__).parent / "fonts" / f"Vazirmatn-{name}.ttf").read_bytes()).decode() faces.append(f"@font-face{{font-family:Vazirmatn;font-weight:{weight};src:url(data:font/ttf;base64,{data})}}") body = [f'