feat: unify course scanning and add manifest-based public library

This commit is contained in:
Meghdad committed 2026-08-04 21:55:15 +03:30
1 parent 2580d86984
commit 114b472643
20 files changed
+809 -796

No files matched your search

-1
View File
@@ -1 +0,0 @@
"""Static assets for the generated local course library."""
-483
View File
@@ -1,483 +0,0 @@
const state = { catalog: null, course: null, query: "", filter: "all" };
const byId = (id) => document.getElementById(id);
const clampPercent = (value) => Math.max(0, Math.min(100, Math.round(value || 0)));
function formatBytes(bytes) {
if (!Number.isFinite(bytes) || bytes <= 0) return "—";
const units = ["B", "KB", "MB", "GB", "TB"];
let value = bytes;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index += 1;
}
const digits = value >= 10 || index === 0 ? 0 : 1;
return `${value.toFixed(digits)} ${units[index]}`;
}
function normalized(value) {
return String(value || "").toLocaleLowerCase().trim();
}
function setText(id, value) {
const element = byId(id);
if (element) element.textContent = value;
}
function appendMarkdownInline(parent, text) {
const pattern = /(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g;
let offset = 0;
for (const match of text.matchAll(pattern)) {
parent.append(document.createTextNode(text.slice(offset, match.index)));
const token = match[0];
if (token.startsWith("**")) {
const strong = document.createElement("strong");
strong.textContent = token.slice(2, -2);
parent.append(strong);
} else if (token.startsWith("`")) {
const code = document.createElement("code");
code.textContent = token.slice(1, -1);
parent.append(code);
} else {
const parts = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
const link = document.createElement("a");
link.textContent = parts[1];
if (/^(https?:\/\/|\.\.?\/)/.test(parts[2])) {
link.href = parts[2];
link.target = "_blank";
link.rel = "noopener";
}
parent.append(link);
}
offset = match.index + token.length;
}
parent.append(document.createTextNode(text.slice(offset)));
}
function markdownCells(line) {
return line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
}
function renderMarkdown(target, source) {
target.innerHTML = "";
const lines = source.replace(/\r\n?/g, "\n").split("\n");
let list = null;
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
if (!line.trim()) {
list = null;
continue;
}
const heading = line.match(/^(#{1,4})\s+(.+)$/);
if (heading) {
list = null;
const element = document.createElement(`h${heading[1].length}`);
appendMarkdownInline(element, heading[2]);
target.append(element);
continue;
}
if (line.includes("|") && index + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[index + 1])) {
list = null;
const table = document.createElement("table");
const head = document.createElement("thead");
const headRow = document.createElement("tr");
markdownCells(line).forEach((cell) => {
const th = document.createElement("th");
appendMarkdownInline(th, cell);
headRow.append(th);
});
head.append(headRow);
table.append(head);
const body = document.createElement("tbody");
index += 2;
while (index < lines.length && lines[index].includes("|") && lines[index].trim()) {
const row = document.createElement("tr");
markdownCells(lines[index]).forEach((cell) => {
const td = document.createElement("td");
appendMarkdownInline(td, cell);
row.append(td);
});
body.append(row);
index += 1;
}
index -= 1;
table.append(body);
target.append(table);
continue;
}
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
const numbered = line.match(/^\s*\d+[.)]\s+(.+)$/);
if (bullet || numbered) {
const type = bullet ? "ul" : "ol";
if (!list || list.tagName.toLowerCase() !== type) {
list = document.createElement(type);
target.append(list);
}
const item = document.createElement("li");
appendMarkdownInline(item, (bullet || numbered)[1]);
list.append(item);
continue;
}
list = null;
const quote = line.match(/^>\s?(.*)$/);
const paragraph = document.createElement(quote ? "blockquote" : "p");
appendMarkdownInline(paragraph, quote ? quote[1] : line);
target.append(paragraph);
}
}
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
localStorage.setItem("ravin-library-theme", theme);
}
function setupTheme() {
const stored = localStorage.getItem("ravin-library-theme");
const preferred = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
applyTheme(stored || preferred);
byId("themeToggle")?.addEventListener("click", () => {
applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark");
});
}
async function loadCatalog() {
const response = await fetch("courses.json", { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load courses.json (${response.status})`);
return response.json();
}
function showLoadError(error) {
const target = byId("courseGrid") || byId("sectionList");
if (!target) return;
target.innerHTML = "";
const box = document.createElement("div");
box.className = "empty-state";
const title = document.createElement("strong");
title.textContent = "The course data could not be loaded";
const detail = document.createElement("span");
detail.textContent = "Open this library with ‘ravin serve-library’, then refresh the page.";
box.append(title, detail);
target.append(box);
console.error(error);
}
function courseCard(course) {
const percent = clampPercent((course.downloaded_count / Math.max(course.file_count, 1)) * 100);
const card = document.createElement("article");
card.className = "course-card";
const top = document.createElement("div");
top.className = "course-card-top";
const code = document.createElement("span");
code.className = "course-code";
code.textContent = course.shortname || `Course ${course.id}`;
const badge = document.createElement("span");
badge.className = "course-badge";
badge.textContent = `${course.activity_count ?? course.file_count} activities`;
top.append(code, badge);
const title = document.createElement("h3");
title.dir = "auto";
title.textContent = course.fullname;
const meta = document.createElement("p");
meta.className = "course-card-meta";
meta.textContent = `${course.section_count} chapters · ${course.file_count} files · ${formatBytes(course.downloaded_bytes)} offline`;
const bottom = document.createElement("div");
bottom.className = "course-card-bottom";
const track = document.createElement("div");
track.className = "progress-track";
const fill = document.createElement("span");
fill.style.setProperty("--progress", `${percent}%`);
track.append(fill);
const progress = document.createElement("div");
progress.className = "progress-copy";
progress.innerHTML = `<span>${course.downloaded_count} offline</span><strong>${percent}%</strong>`;
const link = document.createElement("a");
link.className = "course-link";
link.href = `course.html?id=${encodeURIComponent(course.id)}`;
link.innerHTML = `Open course <span aria-hidden="true">→</span>`;
bottom.append(track, progress, link);
card.append(top, title, meta, bottom);
return card;
}
function renderCourseGrid() {
const grid = byId("courseGrid");
const query = normalized(byId("courseSearch")?.value);
const courses = state.catalog.courses.filter((course) => normalized(`${course.fullname} ${course.shortname}`).includes(query));
grid.innerHTML = "";
courses.forEach((course) => grid.append(courseCard(course)));
byId("emptyCourses").hidden = courses.length !== 0;
}
function renderIndex() {
const stats = state.catalog.stats;
const percent = clampPercent((stats.downloaded_files / Math.max(stats.files, 1)) * 100);
setText("heroPercent", `${percent}%`);
setText("courseCount", stats.courses.toLocaleString());
setText("resourceCount", (stats.activities ?? stats.files).toLocaleString());
setText("downloadedCount", stats.downloaded_files.toLocaleString());
setText("librarySize", formatBytes(stats.downloaded_bytes));
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
byId("courseSearch").addEventListener("input", renderCourseGrid);
renderCourseGrid();
}
function completionKey(item) {
return `ravin-complete-${state.course.id}-${item.id}`;
}
function isComplete(item) {
return localStorage.getItem(completionKey(item)) === "1";
}
function resourceMatches(item) {
const haystack = normalized(`${item.title} ${item.filename} ${item.section}`);
if (state.query && !haystack.includes(state.query)) return false;
if (state.filter === "all") return true;
if (state.filter === "downloaded" || state.filter === "missing") return item.status === state.filter;
return item.kind === state.filter;
}
function resourceRow(item, index) {
const row = document.createElement("article");
row.className = `resource-row${isComplete(item) ? " completed" : ""}`;
const number = document.createElement("span");
number.className = "resource-index";
number.textContent = String(index + 1).padStart(2, "0");
const main = document.createElement("div");
main.className = "resource-main";
const title = document.createElement("span");
title.className = "resource-title";
title.dir = "auto";
title.textContent = item.title;
const filename = document.createElement("span");
filename.className = "resource-file";
filename.dir = "auto";
filename.textContent = item.filename || item.badge || item.activity_type;
main.append(title, filename);
if (item.description) {
const description = document.createElement("span");
description.className = "resource-description";
description.dir = "auto";
description.textContent = item.description;
main.append(description);
}
const artifactLabels = {
questions: "Questions",
summary: "Summary",
transcript: "Transcript",
};
const availableArtifacts = Object.keys(artifactLabels).filter((kind) => item.artifacts?.[kind]?.url);
if (availableArtifacts.length) {
const artifactActions = document.createElement("div");
artifactActions.className = "artifact-actions";
availableArtifacts.forEach((kind) => {
const button = document.createElement("button");
button.type = "button";
button.className = "artifact-button";
button.textContent = artifactLabels[kind];
button.addEventListener("click", () => openArtifact(item, kind));
artifactActions.append(button);
});
main.append(artifactActions);
}
const meta = document.createElement("div");
meta.className = "resource-meta";
const type = document.createElement("span");
type.className = "type-pill";
type.textContent = item.kind;
const dot = document.createElement("span");
dot.className = `status-dot${item.status === "missing" ? " missing" : item.status === "online" ? " online" : ""}`;
const size = document.createElement("span");
size.textContent = item.status === "partial"
? `${formatBytes(item.local_bytes)} partial`
: item.status === "online"
? (item.lms_completed ? "LMS complete" : "Online")
: formatBytes(item.size);
meta.append(type, dot, size);
let action;
if (item.status === "downloaded" && item.kind === "video") {
action = document.createElement("button");
action.type = "button";
action.textContent = "Play";
action.addEventListener("click", () => openVideo(item));
} else if (item.status === "downloaded") {
action = document.createElement("a");
action.href = item.local_url;
action.target = "_blank";
action.rel = "noopener";
action.textContent = item.kind === "document" ? "Open" : "View";
} else if (item.status === "online" && item.source_url) {
action = document.createElement("a");
action.href = item.source_url;
action.target = "_blank";
action.rel = "noopener";
action.textContent = "Open LMS";
} else {
action = document.createElement("span");
action.textContent = item.status === "partial" ? "Partial" : "Missing";
action.setAttribute("aria-disabled", "true");
}
action.className = "action-button";
const complete = document.createElement("input");
complete.className = "complete-check";
complete.type = "checkbox";
complete.checked = isComplete(item);
complete.setAttribute("aria-label", `Mark ${item.title} complete`);
complete.addEventListener("change", () => {
localStorage.setItem(completionKey(item), complete.checked ? "1" : "0");
row.classList.toggle("completed", complete.checked);
});
row.append(number, main, meta, action, complete);
return row;
}
function renderResources() {
const container = byId("sectionList");
container.innerHTML = "";
let visibleCount = 0;
let runningIndex = 0;
state.course.sections.forEach((section) => {
const items = section.items.filter(resourceMatches);
if (!items.length) return;
visibleCount += items.length;
const wrapper = document.createElement("section");
wrapper.className = "resource-section";
const heading = document.createElement("div");
heading.className = "resource-section-header";
const title = document.createElement("h2");
title.dir = "auto";
title.textContent = section.name;
const count = document.createElement("span");
count.textContent = `${items.length} resource${items.length === 1 ? "" : "s"}`;
heading.append(title, count);
if (section.summary) {
const summary = document.createElement("p");
summary.className = "section-summary";
summary.dir = "auto";
summary.textContent = section.summary;
heading.append(summary);
}
const list = document.createElement("div");
list.className = "resource-list";
items.forEach((item) => {
list.append(resourceRow(item, runningIndex));
runningIndex += 1;
});
wrapper.append(heading, list);
container.append(wrapper);
});
byId("emptyResources").hidden = visibleCount !== 0;
}
function openVideo(item) {
const dialog = byId("mediaDialog");
const player = byId("mediaPlayer");
setText("mediaTitle", item.title);
player.src = item.local_url;
dialog.showModal();
player.play().catch(() => {});
}
function closeVideo() {
const dialog = byId("mediaDialog");
const player = byId("mediaPlayer");
player.pause();
player.removeAttribute("src");
player.load();
dialog.close();
}
async function openArtifact(item, kind) {
const artifact = item.artifacts?.[kind];
if (!artifact) return;
const dialog = byId("artifactDialog");
const content = byId("artifactContent");
const labels = { questions: "Exam questions", summary: "Lesson summary", transcript: "Transcript" };
setText("artifactEyebrow", labels[kind] || "Course material");
setText("artifactTitle", item.title);
content.innerHTML = '<p class="artifact-loading">Loading…</p>';
dialog.showModal();
try {
const response = await fetch(artifact.url, { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load ${artifact.url} (${response.status})`);
const source = await response.text();
if (artifact.format === "markdown") renderMarkdown(content, source);
else {
content.innerHTML = "";
const transcript = document.createElement("pre");
transcript.className = "transcript-text";
transcript.textContent = source;
content.append(transcript);
}
} catch (error) {
content.textContent = "This material could not be loaded.";
console.error(error);
}
}
function closeArtifact() {
byId("artifactDialog").close();
byId("artifactContent").innerHTML = "";
}
function renderCourse() {
const id = new URLSearchParams(window.location.search).get("id");
state.course = state.catalog.courses.find((course) => String(course.id) === String(id));
if (!state.course) {
showLoadError(new Error(`Course ${id || "(missing)"} was not found`));
return;
}
const course = state.course;
document.title = `${course.fullname} · Learning Library`;
const percent = clampPercent((course.downloaded_count / Math.max(course.file_count, 1)) * 100);
setText("breadcrumbCourse", course.fullname);
setText("courseCode", course.shortname || `Course ${course.id}`);
setText("courseTitle", course.fullname);
setText("courseSummary", `${course.activity_count ?? course.file_count} activities, ${course.file_count} downloadable files, and ${course.section_count} chapters.`);
setText("coursePercent", `${percent}%`);
setText("courseDownloaded", `${course.downloaded_count} of ${course.file_count}`);
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
byId("courseProgress").style.setProperty("--progress", percent);
byId("courseSource").href = course.source_url;
byId("resourceSearch").addEventListener("input", (event) => {
state.query = normalized(event.target.value);
renderResources();
});
byId("resourceFilters").addEventListener("click", (event) => {
const button = event.target.closest("button[data-filter]");
if (!button) return;
state.filter = button.dataset.filter;
document.querySelectorAll("button[data-filter]").forEach((item) => item.classList.toggle("active", item === button));
renderResources();
});
byId("closeMedia").addEventListener("click", closeVideo);
byId("mediaDialog").addEventListener("click", (event) => {
if (event.target === byId("mediaDialog")) closeVideo();
});
byId("closeArtifact").addEventListener("click", closeArtifact);
byId("artifactDialog").addEventListener("click", (event) => {
if (event.target === byId("artifactDialog")) closeArtifact();
});
renderResources();
}
async function start() {
setupTheme();
try {
state.catalog = await loadCatalog();
if (document.body.dataset.page === "course") renderCourse();
else renderIndex();
} catch (error) {
showLoadError(error);
}
}
start();
-84
View File
@@ -1,84 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-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="styles.css">
<script src="app.js" defer></script>
</head>
<body data-page="course">
<header class="topbar">
<a class="brand" href="index.html" aria-label="Back to Learning Library">
<span class="brand-mark" aria-hidden="true">R</span>
<span>Learning Library</span>
</a>
<button class="icon-button" id="themeToggle" type="button" aria-label="Toggle color theme">◐</button>
</header>
<main>
<nav class="breadcrumbs" aria-label="Breadcrumb">
<a href="index.html">Library</a><span aria-hidden="true">/</span><span id="breadcrumbCourse">Course</span>
</nav>
<section class="course-hero" aria-labelledby="courseTitle">
<div class="course-heading">
<p class="eyebrow" id="courseCode">Course</p>
<h1 id="courseTitle">Loading course…</h1>
<p class="hero-copy" id="courseSummary"></p>
<a class="hero-source" id="courseSource" href="#" target="_blank" rel="noopener">Open in LMS ↗</a>
</div>
<div class="progress-panel">
<div class="progress-ring" id="courseProgress" style="--progress: 0">
<span id="coursePercent">0%</span>
</div>
<div><strong id="courseDownloaded">0 of 0</strong><span>files available offline</span></div>
</div>
</section>
<section class="course-toolbar" aria-label="Resource controls">
<label class="search-box resource-search">
<span aria-hidden="true">⌕</span>
<span class="sr-only">Search lessons and files</span>
<input id="resourceSearch" type="search" placeholder="Search lessons and files" autocomplete="off">
</label>
<div class="filter-group" id="resourceFilters" aria-label="Filter resources">
<button class="filter-chip active" type="button" data-filter="all">All</button>
<button class="filter-chip" type="button" data-filter="video">Videos</button>
<button class="filter-chip" type="button" data-filter="document">Documents</button>
<button class="filter-chip" type="button" data-filter="assessment">Exams</button>
<button class="filter-chip" type="button" data-filter="downloaded">Offline</button>
<button class="filter-chip" type="button" data-filter="missing">Missing</button>
</div>
</section>
<div class="section-list" id="sectionList" aria-live="polite"></div>
<div class="empty-state" id="emptyResources" hidden>
<strong>No matching resources</strong>
<span>Change the search or filter to see more.</span>
</div>
</main>
<dialog class="media-dialog" id="mediaDialog">
<div class="dialog-heading">
<div><p class="eyebrow">Now playing</p><h2 id="mediaTitle"></h2></div>
<button class="icon-button" id="closeMedia" type="button" aria-label="Close player">×</button>
</div>
<video id="mediaPlayer" controls preload="metadata"></video>
</dialog>
<dialog class="artifact-dialog" id="artifactDialog">
<div class="dialog-heading">
<div><p class="eyebrow" id="artifactEyebrow">Course material</p><h2 id="artifactTitle"></h2></div>
<button class="icon-button" id="closeArtifact" type="button" aria-label="Close course material">×</button>
</div>
<article class="artifact-content" id="artifactContent" dir="auto"></article>
</dialog>
<footer>
<a href="index.html">← All courses</a>
<span id="generatedAt"></span>
</footer>
</body>
</html>
-65
View File
@@ -1,65 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-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="styles.css">
<script src="app.js" defer></script>
</head>
<body data-page="index">
<header class="topbar">
<a class="brand" href="index.html" aria-label="Learning Library home">
<span class="brand-mark" aria-hidden="true">R</span>
<span>Learning Library</span>
</a>
<button class="icon-button" id="themeToggle" type="button" aria-label="Toggle color theme">◐</button>
</header>
<main>
<section class="hero" aria-labelledby="pageTitle">
<div>
<p class="eyebrow">Your offline study space</p>
<h1 id="pageTitle">Pick up where you left off.</h1>
<p class="hero-copy">Every course, lesson, video, and document—organized around the work you want to finish.</p>
</div>
<div class="hero-orbit" aria-hidden="true">
<span class="orbit-number" id="heroPercent">0%</span>
<span class="orbit-label">available offline</span>
</div>
</section>
<section class="stat-grid" aria-label="Library summary">
<article class="stat-card"><span class="stat-label">Courses</span><strong id="courseCount">—</strong></article>
<article class="stat-card"><span class="stat-label">Resources</span><strong id="resourceCount">—</strong></article>
<article class="stat-card"><span class="stat-label">Downloaded</span><strong id="downloadedCount">—</strong></article>
<article class="stat-card"><span class="stat-label">Library size</span><strong id="librarySize">—</strong></article>
</section>
<section class="library-section" aria-labelledby="coursesHeading">
<div class="section-heading">
<div>
<p class="eyebrow">Course collection</p>
<h2 id="coursesHeading">Your courses</h2>
</div>
<label class="search-box">
<span aria-hidden="true">⌕</span>
<span class="sr-only">Search courses</span>
<input id="courseSearch" type="search" placeholder="Search courses" autocomplete="off">
</label>
</div>
<div class="course-grid" id="courseGrid" aria-live="polite"></div>
<div class="empty-state" id="emptyCourses" hidden>
<strong>No matching courses</strong>
<span>Try a different search phrase.</span>
</div>
</section>
</main>
<footer>
<span>Private library generated from your authorized LMS access.</span>
<span id="generatedAt"></span>
</footer>
</body>
</html>
-408
View File
@@ -1,408 +0,0 @@
:root {
color-scheme: light;
--ink: #172126;
--muted: #617077;
--paper: #f5f3ec;
--surface: #fffdf8;
--surface-strong: #ffffff;
--line: #dcded8;
--accent: #d8f26a;
--accent-strong: #93ad20;
--blue: #1c5166;
--blue-soft: #dbeaf0;
--danger: #b64d3c;
--shadow: 0 18px 55px rgba(37, 48, 52, .09);
--radius: 22px;
}
:root[data-theme="dark"] {
color-scheme: dark;
--ink: #f2f4ec;
--muted: #aab6b8;
--paper: #101719;
--surface: #172124;
--surface-strong: #1d292d;
--line: #304044;
--accent: #d8f26a;
--accent-strong: #bfd94f;
--blue: #8fc5d6;
--blue-soft: #223a42;
--danger: #f28f7d;
--shadow: 0 18px 55px rgba(0, 0, 0, .24);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
min-height: 100vh;
color: var(--ink);
background:
radial-gradient(circle at 87% 7%, color-mix(in srgb, var(--accent) 22%, transparent), transparent 26rem),
var(--paper);
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Tahoma, Arial, sans-serif;
line-height: 1.5;
}
button, input { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
a { color: inherit; }
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.topbar {
max-width: 1240px;
margin: 0 auto;
padding: 24px 28px;
display: flex;
align-items: center;
justify-content: space-between;
}
.brand {
display: inline-flex;
gap: 12px;
align-items: center;
color: var(--ink);
font-weight: 750;
text-decoration: none;
letter-spacing: -.02em;
}
.brand-mark {
display: grid;
place-items: center;
width: 36px;
height: 36px;
border-radius: 12px;
color: #142024;
background: var(--accent);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .08);
}
.icon-button {
width: 42px;
height: 42px;
border: 1px solid var(--line);
border-radius: 14px;
color: var(--ink);
background: var(--surface);
cursor: pointer;
transition: transform .18s ease, border-color .18s ease;
}
.icon-button:hover { transform: translateY(-2px); border-color: var(--accent-strong); }
.icon-button:focus-visible, .filter-chip:focus-visible, .action-button:focus-visible, input:focus-visible, .complete-check:focus-visible { outline: 3px solid color-mix(in srgb, var(--blue) 35%, transparent); outline-offset: 2px; }
main {
width: min(1184px, calc(100% - 40px));
margin: 0 auto;
}
.hero, .course-hero {
position: relative;
overflow: hidden;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 48px;
align-items: center;
min-height: 330px;
margin-top: 24px;
padding: clamp(34px, 6vw, 72px);
border-radius: 34px;
color: #f7fbf8;
background: #163b49;
box-shadow: var(--shadow);
}
.hero::after, .course-hero::after {
content: "";
position: absolute;
width: 260px;
height: 260px;
right: -65px;
bottom: -120px;
border: 42px solid rgba(216, 242, 106, .16);
border-radius: 50%;
}
.hero h1, .course-hero h1 {
max-width: 760px;
margin: 7px 0 16px;
font-size: clamp(2.5rem, 6vw, 5.2rem);
line-height: .98;
letter-spacing: -.065em;
}
.course-hero h1 { font-size: clamp(2.15rem, 5vw, 4.2rem); }
.eyebrow {
margin: 0;
color: var(--accent-strong);
font-size: .75rem;
font-weight: 850;
letter-spacing: .16em;
text-transform: uppercase;
}
.hero .eyebrow, .course-hero .eyebrow { color: var(--accent); }
.hero-copy {
max-width: 650px;
margin: 0;
color: rgba(247, 251, 248, .72);
font-size: clamp(1rem, 2vw, 1.18rem);
}
.hero-source {
display: inline-flex;
margin-top: 22px;
color: var(--accent);
font-size: .86rem;
font-weight: 800;
text-decoration: none;
}
.hero-orbit {
position: relative;
z-index: 1;
display: grid;
place-items: center;
align-content: center;
width: 190px;
aspect-ratio: 1;
border: 1px solid rgba(255, 255, 255, .2);
border-radius: 50%;
background: rgba(255, 255, 255, .06);
backdrop-filter: blur(12px);
}
.orbit-number { font-size: 3.2rem; font-weight: 800; letter-spacing: -.06em; }
.orbit-label { max-width: 100px; color: rgba(255,255,255,.65); font-size: .75rem; text-align: center; }
.stat-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 14px;
margin: 16px 0 76px;
}
.stat-card {
min-height: 118px;
padding: 24px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
}
.stat-label { display: block; color: var(--muted); font-size: .82rem; }
.stat-card strong { display: block; margin-top: 8px; font-size: 1.8rem; letter-spacing: -.04em; }
.library-section { margin-bottom: 70px; }
.section-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 24px;
margin-bottom: 26px;
}
.section-heading h2 { margin: 5px 0 0; font-size: clamp(1.8rem, 4vw, 3rem); letter-spacing: -.045em; }
.search-box {
display: flex;
align-items: center;
gap: 10px;
min-width: min(330px, 100%);
padding: 0 15px;
border: 1px solid var(--line);
border-radius: 15px;
color: var(--muted);
background: var(--surface);
}
.search-box input {
width: 100%;
padding: 13px 0;
border: 0;
outline: 0;
color: var(--ink);
background: transparent;
}
.course-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
.course-card {
display: flex;
flex-direction: column;
min-height: 300px;
padding: 26px;
border: 1px solid var(--line);
border-radius: 26px;
background: var(--surface);
box-shadow: 0 6px 24px rgba(37,48,52,.04);
transition: transform .2s ease, box-shadow .2s ease;
}
.course-card:hover { transform: translateY(-4px); box-shadow: var(--shadow); }
.course-card-top { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.course-code { color: var(--muted); font-size: .75rem; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
.course-badge { padding: 5px 9px; border-radius: 999px; color: var(--blue); background: var(--blue-soft); font-size: .72rem; font-weight: 750; }
.course-card h3 { margin: 36px 0 10px; font-size: 1.4rem; line-height: 1.28; letter-spacing: -.025em; }
.course-card-meta { margin: 0; color: var(--muted); font-size: .85rem; }
.course-card-bottom { margin-top: auto; }
.progress-track { height: 7px; margin: 28px 0 12px; overflow: hidden; border-radius: 99px; background: var(--line); }
.progress-track span { display: block; width: var(--progress); height: 100%; border-radius: inherit; background: var(--accent-strong); }
.progress-copy { display: flex; justify-content: space-between; color: var(--muted); font-size: .78rem; }
.course-link { display: inline-flex; align-items: center; gap: 8px; margin-top: 22px; color: var(--ink); font-weight: 800; text-decoration: none; }
.course-link span { transition: transform .18s ease; }
.course-link:hover span { transform: translateX(4px); }
.breadcrumbs { display: flex; gap: 9px; margin: 24px 4px 14px; color: var(--muted); font-size: .85rem; }
.breadcrumbs a { text-decoration: none; }
.course-hero { min-height: 300px; margin-top: 0; }
.course-heading { position: relative; z-index: 1; }
.progress-panel { position: relative; z-index: 1; display: flex; align-items: center; gap: 18px; min-width: 250px; }
.progress-panel > div:last-child { display: grid; }
.progress-panel span { color: rgba(255,255,255,.62); font-size: .78rem; }
.progress-ring {
display: grid;
place-items: center;
width: 100px;
aspect-ratio: 1;
border-radius: 50%;
background: radial-gradient(circle closest-side, #163b49 78%, transparent 80% 100%), conic-gradient(var(--accent) calc(var(--progress) * 1%), rgba(255,255,255,.14) 0);
}
.progress-ring span { color: #fff; font-size: 1.25rem; font-weight: 850; }
.course-toolbar {
position: sticky;
top: 12px;
z-index: 5;
display: flex;
justify-content: space-between;
gap: 18px;
margin: 22px 0 34px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 20px;
background: color-mix(in srgb, var(--paper) 84%, transparent);
backdrop-filter: blur(18px);
}
.resource-search { flex: 1; max-width: 420px; }
.filter-group { display: flex; gap: 7px; overflow-x: auto; }
.filter-chip { padding: 10px 14px; border: 1px solid var(--line); border-radius: 12px; color: var(--muted); background: var(--surface); cursor: pointer; white-space: nowrap; }
.filter-chip.active { border-color: var(--ink); color: var(--paper); background: var(--ink); }
.section-list { display: grid; gap: 30px; margin-bottom: 70px; }
.resource-section { overflow: hidden; border: 1px solid var(--line); border-radius: 24px; background: var(--surface); }
.resource-section-header { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 7px 16px; padding: 22px 24px; border-bottom: 1px solid var(--line); }
.resource-section-header h2 { margin: 0; font-size: 1.12rem; }
.resource-section-header span { color: var(--muted); font-size: .8rem; }
.section-summary { grid-column: 1 / -1; max-width: 850px; margin: 0; color: var(--muted); font-size: .82rem; }
.resource-list { display: grid; }
.resource-row {
display: grid;
grid-template-columns: 38px minmax(0, 1fr) auto auto auto;
gap: 16px;
align-items: center;
min-height: 88px;
padding: 14px 22px;
border-bottom: 1px solid var(--line);
}
.resource-row:last-child { border-bottom: 0; }
.resource-row:hover { background: color-mix(in srgb, var(--blue-soft) 34%, transparent); }
.resource-index { color: var(--muted); font-size: .75rem; font-variant-numeric: tabular-nums; }
.resource-main { min-width: 0; }
.resource-title { display: block; overflow: hidden; font-weight: 730; text-overflow: ellipsis; white-space: nowrap; }
.resource-file { display: block; overflow: hidden; margin-top: 4px; color: var(--muted); font-size: .78rem; text-overflow: ellipsis; white-space: nowrap; }
.resource-description { display: -webkit-box; overflow: hidden; margin-top: 5px; color: var(--muted); font-size: .76rem; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
.artifact-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 9px; }
.artifact-button { padding: 5px 9px; border: 1px solid color-mix(in srgb, var(--blue) 24%, var(--line)); border-radius: 8px; color: var(--blue); background: var(--blue-soft); cursor: pointer; font-size: .7rem; font-weight: 750; }
.artifact-button:hover { border-color: var(--blue); }
.resource-meta { display: flex; gap: 8px; align-items: center; color: var(--muted); font-size: .74rem; white-space: nowrap; }
.type-pill { padding: 4px 8px; border-radius: 8px; color: var(--blue); background: var(--blue-soft); font-weight: 750; }
.status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-strong); }
.status-dot.missing { background: var(--danger); }
.status-dot.online { background: var(--blue); }
.action-button { min-width: 70px; padding: 9px 12px; border: 1px solid var(--line); border-radius: 11px; color: var(--ink); background: var(--surface-strong); cursor: pointer; font-weight: 750; text-align: center; text-decoration: none; }
.action-button[aria-disabled="true"] { color: var(--muted); cursor: not-allowed; opacity: .6; }
.complete-check { width: 20px; height: 20px; accent-color: var(--accent-strong); cursor: pointer; }
.resource-row.completed .resource-title { color: var(--muted); text-decoration: line-through; }
.empty-state { padding: 60px 24px; border: 1px dashed var(--line); border-radius: var(--radius); color: var(--muted); text-align: center; }
.empty-state strong, .empty-state span { display: block; }
.empty-state strong { color: var(--ink); font-size: 1.1rem; }
.media-dialog { width: min(1000px, calc(100% - 30px)); padding: 20px; border: 1px solid var(--line); border-radius: 24px; color: var(--ink); background: var(--surface); box-shadow: 0 30px 100px rgba(0,0,0,.4); }
.media-dialog::backdrop { background: rgba(8, 15, 17, .76); backdrop-filter: blur(7px); }
.dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 16px; }
.dialog-heading h2 { margin: 4px 0 0; font-size: 1.2rem; }
.media-dialog video { display: block; width: 100%; max-height: 72vh; border-radius: 15px; background: #000; }
.artifact-dialog { width: min(920px, calc(100% - 30px)); max-height: min(88vh, 1000px); padding: 22px; border: 1px solid var(--line); border-radius: 24px; color: var(--ink); background: var(--surface); box-shadow: 0 30px 100px rgba(0,0,0,.4); }
.artifact-dialog::backdrop { background: rgba(8, 15, 17, .76); backdrop-filter: blur(7px); }
.artifact-content { overflow: auto; max-height: calc(88vh - 105px); padding: 4px 10px 24px; line-height: 1.85; }
.artifact-content h1, .artifact-content h2, .artifact-content h3, .artifact-content h4 { margin: 1.5em 0 .55em; line-height: 1.35; }
.artifact-content h1:first-child, .artifact-content h2:first-child { margin-top: .4em; }
.artifact-content p, .artifact-content li { font-size: .94rem; }
.artifact-content blockquote { margin: 1em 0; padding: 10px 16px; border-inline-start: 4px solid var(--blue); color: var(--muted); background: var(--blue-soft); }
.artifact-content code { padding: 2px 5px; border-radius: 5px; background: var(--paper); font-size: .88em; }
.artifact-content table { width: 100%; margin: 18px 0; border-collapse: collapse; font-size: .86rem; }
.artifact-content th, .artifact-content td { padding: 9px 11px; border: 1px solid var(--line); text-align: start; vertical-align: top; }
.artifact-content th { background: var(--surface-strong); }
.transcript-text { margin: 0; font: inherit; line-height: 2; white-space: pre-wrap; word-break: break-word; }
.artifact-loading { color: var(--muted); }
footer { width: min(1184px, calc(100% - 40px)); margin: 0 auto; padding: 28px 0 40px; display: flex; justify-content: space-between; gap: 20px; border-top: 1px solid var(--line); color: var(--muted); font-size: .78rem; }
footer a { text-decoration: none; font-weight: 700; }
@media (max-width: 900px) {
.hero, .course-hero { grid-template-columns: 1fr; gap: 28px; }
.hero-orbit { width: 145px; }
.stat-grid, .course-grid { grid-template-columns: repeat(2, 1fr); }
.course-toolbar { position: static; flex-direction: column; }
.resource-search { max-width: none; }
.resource-row { grid-template-columns: 30px minmax(0, 1fr) auto auto; }
.resource-meta { display: none; }
}
@media (max-width: 600px) {
.topbar { padding: 18px 20px; }
main { width: min(100% - 24px, 1184px); }
.hero, .course-hero { min-height: auto; padding: 34px 24px; border-radius: 24px; }
.hero h1, .course-hero h1 { letter-spacing: -.045em; }
.stat-grid { grid-template-columns: repeat(2, 1fr); margin-bottom: 54px; }
.stat-card { min-height: 100px; padding: 18px; }
.section-heading { align-items: stretch; flex-direction: column; }
.course-grid { grid-template-columns: 1fr; }
.progress-panel { min-width: 0; }
.course-toolbar { border-radius: 17px; }
.resource-row { grid-template-columns: 24px minmax(0, 1fr) auto; gap: 10px; padding: 13px 14px; }
.complete-check { display: none; }
.action-button { min-width: 58px; }
footer { width: calc(100% - 28px); flex-direction: column; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; transition: none !important; }
}
+10 -167
View File
@@ -1,24 +1,19 @@
"""Build, write, and refresh the static course catalog."""
import hashlib
import html
import json
import mimetypes
import os
import re
import sys
import urllib.parse
from datetime import datetime, timezone
from importlib import resources
from pathlib import Path
from typing import Any, Iterable
from .client import MoodleClient
from .constants import LIBRARY_ASSETS
from .models import FileItem, MoodleError
from .paths import (
_activity_directory_name, _activity_root, _clean_name, _course_content_root,
_discover_artifacts, _read_json_object, _relative_browser_path,
_discover_artifacts, _relative_browser_path,
)
@@ -81,10 +76,15 @@ def _local_activity_record(
fallback=f"{course_id}\0{activity.get('url', '')}\0{activity.get('name', '')}",
)
directory = _course_content_root(library, course_id) / key
metadata = _read_json_object(directory / "item.json")
if not metadata:
files_directory = directory / "files"
files = [
path.relative_to(directory).as_posix()
for path in sorted(files_directory.iterdir())
if path.is_file() and not path.name.endswith(".part")
] if files_directory.is_dir() else []
if not files and not (directory / "artifacts").is_dir():
return None
return metadata, directory
return {"files": files}, directory
def _build_library_catalog(
@@ -154,6 +154,7 @@ def _build_library_catalog(
"extension": Path(item.filename).suffix.removeprefix(".").casefold(),
"kind": _resource_kind(item),
"mimetype": item.mimetype,
"remote_size": item.filesize,
"status": status,
"size": local_bytes if status == "downloaded" else item.filesize,
"local_bytes": local_bytes,
@@ -315,161 +316,3 @@ def _build_library_catalog(
},
"courses": catalog_courses,
}
def _write_library_site(library: Path, catalog: dict[str, Any]) -> Path:
library.mkdir(parents=True, exist_ok=True)
legacy_media_link = library / "media"
if legacy_media_link.is_symlink():
legacy_media_link.unlink()
elif legacy_media_link.exists():
raise MoodleError(f"{legacy_media_link} is not a symlink; move it aside before rebuilding")
asset_root = resources.files("ravin.assets")
for name in LIBRARY_ASSETS:
(library / name).write_bytes(asset_root.joinpath(name).read_bytes())
catalog_path = library / "courses.json"
catalog_path.write_text(
json.dumps(catalog, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
for course in catalog.get("courses", []):
course_id = int(course.get("id") or 0)
course_root = library / "courses" / str(course_id)
course_root.mkdir(parents=True, exist_ok=True)
(course_root / "course.json").write_text(
json.dumps(course, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
quoted_root = json.dumps(str(library.resolve()))
(library / "nginx-server.conf").write_text(
f"""# Generated by ravin. Include this file inside nginx's http block.
server {{
listen 127.0.0.1:8765;
server_name localhost;
root {quoted_root};
index index.html;
charset utf-8;
autoindex off;
location = / {{
try_files /index.html =404;
}}
location = /courses.json {{
try_files $uri =404;
default_type application/json;
add_header Cache-Control "no-store" always;
}}
location /courses/ {{
try_files $uri =404;
sendfile on;
tcp_nopush on;
add_header Accept-Ranges bytes always;
add_header X-Content-Type-Options nosniff always;
}}
location / {{
try_files $uri $uri/ =404;
}}
location ~ (^|/)\\. {{ return 404; }}
location ~ \\.part$ {{ return 404; }}
}}
""",
encoding="utf-8",
)
return catalog_path
def _reuse_library_catalog(library: Path) -> dict[str, Any]:
catalog_path = library / "courses.json"
if not catalog_path.is_file():
raise MoodleError(f"{catalog_path} does not exist; build the library online first")
try:
catalog = json.loads(catalog_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise MoodleError(f"could not read the existing course catalog: {exc}") from exc
catalog["schema_version"] = 3
total_files = 0
total_records = 0
total_downloaded = 0
total_downloaded_bytes = 0
for course in catalog.get("courses", []):
course_id = int(course.get("id") or 0)
course_file_count = 0
course_downloaded = 0
course_downloaded_bytes = 0
for section in course.get("sections", []):
for item in section.get("items", []):
item["title"] = html.unescape(str(item.get("title") or ""))
item["description"] = html.unescape(str(item.get("description") or ""))
key = _activity_directory_name(
item.get("section_number", section.get("number")),
item.get("activity_position"),
item.get("activity_id"),
fallback=f"{course_id}\0{item.get('source_url', '')}\0{item.get('title', '')}",
)
activity_directory = _course_content_root(library, course_id) / key
metadata = _read_json_object(activity_directory / "item.json")
local_files = [
activity_directory / str(relative)
for relative in metadata.get("files", [])
if (activity_directory / str(relative)).is_file()
]
filename = str(item.get("filename") or "")
if filename:
course_file_count += 1
if not local_files and filename:
expected = activity_directory / "files" / filename
if expected.is_file():
local_files = [expected]
local_path = next((path for path in local_files if not filename or path.name == filename), None)
local_path = local_path or (local_files[0] if local_files else None)
if local_path:
local_bytes = local_path.stat().st_size
if not filename:
course_file_count += 1
item.update(
{
"filename": local_path.name,
"extension": local_path.suffix.removeprefix(".").casefold(),
"status": "downloaded",
"size": local_bytes,
"local_bytes": local_bytes,
"local_url": _relative_browser_path(local_path, library),
"artifacts": _discover_artifacts(activity_directory, library),
}
)
if item.get("activity_type") == "quiz":
item["kind"] = "assessment"
course_downloaded += 1
course_downloaded_bytes += local_bytes
elif item.get("status") == "downloaded":
item.update({"status": "missing", "local_bytes": 0, "local_url": None, "artifacts": {}})
course["file_count"] = course_file_count
course["downloaded_count"] = course_downloaded
course["downloaded_bytes"] = course_downloaded_bytes
course_records = [item for section in course.get("sections", []) for item in section.get("items", [])]
type_counts: dict[str, int] = {}
for item in course_records:
kind = str(item.get("kind") or "activity")
type_counts[kind] = type_counts.get(kind, 0) + 1
course["record_count"] = len(course_records)
course["type_counts"] = type_counts
total_files += course_file_count
total_records += len(course_records)
total_downloaded += course_downloaded
total_downloaded_bytes += course_downloaded_bytes
stats = catalog.setdefault("stats", {})
stats.update(
{
"files": total_files,
"records": total_records,
"downloaded_files": total_downloaded,
"downloaded_bytes": total_downloaded_bytes,
}
)
catalog["prepared_at"] = datetime.now(timezone.utc).isoformat()
return catalog
+81 -137
View File
@@ -1,10 +1,10 @@
"""Command-line parser and application entry point."""
"""Command-line parser and application orchestration."""
from __future__ import annotations
import argparse
import json
import re
import sys
from dataclasses import asdict
from pathlib import Path
from .auth import (
@@ -16,50 +16,31 @@ from .auth import (
)
from .client import MoodleClient
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
from .library import (
_build_library_catalog,
_format_size,
_migrate_legacy_downloads,
_reuse_library_catalog,
_serve_library,
_write_library_site,
)
from .migration import migrate_library_to_public
from .models import MoodleError
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
from .server import _serve_library
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.")
parser = argparse.ArgumentParser(description="Scan and download your Ravin Academy Moodle courses.")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})")
parser.add_argument(
"--login-url",
help=(
"account portal used for browser login; defaults to "
f"{DEFAULT_RAVIN_LOGIN_URL} for Ravin Academy"
),
help=f"account portal used for browser login; defaults to {DEFAULT_RAVIN_LOGIN_URL} for Ravin Academy",
)
parser.add_argument("--username", help="LMS username; password is prompted securely")
parser.add_argument("--web-only", action="store_true", help="skip the Moodle mobile API and use a normal web session")
parser.add_argument(
"--browser-session",
action="store_true",
help="force saved or automatic browser-session authentication",
)
parser.add_argument(
"--browser-user-agent",
help="User-Agent copied from the logged-in browser; otherwise prompted",
)
parser.add_argument("--web-only", action="store_true", help="skip the Moodle mobile API and use a web session")
parser.add_argument("--browser-session", action="store_true", help="force browser-session authentication")
parser.add_argument("--browser-user-agent", help="User-Agent copied from the logged-in browser")
parser.add_argument(
"--env-file",
type=Path,
default=DEFAULT_ENV_FILE,
help=f"credentials and browser-session file (default: {DEFAULT_ENV_FILE})",
)
parser.add_argument(
"--refresh-session",
action="store_true",
help="ignore the saved browser session and open the authentication browser",
)
parser.add_argument("--refresh-session", action="store_true", help="refresh the saved browser session")
parser.add_argument(
"--manual-session",
action="store_true",
@@ -71,152 +52,115 @@ def build_parser() -> argparse.ArgumentParser:
default=Path.cwd() / ".ravin-browser-profile",
help="persistent profile for automatic browser login",
)
parser.add_argument(
"--browser-executable",
type=Path,
help="installed Zen, Firefox, Chrome, Chromium, or Brave executable",
)
parser.add_argument(
"--login-timeout",
type=int,
default=600,
help="seconds to wait for interactive browser login (default: 600)",
)
parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
parser.add_argument("--browser-executable", type=Path, help="installed browser executable")
parser.add_argument("--login-timeout", type=int, default=600, help="interactive login timeout")
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("login", help="open a browser and refresh the saved LMS session")
subparsers.add_parser("courses", help="list enrolled courses")
files_parser = subparsers.add_parser("files", help="list downloadable files in a course")
files_parser.add_argument("course_id", type=int)
download_parser = subparsers.add_parser("download", help="download files from one course")
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")
scan_parser.add_argument("--offline", action="store_true", help="verify existing manifests without contacting LMS")
scan_parser.add_argument("--json", action="store_true", help="print machine-readable scan results")
download_parser = subparsers.add_parser("download", help="scan and download files from one course")
download_parser.add_argument("course_id", type=int)
download_parser.add_argument("--output", type=Path, default=Path("library"), help="library root (default: library)")
download_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
download_parser.add_argument("--overwrite", action="store_true")
download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)")
library_parser = subparsers.add_parser(
"library",
help="generate a private static course library and courses.json",
)
library_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all courses")
library_parser.add_argument("--output", type=Path, default=Path("library"), help="generated site directory")
library_parser.add_argument(
"--reuse-catalog",
action="store_true",
help="refresh local files and pages without contacting the LMS",
)
migrate_parser = subparsers.add_parser("migrate-library", help="move legacy downloads into the library layout")
migrate_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all catalog courses")
migrate_parser.add_argument("--source", type=Path, default=Path("downloads"), help="legacy download root")
migrate_parser.add_argument("--library", type=Path, default=Path("library"), help="library root")
serve_parser = subparsers.add_parser("serve-library", help="serve the generated library locally")
serve_parser.add_argument("--site-dir", type=Path, default=Path("library"), help="generated site directory")
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address (default: 127.0.0.1)")
serve_parser.add_argument("--port", type=int, default=8765, help="local port (default: 8765)")
download_parser.add_argument("--json", action="store_true", help="print downloaded paths as JSON")
serve_parser = subparsers.add_parser("serve", help="serve the public learning library locally")
serve_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address")
serve_parser.add_argument("--port", type=int, default=8765, help="local port")
serve_parser.add_argument("--open", action="store_true", help="open the library in your default browser")
return parser
def _maybe_migrate(public: Path) -> None:
if any((public / "courses").glob("*/manifest.json")):
return
legacy = Path("library").resolve()
if (legacy / "courses.json").is_file():
print("Migrating the previous library layout...", file=sys.stderr)
migrate_library_to_public(legacy, public)
def _authenticate(args: argparse.Namespace) -> tuple[MoodleClient, str]:
args.env_values = _load_env_file(args.env_file)
saved_session = _browser_session_values(args, fresh=args.refresh_session)
if args.browser_session or args.refresh_session or saved_session is not None:
return _authenticate_browser_session(args, saved_session)
username, password = _credentials(args)
_save_env_values(
args.env_file,
{ENV_KEYS["username"]: username, ENV_KEYS["password"]: password},
)
args.env_values.update({ENV_KEYS["username"]: username, ENV_KEYS["password"]: password})
client = MoodleClient(args.site, username, password, web_only=args.web_only)
try:
mode = client.authenticate()
except MoodleError as exc:
if "cloudflare requires a real browser session" not in str(exc).casefold():
raise
print("Cloudflare blocked password login; opening the authentication browser.", file=sys.stderr)
return _authenticate_browser_session(args)
return client, mode
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
try:
if args.command == "serve-library":
_serve_library(args.site_dir, args.host, args.port, args.open)
if args.command == "serve":
_serve_library(args.public, args.host, args.port, args.open)
return 0
if args.command == "migrate-library":
source = args.source.expanduser().resolve()
library = args.library.expanduser().resolve()
result = _migrate_legacy_downloads(source, library, args.course_ids)
catalog = _reuse_library_catalog(library)
catalog_path = _write_library_site(library, catalog)
moved = sum(int(course.get("moved_files") or 0) for course in result.get("courses", []))
print(f"Migrated {moved} files and refreshed {catalog_path}.")
return 0
if args.command == "library" and args.reuse_catalog:
output = args.output.expanduser().resolve()
catalog = _reuse_library_catalog(output)
catalog_path = _write_library_site(output, catalog)
print(f"Prepared {catalog_path}, static pages, and Nginx configuration from existing data.")
public = getattr(args, "public", Path("public")).expanduser().resolve()
if args.command in {"scan", "download"}:
_maybe_migrate(public)
if args.command == "scan" and args.offline:
catalog = scan_offline(public, args.course_ids)
print(json.dumps(scan_output(catalog), ensure_ascii=False, indent=2) if args.json else format_scan(catalog))
return 0
args.env_values = _load_env_file(args.env_file)
if args.command == "login":
client, mode = _authenticate_browser_session(args)
_client, mode = _authenticate_browser_session(args)
print(f"Authenticated using {mode}; updated {args.env_file}.")
return 0
saved_session = _browser_session_values(args, fresh=args.refresh_session)
if args.browser_session or args.refresh_session or saved_session is not None:
client, mode = _authenticate_browser_session(args, saved_session)
else:
username, password = _credentials(args)
_save_env_values(
args.env_file,
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
},
)
args.env_values.update(
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
}
)
client = MoodleClient(args.site, username, password, web_only=args.web_only)
try:
mode = client.authenticate()
except MoodleError as exc:
if "cloudflare requires a real browser session" not in str(exc).casefold():
raise
print("Cloudflare blocked password login; opening the authentication browser.", file=sys.stderr)
client, mode = _authenticate_browser_session(args)
client, mode = _authenticate(args)
print(f"Authenticated using {mode}.", file=sys.stderr)
if args.command == "courses":
courses = client.list_courses()
if args.json:
print(json.dumps([asdict(course) for course in courses], ensure_ascii=False, indent=2))
else:
for course in courses:
suffix = f" [{course.shortname}]" if course.shortname else ""
print(f"{course.id:>6} {course.fullname}{suffix}")
return 0
if args.command == "library":
output = args.output.expanduser().resolve()
catalog = _build_library_catalog(client, output, args.course_ids)
catalog_path = _write_library_site(output, catalog)
print(f"Generated {catalog_path} and the static library pages.")
print("View it with: ravin serve-library --open")
if args.command == "scan":
catalog = scan_remote(client, public, args.course_ids)
print(json.dumps(scan_output(catalog), ensure_ascii=False, indent=2) if args.json else format_scan(catalog))
return 0
scan_remote(client, public, [args.course_id])
files = client.list_files(args.course_id)
if args.command == "files":
if args.json:
print(json.dumps([asdict(item) for item in files], ensure_ascii=False, indent=2))
else:
for number, item in enumerate(files, 1):
print(f"{number:>3}. {_format_size(item.filesize):>10} {item.section} / {item.activity} / {item.filename}")
return 0
if not files:
print("No downloadable files were found.")
return 0
downloaded: list[str] = []
for number, item in enumerate(files, 1):
print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr)
library = args.output.expanduser().resolve()
path = client.download(
item,
library,
public,
overwrite=args.overwrite,
retries=max(args.retries, 0),
)
update_download_state(public, item, path)
downloaded.append(str(path))
scan_offline(public, [args.course_id])
if args.json:
print(json.dumps(downloaded, ensure_ascii=False, indent=2))
else:
print(f"Downloaded {len(downloaded)} file(s) to {args.output.resolve()}")
print(f"Downloaded {len(downloaded)} file(s) into {public / 'courses' / str(args.course_id)}")
return 0
except (MoodleError, KeyboardInterrupt) as exc:
if isinstance(exc, KeyboardInterrupt):
-4
View File
@@ -22,7 +22,6 @@ from .paths import (
_filename_from_headers,
_is_cloudflare_challenge,
_unique,
_write_item_metadata,
)
@@ -461,7 +460,6 @@ class MoodleClient:
suggested_filename = _clean_name(item.filename, activity)
destination = directory / suggested_filename
if destination.exists() and not overwrite:
_write_item_metadata(item, activity_directory, destination)
return destination
temporary = destination.with_name(destination.name + ".part")
if overwrite:
@@ -482,7 +480,6 @@ class MoodleClient:
if not temporary.exists() and response_filename != suggested_filename:
destination = directory / response_filename
if destination.exists() and not overwrite:
_write_item_metadata(item, activity_directory, destination)
return destination
temporary = destination.with_name(destination.name + ".part")
resume_at = temporary.stat().st_size if temporary.exists() else 0
@@ -542,7 +539,6 @@ class MoodleClient:
f"connection closed early at {downloaded} of {expected_total} bytes"
)
temporary.replace(destination)
_write_item_metadata(item, activity_directory, destination)
if sys.stderr.isatty():
elapsed = max(time.monotonic() - started, 0.01)
rate = downloaded / 1024 / 1024 / elapsed
+1 -3
View File
@@ -5,7 +5,7 @@ from pathlib import Path
DEFAULT_SITE = "https://training.ravinacademy.com"
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
__version__ = "0.5.0"
__version__ = "0.6.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
DEFAULT_ENV_FILE = Path.cwd() / ".env"
@@ -16,5 +16,3 @@ ENV_KEYS = {
"user_agent": "RAVIN_USER_AGENT",
"cookie": "RAVIN_COOKIE",
}
LIBRARY_ASSETS = ("index.html", "course.html", "styles.css", "app.js")
CONTENT_SCHEMA_VERSION = 1
+10 -11
View File
@@ -1,19 +1,18 @@
"""Compatibility facade for the static library subsystems."""
"""Public facade for scanning and serving the learning library."""
from .catalog import (
_build_library_catalog,
_format_size,
_reuse_library_catalog,
_write_library_site,
)
from .migration import _migrate_legacy_downloads
from .catalog import _build_library_catalog, _format_size
from .migration import migrate_library_to_public
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
from .server import _serve_library
__all__ = [
"_build_library_catalog",
"_format_size",
"_migrate_legacy_downloads",
"_reuse_library_catalog",
"_serve_library",
"_write_library_site",
"format_scan",
"migrate_library_to_public",
"scan_offline",
"scan_output",
"scan_remote",
"update_download_state",
]
+48 -204
View File
@@ -1,218 +1,62 @@
"""Migrate legacy course files into ordered activity bundles."""
"""One-time migration from the generated ``library/`` layout to ``public/``."""
from __future__ import annotations
import json
import mimetypes
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
from typing import Any
from .constants import CONTENT_SCHEMA_VERSION
from .models import FileItem, MoodleError
from .paths import _activity_root, _course_content_root, _read_json_object, _write_item_metadata
from .models import MoodleError
from .paths import _read_json_object
def _move_migration_file(source: Path, destination: Path, moved: list[dict[str, str]], source_root: Path, library: Path) -> None:
if not source.is_file():
if destination.is_file():
return
raise MoodleError(f"migration source is missing: {source}")
if destination.exists():
raise MoodleError(f"migration target already exists: {destination}")
destination.parent.mkdir(parents=True, exist_ok=True)
source.replace(destination)
moved.append(
{
"from": source.relative_to(source_root).as_posix(),
"to": destination.relative_to(library).as_posix(),
}
)
def _normalize_transcript_metadata(path: Path, source_filename: str) -> None:
metadata = _read_json_object(path)
if not metadata:
return
metadata["schema_version"] = CONTENT_SCHEMA_VERSION
metadata["source"] = f"../files/{source_filename}"
metadata["transcript"] = "transcript.fa.txt"
if "transcribed_at" in metadata and "generated_at" not in metadata:
metadata["generated_at"] = metadata.pop("transcribed_at")
path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def _normalize_summary_source(path: Path) -> None:
try:
content = path.read_text(encoding="utf-8")
except OSError:
return
updated = re.sub(r"(?m)^\*\*منبع:\*\*.*$", "**منبع:** transcript.fa.txt", content)
if updated != content:
path.write_text(updated, encoding="utf-8")
def _finalize_item_metadata(activity_directory: Path) -> None:
path = activity_directory / "item.json"
metadata = _read_json_object(path)
artifact_names = {
"transcript": "transcript.fa.txt",
"transcript_metadata": "transcript.meta.json",
"summary": "summary.fa.md",
"questions": "questions.fa.md",
}
artifacts = {
kind: f"artifacts/{filename}"
for kind, filename in artifact_names.items()
if (activity_directory / "artifacts" / filename).is_file()
}
metadata["artifacts"] = artifacts
path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def _record_file_item(course_id: int, section: dict[str, Any], record: dict[str, Any], filename: str) -> FileItem:
return FileItem(
course_id=course_id,
section=str(section.get("name") or "Course"),
activity=str(record.get("title") or filename),
filename=filename,
url=str(record.get("source_url") or ""),
mimetype=str(record.get("mimetype") or mimetypes.guess_type(filename)[0] or ""),
filesize=record.get("size"),
chapter=str(section.get("name") or "Course"),
section_id=record.get("section_id", section.get("id")),
section_number=record.get("section_number", section.get("number")),
activity_id=record.get("activity_id"),
activity_type=str(record.get("activity_type") or "resource"),
activity_position=record.get("activity_position"),
description=str(record.get("description") or ""),
)
def _migrate_legacy_downloads(source_root: Path, library: Path, selected_course_ids: Iterable[int] = ()) -> dict[str, Any]:
"""Move the old flat download layout into ordered activity bundles."""
catalog_path = library / "courses.json"
if not catalog_path.is_file():
raise MoodleError(f"{catalog_path} is required to map legacy files to LMS activities")
def migrate_library_to_public(legacy: Path, public: Path) -> dict[str, Any]:
"""Move private course bundles and create manifests before removing legacy metadata."""
catalog_path = legacy / "courses.json"
catalog = _read_json_object(catalog_path)
selected = set(selected_course_ids)
courses = [
course
for course in catalog.get("courses", [])
if not selected or int(course.get("id") or 0) in selected
]
if selected - {int(course.get("id") or 0) for course in courses}:
missing = ", ".join(str(value) for value in sorted(selected - {int(course.get("id") or 0) for course in courses}))
raise MoodleError(f"course ID(s) are missing from {catalog_path}: {missing}")
courses = catalog.get("courses")
if not isinstance(courses, list) or not courses:
raise MoodleError(f"legacy course catalog not found: {catalog_path}")
migration: dict[str, Any] = {
"schema_version": CONTENT_SCHEMA_VERSION,
"migrated_at": datetime.now(timezone.utc).isoformat(),
"courses": [],
}
moved: list[dict[str, Any]] = []
for course in courses:
course_id = int(course.get("id") or 0)
legacy_course = source_root / str(course_id)
if not legacy_course.is_dir():
continue
moved: list[dict[str, str]] = []
records: list[tuple[dict[str, Any], dict[str, Any]]] = [
(section, record)
for section in course.get("sections", [])
for record in section.get("items", [])
]
records_by_filename = {
str(record.get("filename")): (section, record)
for section, record in records
if record.get("filename")
}
files_directory = legacy_course / "Course files"
for filename, (section, record) in records_by_filename.items():
source_file = files_directory / filename
if not source_file.is_file():
continue
item = _record_file_item(course_id, section, record, filename)
activity_directory = _activity_root(library, item)
destination = activity_directory / "files" / filename
_move_migration_file(source_file, destination, moved, source_root, library)
_write_item_metadata(item, activity_directory, destination)
source_course = legacy / "courses" / str(course_id)
target_course = public / "courses" / str(course_id)
source_content = source_course / "content"
target_content = target_course / "content"
if target_content.exists():
raise MoodleError(f"migration target already exists: {target_content}")
if not source_content.is_dir():
raise MoodleError(f"legacy course content not found: {source_content}")
target_course.mkdir(parents=True, exist_ok=True)
source_content.replace(target_content)
migration_journal = source_course / "migration.json"
if migration_journal.is_file():
migration_journal.replace(target_course / "migration.json")
moved.append({"id": course_id, "content": target_content.as_posix()})
companions = (
(files_directory / f"{filename}.txt", activity_directory / "artifacts" / "transcript.fa.txt"),
(files_directory / f"{filename}.txt.json", activity_directory / "artifacts" / "transcript.meta.json"),
(files_directory / f"{filename}.md", activity_directory / "artifacts" / "summary.fa.md"),
)
for companion_source, companion_destination in companions:
if companion_source.is_file():
_move_migration_file(companion_source, companion_destination, moved, source_root, library)
metadata_path = activity_directory / "artifacts" / "transcript.meta.json"
if metadata_path.is_file():
_normalize_transcript_metadata(metadata_path, filename)
summary_path = activity_directory / "artifacts" / "summary.fa.md"
if summary_path.is_file():
_normalize_summary_source(summary_path)
_finalize_item_metadata(activity_directory)
from .scan import _write_manifests
quizzes = sorted(
((section, record) for section, record in records if record.get("activity_type") == "quiz"),
key=lambda value: (
int(value[1].get("section_number", value[0].get("number")) or 0),
int(value[1].get("activity_position") or 0),
),
)
exams_directory = legacy_course / "Course exams"
exam_pdfs = sorted(exams_directory.glob("*.pdf")) if exams_directory.is_dir() else []
if len(exam_pdfs) > len(quizzes):
raise MoodleError(f"course {course_id} has more local exams than LMS quiz activities")
for exam_index, exam_pdf in enumerate(exam_pdfs):
section, record = quizzes[exam_index]
item = _record_file_item(course_id, section, record, exam_pdf.name)
activity_directory = _activity_root(library, item)
destination = activity_directory / "files" / exam_pdf.name
_move_migration_file(exam_pdf, destination, moved, source_root, library)
_write_item_metadata(item, activity_directory, destination)
questions = exam_pdf.with_suffix(".md")
if questions.is_file():
_move_migration_file(
questions,
activity_directory / "artifacts" / "questions.fa.md",
moved,
source_root,
library,
)
_finalize_item_metadata(activity_directory)
course_root = library / "courses" / str(course_id)
course_root.mkdir(parents=True, exist_ok=True)
course_migration = {
"course_id": course_id,
"source_layout": "downloads/<course-id>/{Course files,Course exams}",
"target_layout": "library/courses/<course-id>/content/SECTION--POSITION--ACTIVITY",
"moved": moved,
}
(course_root / "migration.json").write_text(
json.dumps(course_migration, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
migration["courses"].append({"id": course_id, "moved_files": len(moved)})
remaining = [
path
for path in legacy_course.rglob("*")
if path.is_file() and path.name not in {".DS_Store", "files-map.txt"}
]
if remaining:
names = ", ".join(str(path.relative_to(legacy_course)) for path in remaining[:5])
raise MoodleError(f"migration left unclassified files in course {course_id}: {names}")
for disposable in legacy_course.rglob(".DS_Store"):
disposable.unlink(missing_ok=True)
(legacy_course / "files-map.txt").unlink(missing_ok=True)
for directory in sorted((path for path in legacy_course.rglob("*") if path.is_dir()), reverse=True):
try:
directory.rmdir()
except OSError:
pass
result = _write_manifests(public, courses, remote=False)
for course in courses:
course_id = int(course.get("id") or 0)
manifest = public / "courses" / str(course_id) / "manifest.json"
if not manifest.is_file():
raise MoodleError(f"migration did not create {manifest}")
for item_metadata in (public / "courses" / str(course_id) / "content").rglob("item.json"):
item_metadata.unlink()
source_course = legacy / "courses" / str(course_id)
(source_course / "course.json").unlink(missing_ok=True)
try:
legacy_course.rmdir()
source_course.rmdir()
except OSError:
pass
return migration
for generated in ("app.js", "course.html", "index.html", "nginx-server.conf", "styles.css", "courses.json"):
(legacy / generated).unlink(missing_ok=True)
try:
(legacy / "courses").rmdir()
legacy.rmdir()
except OSError:
pass
return {"catalog": result, "moved": moved}
+1 -29
View File
@@ -8,7 +8,6 @@ import urllib.parse
from pathlib import Path
from typing import Any, Iterable
from .constants import CONTENT_SCHEMA_VERSION
from .models import FileItem, MoodleError
@@ -73,6 +72,7 @@ def _discover_artifacts(activity_directory: Path, library: Path) -> dict[str, di
"transcript": ("transcript.fa.txt", "text", "fa"),
"transcript_metadata": ("transcript.meta.json", "json", None),
"summary": ("summary.fa.md", "markdown", "fa"),
"summary_metadata": ("summary.meta.json", "json", None),
"questions": ("questions.fa.md", "markdown", "fa"),
}
artifacts: dict[str, dict[str, Any]] = {}
@@ -92,34 +92,6 @@ def _discover_artifacts(activity_directory: Path, library: Path) -> dict[str, di
return artifacts
def _write_item_metadata(item: FileItem, activity_directory: Path, file_path: Path) -> Path:
metadata_path = activity_directory / "item.json"
metadata = _read_json_object(metadata_path)
files = [str(value) for value in metadata.get("files", []) if value]
relative_file = file_path.relative_to(activity_directory).as_posix()
if relative_file not in files:
files.append(relative_file)
metadata.update(
{
"schema_version": CONTENT_SCHEMA_VERSION,
"course_id": item.course_id,
"activity_id": item.activity_id,
"type": item.activity_type or "resource",
"title": re.sub(r"\s*فایل\s*$", "", item.activity).strip() or item.filename,
"position": item.activity_position,
"section": {
"id": item.section_id,
"number": item.section_number,
"title": item.chapter or item.section,
},
"description": item.description,
"files": files,
}
)
metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return metadata_path
def _filename_from_headers(headers: Any, url: str, fallback: str) -> str:
disposition = headers.get("Content-Disposition", "")
star = re.search(r"filename\*=UTF-8''([^;]+)", disposition, flags=re.I)
+397
View File
@@ -0,0 +1,397 @@
"""Remote course scanning, local state reconciliation, and manifest storage."""
from __future__ import annotations
import hashlib
import json
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable, Iterator
from .catalog import _build_library_catalog
from .client import MoodleClient
from .models import FileItem, MoodleError
from .paths import (
_activity_directory_name,
_course_content_root,
_discover_artifacts,
_read_json_object,
_relative_browser_path,
)
MANIFEST_SCHEMA_VERSION = 1
STATE_VALUES = {"missing", "partial", "complete", "stale", "error", "not_applicable"}
def _utc_now() -> str:
return datetime.now(timezone.utc).isoformat()
def _atomic_json(path: Path, value: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
temporary = path.with_name(path.name + ".tmp")
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
temporary.replace(path)
@contextmanager
def _manifest_lock(courses_root: Path) -> Iterator[None]:
courses_root.mkdir(parents=True, exist_ok=True)
lock_path = courses_root / ".manifest.lock"
with lock_path.open("a+", encoding="utf-8") as lock:
try:
import fcntl
fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
except (ImportError, OSError):
pass
try:
yield
finally:
try:
import fcntl
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
except (ImportError, OSError):
pass
def _activity_directory(public: Path, course_id: int, section: dict[str, Any], item: dict[str, Any]) -> Path:
key = _activity_directory_name(
item.get("section_number", section.get("number")),
item.get("activity_position"),
item.get("activity_id"),
fallback=f"{course_id}\0{item.get('source_url', '')}\0{item.get('title', '')}",
)
item["key"] = key
item["bundle_path"] = f"content/{key}"
return _course_content_root(public, course_id) / key
def _sha256(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
for chunk in iter(lambda: source.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _summary_metadata(summary: Path, transcript: Path) -> dict[str, Any]:
transcript_stat = transcript.stat()
return {
"schema_version": MANIFEST_SCHEMA_VERSION,
"source": "transcript.fa.txt",
"source_sha256": _sha256(transcript),
"source_size": transcript_stat.st_size,
"source_mtime_ns": transcript_stat.st_mtime_ns,
"generated_at": datetime.fromtimestamp(summary.stat().st_mtime, timezone.utc).isoformat(),
}
def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> str:
artifacts = activity_directory / "artifacts"
if kind == "transcript":
transcript = artifacts / "transcript.fa.txt"
if not transcript.is_file():
return "missing" if applicable else "not_applicable"
metadata = _read_json_object(artifacts / "transcript.meta.json")
source_files: list[Path] = []
source_name = metadata.get("source") if metadata else None
if isinstance(source_name, str):
candidate = (artifacts / source_name).resolve()
try:
candidate.relative_to(activity_directory.resolve())
except ValueError:
candidate = Path()
if candidate.is_file():
source_files.append(candidate)
if not source_files:
source_files = sorted(
path
for path in (activity_directory / "files").glob("*")
if path.is_file() and not path.name.endswith(".part")
)
if not metadata or not source_files:
return "stale"
source_stat = source_files[0].stat()
expected_size = metadata.get("source_size")
expected_mtime = metadata.get("source_mtime_ns")
if expected_size is not None and int(expected_size) != source_stat.st_size:
return "stale"
if expected_mtime is not None and int(expected_mtime) != source_stat.st_mtime_ns:
return "stale"
return "complete"
if kind == "summary":
summary = artifacts / "summary.fa.md"
if not summary.is_file():
return "missing" if applicable else "not_applicable"
transcript = artifacts / "transcript.fa.txt"
if not transcript.is_file():
return "stale"
metadata_path = artifacts / "summary.meta.json"
metadata = _read_json_object(metadata_path)
current = _summary_metadata(summary, transcript)
if not metadata:
_atomic_json(metadata_path, current)
return "complete"
if (
metadata.get("source_sha256") != current["source_sha256"]
or int(metadata.get("source_size") or -1) != current["source_size"]
or int(metadata.get("source_mtime_ns") or -1) != current["source_mtime_ns"]
):
return "stale"
return "complete"
questions = artifacts / "questions.fa.md"
if questions.is_file():
return "complete"
return "missing" if applicable else "not_applicable"
def _download_state(activity_directory: Path, item: dict[str, Any]) -> tuple[str, Path | None]:
filename = str(item.get("filename") or "")
files_directory = activity_directory / "files"
final = files_directory / filename if filename else None
if final and final.is_file():
expected_size = item.get("remote_size")
if expected_size is not None and int(expected_size) != final.stat().st_size:
return "error", final
return "complete", final
partial = final.with_name(final.name + ".part") if final else None
if partial and partial.is_file():
return "partial", partial
if filename or item.get("activity_type") in {"resource", "folder", "page", "book"}:
return "missing", None
return "not_applicable", None
def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
course_id = int(course.get("id") or 0)
downloaded_bytes = 0
type_counts: dict[str, int] = {}
state_counts = {
"downloads": {"complete": 0, "total": 0},
"transcripts": {"complete": 0, "total": 0},
"summaries": {"complete": 0, "total": 0},
"assessments": {"complete": 0, "total": 0},
"partial": 0,
"stale": 0,
"errors": 0,
}
records = 0
for section in course.get("sections", []):
for item in section.get("items", []):
records += 1
activity_directory = _activity_directory(public, course_id, section, item)
download_state, local_path = _download_state(activity_directory, item)
media_applicable = item.get("kind") in {"video", "audio"}
assessment_applicable = item.get("kind") == "assessment" or item.get("activity_type") == "quiz"
transcript_state = _artifact_state(activity_directory, "transcript", media_applicable)
summary_state = _artifact_state(activity_directory, "summary", media_applicable)
questions_state = _artifact_state(activity_directory, "questions", assessment_applicable)
for value in (download_state, transcript_state, summary_state, questions_state):
if value not in STATE_VALUES:
raise MoodleError(f"invalid manifest state {value!r}")
item["state"] = {
"download": download_state,
"transcript": transcript_state,
"summary": summary_state,
"questions": questions_state,
}
item["downloaded"] = download_state == "complete"
item["transcribed"] = transcript_state == "complete"
item["summarized"] = summary_state == "complete"
item["status"] = (
"downloaded" if download_state == "complete"
else "online" if download_state == "not_applicable"
else download_state
)
item["artifacts"] = _discover_artifacts(activity_directory, public)
if local_path:
item["local_bytes"] = local_path.stat().st_size
item["local_url"] = _relative_browser_path(local_path, public)
if download_state == "complete":
item["size"] = local_path.stat().st_size
downloaded_bytes += local_path.stat().st_size
else:
item["local_bytes"] = 0
item["local_url"] = None
if download_state != "not_applicable":
state_counts["downloads"]["total"] += 1
state_counts["downloads"]["complete"] += int(download_state == "complete")
if media_applicable:
state_counts["transcripts"]["total"] += 1
state_counts["transcripts"]["complete"] += int(transcript_state == "complete")
state_counts["summaries"]["total"] += 1
state_counts["summaries"]["complete"] += int(summary_state == "complete")
if assessment_applicable:
state_counts["assessments"]["total"] += 1
state_counts["assessments"]["complete"] += int(questions_state == "complete")
state_counts["partial"] += int(download_state == "partial")
state_counts["stale"] += sum(value == "stale" for value in (transcript_state, summary_state))
state_counts["errors"] += int(download_state == "error")
kind = str(item.get("kind") or "activity")
type_counts[kind] = type_counts.get(kind, 0) + 1
course.update(
{
"record_count": records,
"file_count": state_counts["downloads"]["total"],
"downloaded_count": state_counts["downloads"]["complete"],
"downloaded_bytes": downloaded_bytes,
"type_counts": type_counts,
"states": state_counts,
}
)
return course
def _course_summary(course: dict[str, Any]) -> dict[str, Any]:
return {
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",
)
} | {"manifest_url": f"courses/{course.get('id')}/manifest.json"}
def _catalog_from_manifests(courses_root: Path, now: str) -> dict[str, Any]:
courses: list[dict[str, Any]] = []
for path in sorted(courses_root.glob("*/manifest.json")):
course = _read_json_object(path).get("course")
if isinstance(course, dict):
courses.append(course)
courses.sort(key=lambda course: str(course.get("fullname") or "").casefold())
return {
"schema_version": MANIFEST_SCHEMA_VERSION,
"generated_at": now,
"stats": {
"courses": len(courses),
"activities": sum(int(course.get("activity_count") or 0) for course in courses),
"records": sum(int(course.get("record_count") or 0) for course in courses),
"files": sum(int(course.get("file_count") or 0) for course in courses),
"downloaded_files": sum(int(course.get("downloaded_count") or 0) for course in courses),
"downloaded_bytes": sum(int(course.get("downloaded_bytes") or 0) for course in courses),
},
"courses": [_course_summary(course) for course in courses],
}
def _write_manifests(public: Path, courses: Iterable[dict[str, Any]], *, remote: bool) -> dict[str, Any]:
courses_root = public / "courses"
now = _utc_now()
with _manifest_lock(courses_root):
for course in courses:
reconciled = _reconcile_course(public, course)
manifest_path = courses_root / str(course["id"]) / "manifest.json"
previous = _read_json_object(manifest_path)
scan = dict(previous.get("scan") or {})
scan["local_at"] = now
if remote:
scan["remote_at"] = now
manifest = {
"schema_version": MANIFEST_SCHEMA_VERSION,
"generated_at": now,
"scan": scan,
"course": reconciled,
}
_atomic_json(manifest_path, manifest)
catalog = _catalog_from_manifests(courses_root, now)
_atomic_json(courses_root / "catalog.json", catalog)
return catalog
def scan_remote(client: MoodleClient, public: Path, course_ids: Iterable[int] = ()) -> dict[str, Any]:
full_catalog = _build_library_catalog(client, public, course_ids)
return _write_manifests(public, full_catalog.get("courses", []), remote=True)
def scan_offline(public: Path, course_ids: Iterable[int] = ()) -> dict[str, Any]:
courses_root = public / "courses"
selected = set(course_ids)
manifests = sorted(courses_root.glob("*/manifest.json"))
courses = []
for path in manifests:
manifest = _read_json_object(path)
course = manifest.get("course")
if not isinstance(course, dict):
continue
course_id = int(course.get("id") or 0)
if selected and course_id not in selected:
continue
courses.append(course)
missing = selected - {int(course.get("id") or 0) for course in courses}
if missing:
raise MoodleError(f"course manifest(s) not found: {', '.join(str(value) for value in sorted(missing))}")
if not courses:
raise MoodleError(f"no course manifests found in {courses_root}; run `ravin scan` online first")
return _write_manifests(public, courses, remote=False)
def update_download_state(public: Path, item: FileItem, path: Path) -> None:
if not path.is_file():
return
manifest_path = public / "courses" / str(item.course_id) / "manifest.json"
courses_root = public / "courses"
with _manifest_lock(courses_root):
manifest = _read_json_object(manifest_path)
course = manifest.get("course")
if not isinstance(course, dict):
return
now = _utc_now()
manifest["course"] = _reconcile_course(public, course)
manifest["generated_at"] = now
scan = dict(manifest.get("scan") or {})
scan["local_at"] = now
manifest["scan"] = scan
_atomic_json(manifest_path, manifest)
_atomic_json(courses_root / "catalog.json", _catalog_from_manifests(courses_root, now))
def scan_output(catalog: dict[str, Any]) -> list[dict[str, Any]]:
return [
{
"id": course.get("id"),
"title": course.get("fullname"),
"sections": course.get("section_count"),
"activities": course.get("activity_count"),
"downloads": course.get("states", {}).get("downloads", {}),
"transcripts": course.get("states", {}).get("transcripts", {}),
"summaries": course.get("states", {}).get("summaries", {}),
"assessments": course.get("states", {}).get("assessments", {}),
"partial": course.get("states", {}).get("partial", 0),
"stale": course.get("states", {}).get("stale", 0),
"errors": course.get("states", {}).get("errors", 0),
}
for course in catalog.get("courses", [])
]
def format_scan(catalog: dict[str, Any]) -> str:
blocks = []
for course in scan_output(catalog):
def count(name: str) -> str:
state = course[name]
return f"{int(state.get('complete') or 0):>3} / {int(state.get('total') or 0):<3} complete"
blocks.append(
"\n".join(
(
f"Course {course['id']} — {course['title']}",
f"{course['activities']} activities across {course['sections']} sections",
"",
f"Downloads {count('downloads')}",
f"Transcripts {count('transcripts')}",
f"Summaries {count('summaries')}",
f"Assessments {count('assessments')}",
f"Partial {course['partial']}",
f"Stale {course['stale']}",
f"Errors {course['errors']}",
)
)
)
return "\n\n".join(blocks)
+5 -5
View File
@@ -86,11 +86,11 @@ class _RangeRequestHandler(http.server.SimpleHTTPRequestHandler):
remaining -= len(chunk)
def _serve_library(site_dir: Path, host: str, port: int, open_browser: bool) -> None:
site_dir = site_dir.expanduser().resolve()
if not (site_dir / "index.html").is_file() or not (site_dir / "courses.json").is_file():
raise MoodleError(f"{site_dir} is not built yet; run `ravin library` first")
handler = functools.partial(_RangeRequestHandler, directory=str(site_dir))
def _serve_library(public: Path, host: str, port: int, open_browser: bool) -> None:
public = public.expanduser().resolve()
if not (public / "index.html").is_file() or not (public / "courses" / "catalog.json").is_file():
raise MoodleError(f"{public} is not ready; run `ravin scan` first")
handler = functools.partial(_RangeRequestHandler, directory=str(public))
try:
server = http.server.ThreadingHTTPServer((host, port), handler)
except OSError as exc: