feat: generate Vazirmatn course summary PDFs and add Library study-guide cards
This commit is contained in:
13 files changed
+394
-5
No files matched your search
@@ -382,6 +382,33 @@ ravin summarize 44 --no-keep-awake
|
||||
|
||||
Set `CODEX_SUMMARY_MODEL` in `.env` to make a model override persistent. Leave it empty to use the model configured by Codex CLI.
|
||||
|
||||
## Course summaries PDF
|
||||
|
||||
Install PDF support once, then create a PDF for a course without an LMS login:
|
||||
|
||||
```bash
|
||||
pip install 'ravin-moodle-downloader[pdf]'
|
||||
python -m playwright install chromium
|
||||
ravin pdf COURSE_ID
|
||||
```
|
||||
|
||||
The command combines all non-empty local lesson summaries in chapter and lesson order,
|
||||
preserving Markdown headings, lists, code, and tables. It embeds Vazirmatn Regular and
|
||||
Bold and uses Chromium's Unicode shaping and bidirectional layout for Persian/Arabic
|
||||
letters, Latin text, and Persian, Arabic, and Western digits. Digit characters are
|
||||
preserved as written. Raw HTML and external images are disabled.
|
||||
|
||||
The PDF is saved to `public/courses/COURSE_ID/artifacts/summaries.fa.pdf` and linked
|
||||
on the Library course card and course page immediately. Use `--public PATH` for
|
||||
another library root or `--json` for machine-readable results. Re-running replaces
|
||||
the PDF atomically. Scans mark its link outdated when summaries or their titles
|
||||
change; re-run `ravin pdf COURSE_ID` to refresh it. Courses without summaries report
|
||||
an error instead of producing an empty PDF. Only available summaries are included;
|
||||
generate missing summaries with `ravin summarize COURSE_ID` first.
|
||||
|
||||
Bundled Vazirmatn fonts are distributed under the SIL Open Font License in
|
||||
`src/ravin/fonts/OFL.txt`.
|
||||
|
||||
## Static learning library
|
||||
|
||||
The web interface is already present in the tracked `public/` directory. Generate or refresh its private data, then serve it:
|
||||
|
||||
@@ -211,6 +211,16 @@ function courseCard(course) {
|
||||
link.href = `course.html?id=${encodeURIComponent(course.id)}`;
|
||||
link.innerHTML = `Open course <span aria-hidden="true">→</span>`;
|
||||
bottom.append(track, progress, link);
|
||||
if (course.summary_pdf?.url) {
|
||||
const pdf = document.createElement("a");
|
||||
pdf.className = "guide-card-link";
|
||||
pdf.href = course.summary_pdf.url;
|
||||
pdf.target = "_blank";
|
||||
pdf.rel = "noopener";
|
||||
pdf.innerHTML = '<span class="guide-mini-icon" aria-hidden="true">▤</span><span><strong>Study guide</strong><small></small></span><span aria-hidden="true">↗</span>';
|
||||
pdf.querySelector("small").textContent = `${course.summary_pdf.summary_count || 0} lesson summaries · PDF${course.summary_pdf.state === "stale" ? " · Outdated" : ""}`;
|
||||
bottom.append(pdf);
|
||||
}
|
||||
card.append(top, title, meta, states, bottom);
|
||||
return card;
|
||||
}
|
||||
@@ -536,6 +546,12 @@ function renderCourse() {
|
||||
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
|
||||
byId("courseProgress").style.setProperty("--progress", percent);
|
||||
byId("courseSource").href = course.source_url;
|
||||
const pdf = byId("coursePdf");
|
||||
pdf.hidden = !course.summary_pdf?.url;
|
||||
if (course.summary_pdf?.url) {
|
||||
pdf.href = course.summary_pdf.url;
|
||||
setText("guideMeta", `${course.summary_pdf.summary_count || 0} lesson summaries · Persian · PDF${course.summary_pdf.state === "stale" ? " · Update available: regenerate your guide" : ""}`);
|
||||
}
|
||||
byId("resourceSearch").addEventListener("input", (event) => {
|
||||
state.query = normalized(event.target.value);
|
||||
renderResources();
|
||||
|
||||
@@ -168,6 +168,31 @@ main {
|
||||
font-size: clamp(1rem, 2vw, 1.18rem);
|
||||
}
|
||||
|
||||
#coursePdf[hidden] { display: none; }
|
||||
|
||||
.study-guide { display:flex; align-items:center; gap:28px; position:relative; overflow:hidden; margin-top:24px; padding:26px 32px; border:1px solid var(--line); border-radius:24px; background:linear-gradient(115deg, var(--surface), color-mix(in srgb, var(--accent) 13%, var(--surface))); text-decoration:none; transition:box-shadow .2s, border-color .2s; }
|
||||
.study-guide:hover { border-color:var(--accent-strong); box-shadow:var(--shadow); }
|
||||
.study-guide:focus-visible, .guide-card-link:focus-visible { outline:3px solid var(--blue); outline-offset:4px; }
|
||||
.guide-cover { flex-shrink:0; display:flex; flex-direction:column; justify-content:space-between; width:88px; height:116px; padding:14px 12px 10px 17px; border-radius:3px 9px 9px 3px; background:#1c5166; color:#f5f3ec; box-shadow:-4px 0 0 #123a4b, 3px 3px 0 #dedfd4, 7px 10px 18px #17212620; transform:rotate(-6deg); transition:transform .2s; border-left:2px solid #ffffff25; }
|
||||
.study-guide:hover .guide-cover { transform:rotate(-2deg) translateY(-2px); }
|
||||
.guide-cover-label { font-size:11px; line-height:1.3; font-weight:850; letter-spacing:.08em; }
|
||||
.guide-cover-lines { width:42px; height:16px; background:repeating-linear-gradient(to bottom, #d8f26a 0 2px, transparent 2px 7px); }
|
||||
.guide-cover-format { align-self:flex-end; font-size:9px; font-weight:800; letter-spacing:.12em; color:#d8f26a; }
|
||||
.guide-copy { display:grid; gap:6px; flex:1; min-width:0; }
|
||||
.guide-eyebrow { color:var(--blue); font-size:.65rem; font-weight:850; letter-spacing:.14em; }
|
||||
.guide-copy strong { font-size:clamp(1.3rem, 3vw, 1.8rem); line-height:1.25; letter-spacing:-.04em; }
|
||||
.guide-description { color:var(--muted); font-size:.88rem; }
|
||||
.guide-meta { color:var(--muted); font-size:.73rem; margin-top:5px; }
|
||||
.guide-action { display:flex; gap:20px; align-items:center; padding:12px 18px; border-radius:12px; background:var(--ink); color:var(--paper); font-size:.8rem; font-weight:750; white-space:nowrap; }
|
||||
.guide-card-link { display:flex; align-items:center; gap:12px; margin-top:18px; padding:12px; border:1px solid var(--line); border-radius:12px; text-decoration:none; background:color-mix(in srgb, var(--accent) 10%, var(--surface)); }
|
||||
.guide-card-link > span:nth-child(2) { flex:1; display:grid; gap:2px; }
|
||||
.guide-card-link strong { font-size:.8rem; }
|
||||
.guide-card-link small { font-size:.68rem; color:var(--muted); }
|
||||
.guide-mini-icon { display:grid; place-items:center; width:32px; height:38px; border-radius:5px; background:var(--blue-soft); color:var(--blue); font-size:22px; }
|
||||
@media(max-width:700px) { .study-guide { gap:20px; padding:22px; flex-wrap:wrap; } .guide-action { margin-left:108px; } }
|
||||
@media(max-width:420px) { .guide-cover { width:64px; height:94px; padding:10px; } .guide-cover-label { font-size:9px; } .guide-description { font-size:.78rem; } .guide-action { margin-left:84px; padding:10px 12px; } }
|
||||
@media(prefers-reduced-motion:reduce) { .guide-cover, .study-guide { transition:none; } }
|
||||
|
||||
.hero-source {
|
||||
display: inline-flex;
|
||||
margin-top: 22px;
|
||||
|
||||
+8
-2
@@ -5,8 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="description" content="Browse the resources in a downloaded course.">
|
||||
<title>Course · Learning Library</title>
|
||||
<link rel="stylesheet" href="assets/styles.css">
|
||||
<script src="assets/app.js" defer></script>
|
||||
<link rel="stylesheet" href="assets/styles.css?v=course-pdf-3">
|
||||
<script src="assets/app.js?v=course-pdf-3" defer></script>
|
||||
</head>
|
||||
<body data-page="course">
|
||||
<header class="topbar">
|
||||
@@ -42,6 +42,12 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<a class="study-guide" id="coursePdf" hidden target="_blank" rel="noopener" aria-labelledby="guideTitle">
|
||||
<span class="guide-cover" aria-hidden="true"><span class="guide-cover-label">COURSE<br>NOTES</span><span class="guide-cover-lines"></span><span class="guide-cover-format">PDF</span></span>
|
||||
<span class="guide-copy"><span class="guide-eyebrow">YOUR STUDY COMPANION</span><strong id="guideTitle">The course, collected.</strong><span class="guide-description">Your lesson summaries in one beautifully readable guide.</span><span class="guide-meta" id="guideMeta"></span></span>
|
||||
<span class="guide-action">Open study guide <span aria-hidden="true">↗</span></span>
|
||||
</a>
|
||||
|
||||
<section class="course-toolbar" aria-label="Resource controls">
|
||||
<label class="search-box resource-search">
|
||||
<span aria-hidden="true">⌕</span>
|
||||
|
||||
+2
-2
@@ -5,8 +5,8 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="description" content="A private, local library for downloaded course materials.">
|
||||
<title>Learning Library</title>
|
||||
<link rel="stylesheet" href="assets/styles.css">
|
||||
<script src="assets/app.js" defer></script>
|
||||
<link rel="stylesheet" href="assets/styles.css?v=course-pdf-3">
|
||||
<script src="assets/app.js?v=course-pdf-3" defer></script>
|
||||
</head>
|
||||
<body data-page="index">
|
||||
<header class="topbar">
|
||||
|
||||
@@ -27,6 +27,7 @@ classifiers = [
|
||||
dependencies = ["selenium>=4.46,<5"]
|
||||
|
||||
[project.optional-dependencies]
|
||||
pdf = ["playwright>=1.50,<2", "markdown-it-py>=3,<5"]
|
||||
transcribe = [
|
||||
"openai-whisper==20250625",
|
||||
"torch==2.13.0",
|
||||
@@ -40,3 +41,6 @@ package-dir = {"" = "src"}
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["src"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
ravin = ["fonts/*.ttf", "fonts/OFL.txt"]
|
||||
@@ -70,6 +70,11 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
|
||||
subparsers.add_parser("login", help="open a browser and refresh the saved LMS session")
|
||||
|
||||
pdf_parser = subparsers.add_parser("pdf", help="create a course PDF from its local summaries")
|
||||
pdf_parser.add_argument("course_id", type=int)
|
||||
pdf_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||
pdf_parser.add_argument("--json", action="store_true", help="print PDF details as JSON")
|
||||
|
||||
scan_parser = subparsers.add_parser("scan", help="scan LMS courses and reconcile local learning state")
|
||||
scan_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all courses")
|
||||
scan_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||
@@ -299,6 +304,13 @@ def _authenticate(args: argparse.Namespace) -> tuple[MoodleClient, str]:
|
||||
def main(argv: list[str] | None = None) -> int:
|
||||
args = build_parser().parse_args(argv)
|
||||
try:
|
||||
if args.command == "pdf":
|
||||
from .course_pdf import create_course_pdf
|
||||
result = create_course_pdf(args.public, args.course_id)
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2) if args.json else
|
||||
f"Created PDF from {result['summary_count']} summaries: {result['path']}")
|
||||
return 0
|
||||
|
||||
if args.command == "serve":
|
||||
_serve_library(args.public, args.host, args.port, args.open)
|
||||
return 0
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
"""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'<h1 dir="auto">{escape(course.get("fullname") or str(course["id"]))}</h1>']
|
||||
previous = None
|
||||
for chapter, title, path in sources:
|
||||
if chapter != previous:
|
||||
body.append(f'<h2 dir="auto">{escape(chapter)}</h2>')
|
||||
previous = chapter
|
||||
content = markdown.render(path.read_text(encoding="utf-8"))
|
||||
body.append(f'<section><h3 dir="auto">{escape(title)}</h3>{content}</section>')
|
||||
return '<!doctype html><html lang="fa" dir="rtl"><meta charset="utf-8"><style>' + ''.join(faces) + '''
|
||||
@page { size:A4; margin:18mm 16mm 20mm; }
|
||||
body {font-family:Vazirmatn; font-size:11pt; line-height:1.9; color:#182334;}
|
||||
h1 {font-size:24pt;} h2 {font-size:18pt; border-bottom:1px solid #ccd5df;}
|
||||
h3 {font-size:14pt;} h1,h2,h3 {break-after:avoid;}
|
||||
p,li,td,th {unicode-bidi:plaintext; overflow-wrap:anywhere;}
|
||||
pre {direction:ltr; text-align:left; white-space:pre-wrap; unicode-bidi:isolate;}
|
||||
code {font-family:Vazirmatn; unicode-bidi:isolate; direction:ltr;}
|
||||
table {width:100%; border-collapse:collapse; font-size:10pt;}
|
||||
th,td {border:1px solid #ccd5df; padding:5px;}
|
||||
tr,blockquote {break-inside:avoid;} a {color:#245b8c;}
|
||||
</style><body>''' + ''.join(body) + '</body></html>'
|
||||
|
||||
|
||||
def create_course_pdf(public: Path, course_id: int) -> dict:
|
||||
"""Atomically replace the course PDF and refresh Library manifests."""
|
||||
from .scan import _atomic_json
|
||||
public = public.expanduser().resolve()
|
||||
scan_offline(public, [course_id])
|
||||
course = _read_json_object(public / "courses" / str(course_id) / "manifest.json")["course"]
|
||||
sources = summary_sources(public, course)
|
||||
if not sources:
|
||||
raise MoodleError(f"course {course_id} has no non-empty summaries; run `ravin summarize {course_id}` first")
|
||||
try:
|
||||
from playwright.sync_api import sync_playwright, Error
|
||||
html = render_html(course, sources)
|
||||
except ImportError as exc:
|
||||
raise MoodleError('PDF support requires `pip install "ravin-moodle-downloader[pdf]"` and `python -m playwright install chromium`') from exc
|
||||
target = public / "courses" / str(course_id) / "artifacts" / "summaries.fa.pdf"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
digest = source_digest(course, sources)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory(prefix=".pdf-", dir=target.parent) as temporary:
|
||||
output = Path(temporary) / "course.pdf"
|
||||
with sync_playwright() as playwright:
|
||||
browser = playwright.chromium.launch()
|
||||
try:
|
||||
page = browser.new_page()
|
||||
page.route("**/*", lambda route: route.abort())
|
||||
page.set_content(html, wait_until="load")
|
||||
page.evaluate("document.fonts.ready")
|
||||
page.pdf(path=str(output), format="A4", print_background=True,
|
||||
prefer_css_page_size=True, display_header_footer=True,
|
||||
header_template="<span></span>",
|
||||
footer_template='<div style="width:100%;text-align:center;font-size:9px"><span class="pageNumber"></span> / <span class="totalPages"></span></div>')
|
||||
finally:
|
||||
browser.close()
|
||||
output.replace(target)
|
||||
except Error as exc:
|
||||
raise MoodleError(f"PDF rendering failed; install Chromium with `python -m playwright install chromium`: {exc}") from exc
|
||||
_atomic_json(target.with_suffix(".meta.json"), {"source_sha256": digest, "summary_count": len(sources)})
|
||||
scan_offline(public, [course_id])
|
||||
return {"course_id": course_id, "path": str(target), "summary_count": len(sources)}
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2015 The Vazirmatn Project Authors (https://github.com/rastikerdar/vazirmatn)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
+3
-1
@@ -361,6 +361,8 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
|
||||
},
|
||||
}
|
||||
)
|
||||
from .course_pdf import summary_pdf_artifact
|
||||
course["summary_pdf"] = summary_pdf_artifact(public, course)
|
||||
return course
|
||||
|
||||
|
||||
@@ -369,7 +371,7 @@ def _course_summary(course: dict[str, Any]) -> dict[str, Any]:
|
||||
key: course.get(key)
|
||||
for key in (
|
||||
"id", "fullname", "shortname", "source_url", "section_count", "activity_count",
|
||||
"record_count", "file_count", "downloaded_count", "downloaded_bytes", "type_counts", "states",
|
||||
"record_count", "file_count", "downloaded_count", "downloaded_bytes", "type_counts", "states", "summary_pdf",
|
||||
)
|
||||
} | {"manifest_url": f"courses/{course.get('id')}/manifest.json"}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
from ravin.course_pdf import create_course_pdf, render_html, source_digest, summary_sources
|
||||
from ravin.models import MoodleError
|
||||
from ravin.scan import scan_offline
|
||||
from ravin.cli import build_parser
|
||||
|
||||
|
||||
class CoursePdfTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.public = Path(self.temp.name)
|
||||
self.path = self.public / 'courses/44/content/001--001--101/artifacts/summary.fa.md'
|
||||
self.path.parent.mkdir(parents=True)
|
||||
self.path.write_text('# شبکه\n\nاعداد ۱۲۳ و ١٢٣ و 123، IP 192.168.1.1\n\n| نام | مقدار |\n| --- | --- |\n| پورت | 8080 |\n\n<script>alert(1)</script>\n', encoding='utf-8')
|
||||
self.course = {'id': 44, 'fullname': 'شبکه Network+', 'sections': [
|
||||
{'number': 1, 'name': 'فصل اول', 'items': [
|
||||
{'title': 'درس اول', 'activity_id': 101, 'activity_position': 1, 'section_number': 1,
|
||||
'artifacts': {'summary': {'url': self.path.relative_to(self.public).as_posix()}}}]}]}
|
||||
(self.public / 'courses/44/manifest.json').write_text(json.dumps({'course': self.course}), encoding='utf-8')
|
||||
|
||||
def test_unicode_and_safe_markdown(self):
|
||||
try:
|
||||
html = render_html(self.course, summary_sources(self.public, self.course))
|
||||
except ImportError:
|
||||
self.skipTest('PDF optional dependencies are not installed')
|
||||
for text in ['۱۲۳', '١٢٣', '123', '192.168.1.1', 'Vazirmatn', '<table>', 'فصل اول']:
|
||||
self.assertIn(text, html)
|
||||
self.assertNotIn('<script>', html)
|
||||
self.assertIn('<script>', html)
|
||||
|
||||
def test_manifest_pdf_discovery_and_freshness(self):
|
||||
scan_offline(self.public, [44])
|
||||
course = json.loads((self.public / 'courses/44/manifest.json').read_text())['course']
|
||||
target = self.public / 'courses/44/artifacts/summaries.fa.pdf'
|
||||
target.parent.mkdir()
|
||||
target.write_bytes(b'%PDF-test')
|
||||
target.with_suffix('.meta.json').write_text(json.dumps({
|
||||
'source_sha256': source_digest(course, summary_sources(self.public, course)), 'summary_count': 1}))
|
||||
catalog = scan_offline(self.public, [44])
|
||||
self.assertEqual(catalog['courses'][0]['summary_pdf']['state'], 'complete')
|
||||
self.path.write_text('خلاصه جدید', encoding='utf-8')
|
||||
self.assertEqual(scan_offline(self.public, [44])['courses'][0]['summary_pdf']['state'], 'stale')
|
||||
|
||||
def test_empty_course(self):
|
||||
self.path.unlink()
|
||||
with self.assertRaisesRegex(MoodleError, 'no non-empty summaries'):
|
||||
create_course_pdf(self.public, 44)
|
||||
|
||||
def test_no_path_escape(self):
|
||||
self.course['sections'][0]['items'][0]['artifacts']['summary']['url'] = '../outside.md'
|
||||
with self.assertRaises(MoodleError):
|
||||
summary_sources(self.public, self.course)
|
||||
|
||||
def test_cli(self):
|
||||
args = build_parser().parse_args(['pdf', '44', '--json'])
|
||||
self.assertEqual(args.course_id, 44)
|
||||
self.assertTrue(args.json)
|
||||
|
||||
def test_render_failure_preserves_old_pdf(self):
|
||||
try:
|
||||
from playwright.sync_api import Error
|
||||
except ImportError:
|
||||
self.skipTest('PDF optional dependencies are not installed')
|
||||
target = self.public / 'courses/44/artifacts/summaries.fa.pdf'
|
||||
target.parent.mkdir()
|
||||
target.write_bytes(b'old PDF')
|
||||
with patch('playwright.sync_api.sync_playwright', side_effect=Error('failed')):
|
||||
with self.assertRaises(MoodleError):
|
||||
create_course_pdf(self.public, 44)
|
||||
self.assertEqual(target.read_bytes(), b'old PDF')
|
||||
Reference in new issue
Block a user