feat: preserve and display archived course file versions

This commit is contained in:
Meghdad committed 2026-08-13 16:55:59 +03:30
1 parent 53b6dad560
commit 3869d94cfe
11 files changed
+301 -16

No files matched your search

+9
View File
@@ -2,6 +2,15 @@
All notable changes to this project will be documented here.
## 0.10.0 - 2026-08-13
- Track the Moodle-selected resource as current while retaining other local files as archived versions.
- Preserve an existing same-name download under `files/archive/` before atomically installing its replacement.
- Show current and archived files in the static library, including playback for archived videos.
- Mark transcripts and summaries stale when they were generated from an archived media version.
- Match scanner paths using the downloader's filename normalization so Moodle whitespace changes do not create false missing-file reports.
- Apply the same filename normalization during transcription discovery when archived media is also present.
## 0.9.0 - 2026-08-13
- Add an interactive `ravin questions` wizard for importing or updating Markdown exam questions.
+5 -1
View File
@@ -99,6 +99,10 @@ SECTION_NUMBER--ACTIVITY_POSITION--ACTIVITY_ID
Original filenames stay unchanged in the bundle's `files/` directory. Interrupted downloads use a `.part` suffix and resume with HTTP byte ranges. Completed files are skipped unless `--overwrite` is supplied.
When an instructor replaces a resource, the manifest treats the filename currently published by Moodle as the **current** version and keeps other local files as **archived** versions. A replacement with the same filename and a different known size is downloaded automatically; `--overwrite` can force a same-name refresh when Moodle does not report a size. In both cases the existing file is preserved under `files/archive/` before the new download takes its place.
The library's main Play or Open action always uses the current file. Older files remain available in an expandable archived-version list. If a transcript was generated from an archived file, both it and its dependent summary are marked stale; run `ravin transcribe COURSE_ID` and then `ravin summarize COURSE_ID` to regenerate them for the current file.
An activity can also contain generated study material:
```text
@@ -255,7 +259,7 @@ ravin scan
ravin serve --open
```
The site provides course search, chapter grouping, local availability and artifact states, video playback, document and assessment links, transcript and summary readers, Markdown question rendering, dark mode, and browser-local completion checkboxes.
The site provides course search, chapter grouping, local availability and artifact states, current and archived file playback, document and assessment links, transcript and summary readers, Markdown question rendering, dark mode, and browser-local completion checkboxes.
The layout is:
+52 -5
View File
@@ -246,7 +246,8 @@ function isComplete(item) {
}
function resourceMatches(item) {
const haystack = normalized(`${item.title} ${item.filename} ${item.section}`);
const versionNames = (item.file_versions || []).map((version) => version.filename).join(" ");
const haystack = normalized(`${item.title} ${item.filename} ${versionNames} ${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;
@@ -266,11 +267,20 @@ function resourceRow(item, index) {
title.className = "resource-title";
title.dir = "auto";
title.textContent = item.title;
const fileLine = document.createElement("div");
fileLine.className = "resource-file-line";
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);
fileLine.append(filename);
if ((item.file_versions || []).some((version) => version.state === "current")) {
const currentBadge = document.createElement("span");
currentBadge.className = "current-version-badge";
currentBadge.textContent = "Current";
fileLine.append(currentBadge);
}
main.append(title, fileLine);
if (item.description) {
const description = document.createElement("span");
description.className = "resource-description";
@@ -297,6 +307,43 @@ function resourceRow(item, index) {
});
main.append(artifactActions);
}
const archivedVersions = (item.file_versions || []).filter((version) => version.state === "archived");
if (archivedVersions.length) {
const history = document.createElement("details");
history.className = "version-history";
const historyTitle = document.createElement("summary");
historyTitle.textContent = `${archivedVersions.length} archived version${archivedVersions.length === 1 ? "" : "s"}`;
history.append(historyTitle);
const versionList = document.createElement("div");
versionList.className = "version-list";
archivedVersions.forEach((version) => {
const versionRow = document.createElement("div");
versionRow.className = "version-row";
const versionInfo = document.createElement("span");
versionInfo.className = "version-info";
versionInfo.dir = "auto";
const modified = version.modified_at ? new Date(version.modified_at).toLocaleDateString() : "";
versionInfo.textContent = `${version.filename} · ${formatBytes(version.size)}${modified ? ` · ${modified}` : ""}`;
let versionAction;
if (String(version.mimetype || "").startsWith("video/")) {
versionAction = document.createElement("button");
versionAction.type = "button";
versionAction.textContent = "Play archived";
versionAction.addEventListener("click", () => openVideo(item, version));
} else {
versionAction = document.createElement("a");
versionAction.href = version.url;
versionAction.target = "_blank";
versionAction.rel = "noopener";
versionAction.textContent = "Open archived";
}
versionAction.className = "version-action";
versionRow.append(versionInfo, versionAction);
versionList.append(versionRow);
});
history.append(versionList);
main.append(history);
}
const stateLabels = { download: "File", transcript: "Transcript", summary: "Summary", questions: "Questions" };
const visibleStates = Object.entries(item.state || {}).filter(([, value]) => value !== "not_applicable");
if (visibleStates.length) {
@@ -402,11 +449,11 @@ function renderResources() {
byId("emptyResources").hidden = visibleCount !== 0;
}
function openVideo(item) {
function openVideo(item, version = null) {
const dialog = byId("mediaDialog");
const player = byId("mediaPlayer");
setText("mediaTitle", item.title);
player.src = item.local_url;
setText("mediaTitle", version ? `${item.title} — ${version.filename} (Archived)` : item.title);
player.src = version?.url || item.local_url;
dialog.showModal();
player.play().catch(() => {});
}
+9 -1
View File
@@ -338,11 +338,19 @@ main {
.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-file-line { display: flex; align-items: center; flex-wrap: wrap; gap: 7px; margin-top: 4px; }
.resource-file { display: block; overflow: hidden; color: var(--muted); font-size: .78rem; text-overflow: ellipsis; white-space: nowrap; }
.current-version-badge { padding: 3px 6px; border-radius: 6px; color: var(--accent-strong); background: color-mix(in srgb, var(--accent) 22%, var(--surface)); font-size: .6rem; font-weight: 800; letter-spacing: .04em; text-transform: uppercase; }
.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); }
.version-history { max-width: 680px; margin-top: 9px; color: var(--muted); font-size: .72rem; }
.version-history summary { width: max-content; cursor: pointer; color: color-mix(in srgb, var(--ink) 62%, #c48600); font-weight: 750; }
.version-list { display: grid; gap: 6px; margin-top: 7px; }
.version-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 7px 9px; border: 1px solid color-mix(in srgb, #c48600 32%, var(--line)); border-radius: 9px; background: color-mix(in srgb, #c48600 9%, var(--surface)); }
.version-info { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.version-action { flex: 0 0 auto; padding: 4px 7px; border: 0; border-radius: 6px; color: color-mix(in srgb, var(--ink) 70%, #a76c00); background: color-mix(in srgb, #c48600 18%, var(--surface-strong)); cursor: pointer; font: inherit; font-weight: 750; text-decoration: none; }
.state-chips { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 9px; }
.state-chip { padding: 4px 7px; border-radius: 7px; color: var(--muted); background: var(--surface-strong); font-size: .65rem; font-weight: 700; text-transform: capitalize; }
.state-chip.complete { color: var(--accent-strong); background: color-mix(in srgb, var(--accent-soft) 78%, transparent); }
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ravin-moodle-downloader"
version = "0.9.0"
version = "0.10.0"
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
readme = "README.md"
requires-python = ">=3.10"
+26 -2
View File
@@ -4,7 +4,9 @@ import http.client
import http.cookiejar
import json
import mimetypes
import os
import re
import shutil
import sys
import time
import urllib.error
@@ -25,6 +27,23 @@ from .paths import (
)
def _archive_existing_download(path: Path) -> Path:
"""Preserve a file before replacing its current path."""
archive_directory = path.parent / "archive"
archive_directory.mkdir(parents=True, exist_ok=True)
timestamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
candidate = archive_directory / f"{timestamp}--{path.name}"
counter = 2
while candidate.exists():
candidate = archive_directory / f"{timestamp}--{counter}--{path.name}"
counter += 1
try:
os.link(path, candidate)
except OSError:
shutil.copy2(path, candidate)
return candidate
class MoodleClient:
def __init__(
self,
@@ -460,7 +479,8 @@ class MoodleClient:
suggested_filename = _clean_name(item.filename, activity)
destination = directory / suggested_filename
if destination.exists() and not overwrite:
return destination
if item.filesize is None or destination.stat().st_size == item.filesize:
return destination
temporary = destination.with_name(destination.name + ".part")
if overwrite:
temporary.unlink(missing_ok=True)
@@ -480,7 +500,8 @@ class MoodleClient:
if not temporary.exists() and response_filename != suggested_filename:
destination = directory / response_filename
if destination.exists() and not overwrite:
return destination
if expected_total is None or destination.stat().st_size == expected_total:
return destination
temporary = destination.with_name(destination.name + ".part")
resume_at = temporary.stat().st_size if temporary.exists() else 0
@@ -538,6 +559,9 @@ class MoodleClient:
raise MoodleError(
f"connection closed early at {downloaded} of {expected_total} bytes"
)
if destination.exists():
archived = _archive_existing_download(destination)
print(f" archived previous version as {archived.name}", file=sys.stderr)
temporary.replace(destination)
if sys.stderr.isatty():
elapsed = max(time.monotonic() - started, 0.01)
+1 -1
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.9.0"
__version__ = "0.10.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
DEFAULT_ENV_FILE = Path.cwd() / ".env"
+74 -3
View File
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import json
import mimetypes
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
@@ -14,6 +15,7 @@ from .client import MoodleClient
from .models import FileItem, MoodleError
from .paths import (
_activity_directory_name,
_clean_name,
_course_content_root,
_discover_artifacts,
_read_json_object,
@@ -90,7 +92,12 @@ def _summary_metadata(summary: Path, transcript: Path) -> dict[str, Any]:
}
def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> str:
def _artifact_state(
activity_directory: Path,
kind: str,
applicable: bool,
current_source: Path | None = None,
) -> str:
artifacts = activity_directory / "artifacts"
if kind == "transcript":
transcript = artifacts / "transcript.fa.txt"
@@ -118,6 +125,8 @@ def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> st
)
if not metadata or not source_files:
return "error" if failed else "stale"
if current_source is not None and source_files[0].resolve() != current_source.resolve():
return "error" if failed else "stale"
source_stat = source_files[0].stat()
expected_size = metadata.get("source_size")
expected_mtime = metadata.get("source_mtime_ns")
@@ -160,7 +169,7 @@ def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> st
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
final = files_directory / _clean_name(filename, "file") 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:
@@ -174,6 +183,50 @@ def _download_state(activity_directory: Path, item: dict[str, Any]) -> tuple[str
return "not_applicable", None
def _file_versions(
public: Path,
activity_directory: Path,
current: Path | None,
) -> list[dict[str, Any]]:
"""Describe the current resource and every preserved older version."""
files_directory = activity_directory / "files"
if not files_directory.is_dir():
return []
candidates = [
path
for path in files_directory.rglob("*")
if path.is_file()
and not path.name.endswith(".part")
and not any(part.startswith(".") for part in path.relative_to(files_directory).parts)
]
current_resolved = current.resolve() if current and current.is_file() else None
records: list[dict[str, Any]] = []
for path in candidates:
stat = path.stat()
is_current = current_resolved is not None and path.resolve() == current_resolved
mimetype = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
records.append(
{
"filename": path.name,
"path": path.relative_to(activity_directory).as_posix(),
"url": _relative_browser_path(path, public),
"size": stat.st_size,
"mtime_ns": stat.st_mtime_ns,
"modified_at": datetime.fromtimestamp(stat.st_mtime, timezone.utc).isoformat(),
"mimetype": mimetype,
"state": "current" if is_current else "archived",
}
)
return sorted(
records,
key=lambda record: (
record["state"] != "current",
-int(record["mtime_ns"]),
str(record["path"]).casefold(),
),
)
def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
course_id = int(course.get("id") or 0)
downloaded_bytes = 0
@@ -195,8 +248,22 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
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)
transcript_state = _artifact_state(
activity_directory,
"transcript",
media_applicable,
current_source=local_path,
)
if media_applicable and download_state != "complete" and transcript_state == "complete":
transcript_state = "stale"
summary_state = _artifact_state(activity_directory, "summary", media_applicable)
if (
media_applicable
and download_state == "complete"
and transcript_state != "complete"
and summary_state == "complete"
):
summary_state = "stale"
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:
@@ -216,6 +283,10 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
else download_state
)
item["artifacts"] = _discover_artifacts(activity_directory, public)
if item.get("activity_type") == "resource" and item.get("filename"):
item["file_versions"] = _file_versions(public, activity_directory, local_path)
else:
item.pop("file_versions", None)
if local_path:
item["local_bytes"] = local_path.stat().st_size
item["local_url"] = _relative_browser_path(local_path, public)
+2 -2
View File
@@ -18,7 +18,7 @@ from pathlib import Path
from typing import Any, Callable, Iterator
from .models import MoodleError
from .paths import _read_json_object
from .paths import _clean_name, _read_json_object
from .scan import scan_offline
@@ -279,7 +279,7 @@ class CourseTranscriber:
continue
key = str(item.get("key") or item.get("bundle_path", "").removeprefix("content/"))
activity = courses_root / str(course_id) / "content" / key
expected = activity / "files" / str(item.get("filename") or "")
expected = activity / "files" / _clean_name(str(item.get("filename") or ""), "file")
candidates = sorted(
path for path in (activity / "files").glob("*")
if path.is_file() and not path.name.endswith(".part")
+101
View File
@@ -415,6 +415,107 @@ class ParserTests(unittest.TestCase):
self.assertEqual(item["state"]["download"], "complete")
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
def test_offline_scan_uses_the_downloaders_normalized_filename(self):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory) / "public"
activity = output / "courses" / "44" / "content" / "013--001--4951"
downloaded = activity / "files" / "Network + 12 Exp.mp4"
downloaded.parent.mkdir(parents=True)
downloaded.write_bytes(b"replacement video")
old_file = activity / "files" / "12.mp4"
old_file.write_bytes(b"old video preserved")
transcript = activity / "artifacts" / "transcript.fa.txt"
transcript.parent.mkdir(parents=True)
transcript.write_text("old transcript", encoding="utf-8")
old_stat = old_file.stat()
(activity / "artifacts" / "transcript.meta.json").write_text(
json.dumps(
{
"source": "../files/12.mp4",
"source_size": old_stat.st_size,
"source_mtime_ns": old_stat.st_mtime_ns,
}
),
encoding="utf-8",
)
manifest_path = output / "courses" / "44" / "manifest.json"
manifest_path.write_text(
json.dumps(
{
"schema_version": 1,
"course": {
"id": 44,
"fullname": "Network +",
"sections": [{
"number": 13,
"items": [{
"filename": "Network + 12 Exp.mp4",
"activity_type": "resource",
"kind": "video",
"title": "Internet Protocol Addressing (IP)",
"section_number": 13,
"activity_position": 1,
"activity_id": 4951,
}],
}],
},
}
),
encoding="utf-8",
)
scan_offline(output, [44])
refreshed = json.loads(manifest_path.read_text(encoding="utf-8"))
item = refreshed["course"]["sections"][0]["items"][0]
self.assertEqual(item["state"]["download"], "complete")
self.assertEqual(
item["local_url"],
"courses/44/content/013--001--4951/files/Network%20%2B%2012%20Exp.mp4",
)
self.assertEqual(item["state"]["transcript"], "stale")
self.assertEqual(
[(version["filename"], version["state"]) for version in item["file_versions"]],
[("Network + 12 Exp.mp4", "current"), ("12.mp4", "archived")],
)
self.assertEqual(downloaded.read_bytes(), b"replacement video")
self.assertEqual(old_file.read_bytes(), b"old video preserved")
def test_changed_same_name_download_archives_previous_file(self):
response = _FakeResponse([b"new version"])
client = _FakeDownloadClient([response])
item = FileItem(
44,
"Course files",
"Lesson",
"file.bin",
"https://training.example/file.bin",
filesize=len(b"new version"),
section_number=2,
activity_id=4940,
activity_position=1,
)
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
destination = root / "courses" / "44" / "content" / "002--001--4940" / "files" / "file.bin"
destination.parent.mkdir(parents=True)
destination.write_bytes(b"old")
downloaded = client.download(item, root, retries=0, retry_delay=0)
archived = list((destination.parent / "archive").glob("*--file.bin"))
self.assertEqual(downloaded.read_bytes(), b"new version")
self.assertEqual(len(archived), 1)
self.assertEqual(archived[0].read_bytes(), b"old")
def test_public_library_renders_current_and_archived_versions(self):
script = (Path(__file__).resolve().parents[1] / "public" / "assets" / "app.js").read_text(
encoding="utf-8"
)
self.assertIn("current-version-badge", script)
self.assertIn("archivedVersions", script)
self.assertIn("Play archived", script)
def test_interrupted_download_retries_with_range(self):
first = _FakeResponse(
[
+21
View File
@@ -192,6 +192,27 @@ class TranscriptionTests(unittest.TestCase):
self.assertEqual(result.total, 1)
self.assertFalse(transcriber.runtime_root.exists())
def test_discovery_normalizes_current_filename_when_archived_media_exists(self) -> None:
self.write_course(["Network + 12 Exp.mp4"])
manifest_path = self.public / "courses" / "44" / "manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
manifest["course"]["sections"][0]["items"][0]["filename"] = "Network + 12 Exp.mp4"
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
files = self.public / "courses" / "44" / "content" / "002--001--4901" / "files"
(files / "12.mp4").write_bytes(b"archived video")
transcriber = CourseTranscriber(
self.options(dry_run=True),
model_loader=lambda _name, _device: (_ for _ in ()).throw(
AssertionError("dry-run must not load Whisper")
),
media_validator=lambda _source: None,
)
result = transcriber.run()
self.assertEqual(result.total, 1)
self.assertEqual(result.unavailable, 0)
if __name__ == "__main__":
unittest.main()