feat: reconcile course bundles by stable activity ID
This commit is contained in:
8 files changed
+596
-26
No files matched your search
@@ -2,6 +2,14 @@
|
||||
|
||||
All notable changes to this project will be documented here.
|
||||
|
||||
## 0.16.0 - 2026-08-30
|
||||
|
||||
- Treat Moodle activity IDs as stable local bundle identities while retaining sortable `SECTION--POSITION--ID` paths.
|
||||
- Automatically rekey complete activity bundles when instructors reorder sections or activities.
|
||||
- Repair layouts before online discovery and during offline scans, imports, and manifest reconciliation.
|
||||
- Safely merge duplicate old/current paths, deduplicate identical data, and archive conflicting older files and artifacts.
|
||||
- Preserve orphaned and ID-less bundles without presenting them as current LMS activities.
|
||||
|
||||
## 0.15.0 - 2026-08-27
|
||||
|
||||
- Add accurate, balanced, and fast Whisper decoding profiles.
|
||||
|
||||
@@ -102,6 +102,8 @@ 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.
|
||||
|
||||
The final activity ID is the bundle's stable identity. If an instructor inserts, removes, or reorders sections or activities, an online scan automatically rekeys the complete local bundle to the LMS's current section and position before checking its state. An offline scan performs the same repair from the latest saved manifest. This preserves downloads and generated artifacts instead of reporting them missing or downloading duplicates. If both the old and current paths already contain data, Ravin safely merges them, keeps the current LMS layout authoritative, deduplicates identical files, and archives conflicting older versions.
|
||||
|
||||
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.
|
||||
@@ -441,6 +443,7 @@ src/ravin/
|
||||
├── recordings.py # local live-class recording imports
|
||||
├── exporter.py # atomic course ZIP exports
|
||||
├── importer.py # safe URL restores and mirror updates
|
||||
├── layout.py # activity-ID layout reconciliation
|
||||
├── local_files.py # atomic local copies and archived versions
|
||||
├── wizard.py # shared interactive import helpers
|
||||
├── migration.py # previous-layout migration
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "ravin-moodle-downloader"
|
||||
version = "0.15.0"
|
||||
version = "0.16.0"
|
||||
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -11,6 +11,7 @@ from typing import Any, Iterable
|
||||
|
||||
from .client import MoodleClient
|
||||
from .constants import LIVE_CLASS_MODULES
|
||||
from .layout import format_layout_repair, repair_activity_layout
|
||||
from .models import FileItem, MoodleError
|
||||
from .paths import (
|
||||
_activity_directory_name, _activity_root, _clean_name, _course_content_root,
|
||||
@@ -134,6 +135,37 @@ def _build_library_catalog(
|
||||
structure = []
|
||||
consumed: set[int] = set()
|
||||
|
||||
desired_keys: dict[int, str] = {}
|
||||
for section in structure:
|
||||
for activity in section.get("activities", []):
|
||||
try:
|
||||
activity_id = int(activity.get("id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if activity_id <= 0:
|
||||
continue
|
||||
desired_keys[activity_id] = _activity_directory_name(
|
||||
section.get("number"),
|
||||
activity.get("position"),
|
||||
activity_id,
|
||||
fallback=f"{course.id}\0{activity.get('url', '')}\0{activity.get('name', '')}",
|
||||
)
|
||||
for item in items:
|
||||
if item.activity_id is None or int(item.activity_id) <= 0:
|
||||
continue
|
||||
desired_keys.setdefault(
|
||||
int(item.activity_id),
|
||||
_activity_directory_name(
|
||||
item.section_number,
|
||||
item.activity_position,
|
||||
item.activity_id,
|
||||
fallback=f"{course.id}\0{item.url}\0{item.activity}\0{item.filename}",
|
||||
),
|
||||
)
|
||||
layout_repair = repair_activity_layout(library, course.id, desired_keys)
|
||||
if layout_repair.changed:
|
||||
print(format_layout_repair(layout_repair), file=sys.stderr)
|
||||
|
||||
def file_record(
|
||||
item: FileItem,
|
||||
item_index: int,
|
||||
|
||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
DEFAULT_SITE = "https://training.ravinacademy.com"
|
||||
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
||||
__version__ = "0.15.0"
|
||||
__version__ = "0.16.0"
|
||||
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
||||
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
||||
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
"""Stable activity identity and safe local bundle layout repair."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import re
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Iterator, Mapping
|
||||
|
||||
from .models import MoodleError
|
||||
from .paths import _activity_directory_name, _course_content_root
|
||||
|
||||
|
||||
ACTIVITY_DIRECTORY_PATTERN = re.compile(r"^\d+--\d+--([1-9]\d*)$")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class LayoutRepairResult:
|
||||
course_id: int
|
||||
rekeyed: int = 0
|
||||
merged: int = 0
|
||||
deduplicated: int = 0
|
||||
archived_conflicts: int = 0
|
||||
|
||||
@property
|
||||
def changed(self) -> bool:
|
||||
return bool(self.rekeyed)
|
||||
|
||||
|
||||
@contextmanager
|
||||
def manifest_lock(courses_root: Path) -> Iterator[None]:
|
||||
"""Serialize manifest and activity-layout changes for one public root."""
|
||||
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 desired_activity_keys(course: Mapping[str, Any]) -> dict[int, str]:
|
||||
"""Return the current canonical key for every stable activity ID."""
|
||||
desired: dict[int, str] = {}
|
||||
course_id = int(course.get("id") or 0)
|
||||
for section in course.get("sections", []):
|
||||
if not isinstance(section, Mapping):
|
||||
continue
|
||||
for item in section.get("items", []):
|
||||
if not isinstance(item, Mapping):
|
||||
continue
|
||||
try:
|
||||
activity_id = int(item.get("activity_id") or 0)
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
if activity_id <= 0:
|
||||
continue
|
||||
key = _activity_directory_name(
|
||||
item.get("section_number", section.get("number")),
|
||||
item.get("activity_position"),
|
||||
activity_id,
|
||||
fallback=f"{course_id}\0{item.get('source_url', '')}\0{item.get('title', '')}",
|
||||
)
|
||||
previous = desired.get(activity_id)
|
||||
if previous is not None and previous != key:
|
||||
raise MoodleError(
|
||||
f"activity {activity_id} has conflicting positions in course {course_id}: "
|
||||
f"{previous} and {key}"
|
||||
)
|
||||
desired[activity_id] = key
|
||||
return desired
|
||||
|
||||
|
||||
def _activity_id(path: Path) -> int | None:
|
||||
match = ACTIVITY_DIRECTORY_PATTERN.fullmatch(path.name)
|
||||
return int(match.group(1)) if match else None
|
||||
|
||||
|
||||
def _same_file(left: Path, right: Path) -> bool:
|
||||
if left.is_symlink() or right.is_symlink():
|
||||
return left.is_symlink() and right.is_symlink() and os.readlink(left) == os.readlink(right)
|
||||
if not left.is_file() or not right.is_file():
|
||||
return False
|
||||
left_stat = left.stat()
|
||||
right_stat = right.stat()
|
||||
if left_stat.st_size != right_stat.st_size:
|
||||
return False
|
||||
if left_stat.st_ino == right_stat.st_ino and left_stat.st_dev == right_stat.st_dev:
|
||||
return True
|
||||
with left.open("rb") as left_file, right.open("rb") as right_file:
|
||||
while True:
|
||||
left_chunk = left_file.read(1024 * 1024)
|
||||
right_chunk = right_file.read(1024 * 1024)
|
||||
if left_chunk != right_chunk:
|
||||
return False
|
||||
if not left_chunk:
|
||||
return True
|
||||
|
||||
|
||||
def _unique_archive_path(
|
||||
canonical: Path,
|
||||
relative: Path,
|
||||
source_key: str,
|
||||
timestamp: str,
|
||||
) -> Path:
|
||||
if relative.parts and relative.parts[0] == "files":
|
||||
archive_directory = canonical / "files" / "archive"
|
||||
elif relative.parts and relative.parts[0] == "artifacts":
|
||||
archive_directory = canonical / "artifacts" / "archive"
|
||||
else:
|
||||
archive_directory = canonical / "archive"
|
||||
archive_directory.mkdir(parents=True, exist_ok=True)
|
||||
base = f"{timestamp}--layout-{source_key}--{relative.name}"
|
||||
candidate = archive_directory / base
|
||||
counter = 2
|
||||
while candidate.exists() or candidate.is_symlink():
|
||||
candidate = archive_directory / f"{timestamp}--{counter}--layout-{source_key}--{relative.name}"
|
||||
counter += 1
|
||||
return candidate
|
||||
|
||||
|
||||
def _merge_entry(
|
||||
source: Path,
|
||||
target: Path,
|
||||
*,
|
||||
source_root: Path,
|
||||
canonical: Path,
|
||||
timestamp: str,
|
||||
) -> tuple[int, int]:
|
||||
"""Merge one source entry, returning deduplicated and archived counts."""
|
||||
if not target.exists() and not target.is_symlink():
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
os.replace(source, target)
|
||||
return 0, 0
|
||||
|
||||
source_is_directory = source.is_dir() and not source.is_symlink()
|
||||
target_is_directory = target.is_dir() and not target.is_symlink()
|
||||
if source_is_directory and target_is_directory:
|
||||
deduplicated = 0
|
||||
archived = 0
|
||||
for child in sorted(source.iterdir(), key=lambda path: path.name.casefold()):
|
||||
child_deduplicated, child_archived = _merge_entry(
|
||||
child,
|
||||
target / child.name,
|
||||
source_root=source_root,
|
||||
canonical=canonical,
|
||||
timestamp=timestamp,
|
||||
)
|
||||
deduplicated += child_deduplicated
|
||||
archived += child_archived
|
||||
source.rmdir()
|
||||
return deduplicated, archived
|
||||
|
||||
if not source_is_directory and not target_is_directory and _same_file(source, target):
|
||||
source.unlink()
|
||||
return 1, 0
|
||||
|
||||
relative = source.relative_to(source_root)
|
||||
archived_path = _unique_archive_path(canonical, relative, source_root.name, timestamp)
|
||||
os.replace(source, archived_path)
|
||||
return 0, 1
|
||||
|
||||
|
||||
def _merge_bundle(source: Path, canonical: Path, timestamp: str) -> tuple[int, int]:
|
||||
deduplicated = 0
|
||||
archived = 0
|
||||
for entry in sorted(source.iterdir(), key=lambda path: path.name.casefold()):
|
||||
entry_deduplicated, entry_archived = _merge_entry(
|
||||
entry,
|
||||
canonical / entry.name,
|
||||
source_root=source,
|
||||
canonical=canonical,
|
||||
timestamp=timestamp,
|
||||
)
|
||||
deduplicated += entry_deduplicated
|
||||
archived += entry_archived
|
||||
source.rmdir()
|
||||
return deduplicated, archived
|
||||
|
||||
|
||||
def repair_activity_layout(
|
||||
public: Path,
|
||||
course_id: int,
|
||||
desired: Mapping[int, str],
|
||||
*,
|
||||
assume_locked: bool = False,
|
||||
) -> LayoutRepairResult:
|
||||
"""Move existing bundles to the current sortable key using activity ID identity."""
|
||||
public = public.expanduser().resolve()
|
||||
content_root = _course_content_root(public, course_id)
|
||||
if not content_root.is_dir() or not desired:
|
||||
return LayoutRepairResult(course_id=course_id)
|
||||
|
||||
for activity_id, canonical_key in desired.items():
|
||||
match = ACTIVITY_DIRECTORY_PATTERN.fullmatch(canonical_key)
|
||||
if activity_id <= 0 or match is None or int(match.group(1)) != activity_id:
|
||||
raise MoodleError(
|
||||
f"invalid canonical activity key for course {course_id}, activity {activity_id}: "
|
||||
f"{canonical_key!r}"
|
||||
)
|
||||
|
||||
def perform() -> LayoutRepairResult:
|
||||
by_activity: dict[int, list[Path]] = {}
|
||||
for path in content_root.iterdir():
|
||||
if not path.is_dir() or path.is_symlink():
|
||||
continue
|
||||
activity_id = _activity_id(path)
|
||||
if activity_id is not None:
|
||||
by_activity.setdefault(activity_id, []).append(path)
|
||||
|
||||
rekeyed = 0
|
||||
merged = 0
|
||||
deduplicated = 0
|
||||
archived_conflicts = 0
|
||||
timestamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
|
||||
for activity_id, canonical_key in sorted(desired.items()):
|
||||
if activity_id <= 0:
|
||||
continue
|
||||
canonical = content_root / canonical_key
|
||||
sources = sorted(
|
||||
(path for path in by_activity.get(activity_id, []) if path.name != canonical_key),
|
||||
key=lambda path: path.name.casefold(),
|
||||
)
|
||||
for source in sources:
|
||||
try:
|
||||
if not canonical.exists() and not canonical.is_symlink():
|
||||
os.replace(source, canonical)
|
||||
else:
|
||||
if not canonical.is_dir() or canonical.is_symlink():
|
||||
raise MoodleError(f"canonical activity path is not a directory: {canonical}")
|
||||
duplicate_count, archive_count = _merge_bundle(source, canonical, timestamp)
|
||||
merged += 1
|
||||
deduplicated += duplicate_count
|
||||
archived_conflicts += archive_count
|
||||
rekeyed += 1
|
||||
except MoodleError:
|
||||
raise
|
||||
except OSError as exc:
|
||||
raise MoodleError(
|
||||
f"could not rekey course {course_id} activity {activity_id} "
|
||||
f"from {source.name} to {canonical_key}: {exc}"
|
||||
) from exc
|
||||
return LayoutRepairResult(
|
||||
course_id=course_id,
|
||||
rekeyed=rekeyed,
|
||||
merged=merged,
|
||||
deduplicated=deduplicated,
|
||||
archived_conflicts=archived_conflicts,
|
||||
)
|
||||
|
||||
if assume_locked:
|
||||
return perform()
|
||||
with manifest_lock(public / "courses"):
|
||||
return perform()
|
||||
|
||||
|
||||
def repair_courses_layout(
|
||||
public: Path,
|
||||
courses: Iterable[dict[str, Any]],
|
||||
*,
|
||||
assume_locked: bool = False,
|
||||
) -> list[LayoutRepairResult]:
|
||||
results: list[LayoutRepairResult] = []
|
||||
for course in courses:
|
||||
course_id = int(course.get("id") or 0)
|
||||
if course_id <= 0:
|
||||
continue
|
||||
result = repair_activity_layout(
|
||||
public,
|
||||
course_id,
|
||||
desired_activity_keys(course),
|
||||
assume_locked=assume_locked,
|
||||
)
|
||||
if result.changed:
|
||||
results.append(result)
|
||||
return results
|
||||
|
||||
|
||||
def format_layout_repair(result: LayoutRepairResult) -> str:
|
||||
detail: list[str] = []
|
||||
if result.merged:
|
||||
detail.append(f"merged {result.merged} {'collision' if result.merged == 1 else 'collisions'}")
|
||||
if result.deduplicated:
|
||||
file_label = "file" if result.deduplicated == 1 else "files"
|
||||
detail.append(f"deduplicated {result.deduplicated} identical {file_label}")
|
||||
if result.archived_conflicts:
|
||||
conflict_label = "conflict" if result.archived_conflicts == 1 else "conflicts"
|
||||
detail.append(f"archived {result.archived_conflicts} {conflict_label}")
|
||||
suffix = f" ({', '.join(detail)})" if detail else ""
|
||||
bundle_label = "bundle" if result.rekeyed == 1 else "bundles"
|
||||
return f"Rekeyed {result.rekeyed} activity {bundle_label} for course {result.course_id}{suffix}."
|
||||
+6
-24
@@ -5,14 +5,15 @@ from __future__ import annotations
|
||||
import hashlib
|
||||
import json
|
||||
import mimetypes
|
||||
from contextlib import contextmanager
|
||||
import sys
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Iterable, Iterator
|
||||
from typing import Any, Iterable
|
||||
|
||||
from .catalog import _build_library_catalog
|
||||
from .client import MoodleClient
|
||||
from .constants import LIVE_CLASS_MODULES
|
||||
from .layout import format_layout_repair, manifest_lock as _manifest_lock, repair_courses_layout
|
||||
from .models import FileItem, MoodleError
|
||||
from .paths import (
|
||||
_activity_directory_name,
|
||||
@@ -40,28 +41,6 @@ def _atomic_json(path: Path, value: dict[str, Any]) -> None:
|
||||
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")),
|
||||
@@ -391,9 +370,12 @@ def _catalog_from_manifests(courses_root: Path, now: str) -> dict[str, Any]:
|
||||
|
||||
|
||||
def _write_manifests(public: Path, courses: Iterable[dict[str, Any]], *, remote: bool) -> dict[str, Any]:
|
||||
courses = list(courses)
|
||||
courses_root = public / "courses"
|
||||
now = _utc_now()
|
||||
with _manifest_lock(courses_root):
|
||||
for result in repair_courses_layout(public, courses, assume_locked=True):
|
||||
print(format_layout_repair(result), file=sys.stderr)
|
||||
for course in courses:
|
||||
reconciled = _reconcile_course(public, course)
|
||||
manifest_path = courses_root / str(course["id"]) / "manifest.json"
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||
|
||||
from ravin import Course, FileItem
|
||||
from ravin.layout import format_layout_repair, repair_activity_layout
|
||||
from ravin.models import MoodleError
|
||||
from ravin.scan import scan_offline, scan_remote
|
||||
|
||||
|
||||
class ActivityLayoutTests(unittest.TestCase):
|
||||
def setUp(self) -> None:
|
||||
self.temporary_directory = tempfile.TemporaryDirectory()
|
||||
self.root = Path(self.temporary_directory.name)
|
||||
self.public = self.root / "public"
|
||||
self.content = self.public / "courses" / "51" / "content"
|
||||
|
||||
def tearDown(self) -> None:
|
||||
self.temporary_directory.cleanup()
|
||||
|
||||
def test_rekeys_complete_bundle_by_stable_activity_id(self) -> None:
|
||||
old = self.content / "002--001--5222"
|
||||
media = old / "files" / "Intro01.mp4"
|
||||
transcript = old / "artifacts" / "transcript.fa.txt"
|
||||
media.parent.mkdir(parents=True)
|
||||
transcript.parent.mkdir(parents=True)
|
||||
media.write_bytes(b"video")
|
||||
transcript.write_text("transcript", encoding="utf-8")
|
||||
(old / "artifacts/questions.fa.md").write_text("questions", encoding="utf-8")
|
||||
(old / "artifacts/recording.meta.json").write_text(
|
||||
'{"source":"../files/Intro01.mp4"}',
|
||||
encoding="utf-8",
|
||||
)
|
||||
(old / "files/archive").mkdir()
|
||||
(old / "files/archive/previous.mp4").write_bytes(b"previous")
|
||||
original_mtime = media.stat().st_mtime_ns
|
||||
orphan = self.content / "003--001--9999"
|
||||
orphan.mkdir(parents=True)
|
||||
idless = self.content / "custom-bundle"
|
||||
idless.mkdir()
|
||||
|
||||
result = repair_activity_layout(self.public, 51, {5222: "004--001--5222"})
|
||||
|
||||
canonical = self.content / "004--001--5222"
|
||||
self.assertFalse(old.exists())
|
||||
self.assertEqual((canonical / "files/Intro01.mp4").read_bytes(), b"video")
|
||||
self.assertEqual((canonical / "artifacts/transcript.fa.txt").read_text(), "transcript")
|
||||
self.assertEqual((canonical / "artifacts/questions.fa.md").read_text(), "questions")
|
||||
self.assertTrue((canonical / "artifacts/recording.meta.json").is_file())
|
||||
self.assertEqual((canonical / "files/archive/previous.mp4").read_bytes(), b"previous")
|
||||
self.assertEqual((canonical / "files/Intro01.mp4").stat().st_mtime_ns, original_mtime)
|
||||
self.assertTrue(orphan.is_dir())
|
||||
self.assertTrue(idless.is_dir())
|
||||
self.assertEqual(result.rekeyed, 1)
|
||||
self.assertEqual(result.merged, 0)
|
||||
self.assertEqual(
|
||||
format_layout_repair(result),
|
||||
"Rekeyed 1 activity bundle for course 51.",
|
||||
)
|
||||
|
||||
def test_merges_collisions_with_canonical_priority_and_no_data_loss(self) -> None:
|
||||
canonical = self.content / "004--001--5222"
|
||||
old = self.content / "002--001--5222"
|
||||
older = self.content / "003--009--5222"
|
||||
for directory in (canonical, old, older):
|
||||
(directory / "files").mkdir(parents=True)
|
||||
(canonical / "files/current.mp4").write_bytes(b"current LMS version")
|
||||
(canonical / "files/same.pdf").write_bytes(b"identical")
|
||||
(canonical / "artifacts").mkdir()
|
||||
(canonical / "artifacts/transcript.fa.txt").write_text("canonical transcript", encoding="utf-8")
|
||||
|
||||
(old / "files/current.mp4").write_bytes(b"older version")
|
||||
(old / "files/same.pdf").write_bytes(b"identical")
|
||||
(old / "files/notes.pdf").write_bytes(b"notes")
|
||||
(old / "files/resume.mp4.part").write_bytes(b"partial download")
|
||||
(old / "files/archive").mkdir()
|
||||
(old / "files/archive/previous.mp4").write_bytes(b"previous version")
|
||||
(old / "artifacts").mkdir()
|
||||
(old / "artifacts/transcript.fa.txt").write_text("old transcript", encoding="utf-8")
|
||||
(old / "artifacts/summary.fa.md").write_text("summary", encoding="utf-8")
|
||||
(older / "files/extra.txt").write_text("extra", encoding="utf-8")
|
||||
|
||||
result = repair_activity_layout(self.public, 51, {5222: canonical.name})
|
||||
|
||||
self.assertFalse(old.exists())
|
||||
self.assertFalse(older.exists())
|
||||
self.assertEqual((canonical / "files/current.mp4").read_bytes(), b"current LMS version")
|
||||
self.assertEqual((canonical / "files/notes.pdf").read_bytes(), b"notes")
|
||||
self.assertEqual((canonical / "files/extra.txt").read_text(), "extra")
|
||||
self.assertEqual((canonical / "files/resume.mp4.part").read_bytes(), b"partial download")
|
||||
self.assertEqual((canonical / "files/archive/previous.mp4").read_bytes(), b"previous version")
|
||||
self.assertEqual((canonical / "artifacts/transcript.fa.txt").read_text(), "canonical transcript")
|
||||
self.assertEqual((canonical / "artifacts/summary.fa.md").read_text(), "summary")
|
||||
archived_media = list((canonical / "files/archive").glob("*--current.mp4"))
|
||||
archived_artifact = list((canonical / "artifacts/archive").glob("*--transcript.fa.txt"))
|
||||
self.assertEqual([path.read_bytes() for path in archived_media], [b"older version"])
|
||||
self.assertEqual([path.read_text() for path in archived_artifact], ["old transcript"])
|
||||
self.assertEqual(result.rekeyed, 2)
|
||||
self.assertEqual(result.merged, 2)
|
||||
self.assertEqual(result.deduplicated, 1)
|
||||
self.assertEqual(result.archived_conflicts, 2)
|
||||
|
||||
def test_rejects_unsafe_or_mismatched_canonical_key(self) -> None:
|
||||
(self.content / "002--001--5222").mkdir(parents=True)
|
||||
for key in ("../../outside", "004--001--9999"):
|
||||
with self.subTest(key=key):
|
||||
with self.assertRaisesRegex(MoodleError, "invalid canonical activity key"):
|
||||
repair_activity_layout(self.public, 51, {5222: key})
|
||||
|
||||
def test_offline_scan_repairs_manifest_layout_and_restores_artifact_states(self) -> None:
|
||||
old = self.content / "002--001--5222"
|
||||
media = old / "files/Intro01.mp4"
|
||||
artifacts = old / "artifacts"
|
||||
media.parent.mkdir(parents=True)
|
||||
artifacts.mkdir(parents=True)
|
||||
media.write_bytes(b"video")
|
||||
transcript = artifacts / "transcript.fa.txt"
|
||||
transcript.write_text("transcript", encoding="utf-8")
|
||||
media_stat = media.stat()
|
||||
(artifacts / "transcript.meta.json").write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"source": "../files/Intro01.mp4",
|
||||
"source_size": media_stat.st_size,
|
||||
"source_mtime_ns": media_stat.st_mtime_ns,
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(artifacts / "summary.fa.md").write_text("summary", encoding="utf-8")
|
||||
manifest = self.public / "courses/51/manifest.json"
|
||||
manifest.parent.mkdir(parents=True, exist_ok=True)
|
||||
manifest.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"schema_version": 1,
|
||||
"course": {
|
||||
"id": 51,
|
||||
"fullname": "LPIC",
|
||||
"sections": [
|
||||
{
|
||||
"number": 4,
|
||||
"items": [
|
||||
{
|
||||
"filename": "Intro01.mp4",
|
||||
"activity_type": "resource",
|
||||
"kind": "video",
|
||||
"title": "Intro",
|
||||
"section_number": 4,
|
||||
"activity_position": 1,
|
||||
"activity_id": 5222,
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
},
|
||||
}
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
catalog = scan_offline(self.public, [51])
|
||||
|
||||
canonical = self.content / "004--001--5222"
|
||||
refreshed = json.loads(manifest.read_text(encoding="utf-8"))
|
||||
item = refreshed["course"]["sections"][0]["items"][0]
|
||||
self.assertTrue(canonical.is_dir())
|
||||
self.assertFalse(old.exists())
|
||||
self.assertEqual(item["key"], "004--001--5222")
|
||||
self.assertEqual(item["state"]["download"], "complete")
|
||||
self.assertEqual(item["state"]["transcript"], "complete")
|
||||
self.assertEqual(item["state"]["summary"], "complete")
|
||||
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
|
||||
|
||||
def test_online_scan_repairs_before_catalog_discovers_local_files(self) -> None:
|
||||
old = self.content / "002--001--5222"
|
||||
media = old / "files/Intro01.mp4"
|
||||
media.parent.mkdir(parents=True)
|
||||
media.write_bytes(b"video")
|
||||
|
||||
class FakeClient:
|
||||
site = "https://training.example"
|
||||
|
||||
def list_courses(self):
|
||||
return [Course(51, "LPIC")]
|
||||
|
||||
def list_files(self, _course_id):
|
||||
return [
|
||||
FileItem(
|
||||
51,
|
||||
"Introduction",
|
||||
"Intro",
|
||||
"Intro01.mp4",
|
||||
"https://training.example/pluginfile.php/intro.mp4",
|
||||
"video/mp4",
|
||||
5,
|
||||
section_number=4,
|
||||
activity_id=5222,
|
||||
activity_type="resource",
|
||||
activity_position=1,
|
||||
)
|
||||
]
|
||||
|
||||
def course_structure(self, _course_id):
|
||||
return [
|
||||
{
|
||||
"id": 200,
|
||||
"number": 4,
|
||||
"name": "Introduction",
|
||||
"activities": [
|
||||
{
|
||||
"id": 5222,
|
||||
"position": 1,
|
||||
"name": "Intro",
|
||||
"type": "resource",
|
||||
"url": "https://training.example/mod/resource/view.php?id=5222",
|
||||
}
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
catalog = scan_remote(FakeClient(), self.public, [51])
|
||||
|
||||
canonical = self.content / "004--001--5222"
|
||||
self.assertTrue((canonical / "files/Intro01.mp4").is_file())
|
||||
self.assertFalse(old.exists())
|
||||
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
|
||||
manifest = json.loads((self.public / "courses/51/manifest.json").read_text())
|
||||
item = manifest["course"]["sections"][0]["items"][0]
|
||||
self.assertEqual(item["local_url"], "courses/51/content/004--001--5222/files/Intro01.mp4")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user