From c50b06297c191b81f79ae4707dfaa3ed46a41bee Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 13 Aug 2026 21:24:04 +0330 Subject: [PATCH] feat: add actionable scan output and reconcile file counts --- CHANGELOG.md | 10 +++ README.md | 4 +- pyproject.toml | 2 +- src/ravin/cli.py | 6 +- src/ravin/client.py | 6 ++ src/ravin/constants.py | 2 +- src/ravin/paths.py | 23 +++++++ src/ravin/scan.py | 150 +++++++++++++++++++++++++++++++++++------ tests/test_ravin.py | 118 +++++++++++++++++++++++++++++++- 9 files changed, 294 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 00a8845..02c256b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,16 @@ All notable changes to this project will be documented here. +## 0.12.0 - 2026-08-13 + +- Add per-category missing, partial, stale, and error details to scan output. +- Print ordered next-step commands for downloading, transcribing, summarizing, and importing exam questions. +- Report missing live-class recordings as optional follow-up work. +- Exclude empty LMS resource activities from downloadable-file totals. +- Recognize files written by the previous mojibake filename bug without renaming or modifying course content. +- Repair future UTF-8 `Content-Disposition` filenames and avoid redownloading known legacy paths. +- Replace the misleading download total with a checked-entry count followed by reconciled course status. + ## 0.11.0 - 2026-08-13 - Add a `ravin recording` wizard for attaching local videos to Moodle live-class activities. diff --git a/README.md b/README.md index f622ae4..4d389eb 100644 --- a/README.md +++ b/README.md @@ -115,7 +115,9 @@ artifacts/ └── questions.fa.md ``` -The scanner reports each applicable file, transcript, summary, and assessment as `missing`, `partial`, `complete`, `stale`, or `error`. Non-applicable states are recorded as `not_applicable`. Transcript freshness is checked against its source file metadata; summary freshness is checked against the transcript hash. +The scanner reports each applicable file, transcript, summary, and assessment as `missing`, `partial`, `complete`, `stale`, or `error`. Each course includes an ordered **Next** section with copyable commands for downloads, transcription, summaries, and exam questions; missing live-class recordings are shown separately as optional work. Non-applicable states are recorded as `not_applicable`. Transcript freshness is checked against its source file metadata; summary freshness is checked against the transcript hash. + +Empty LMS resource activities that expose no actual file are not counted as downloads. Older files saved with broken UTF-8 header names are recognized in place without renaming or altering their contents. After `ravin download`, the command says how many LMS entries it checked and prints the same reconciled status and next actions instead of claiming every existing file was newly downloaded. The downloader updates the course manifest after every completed file. A final offline scan reconciles all totals, so an interrupted run still retains useful progress. diff --git a/pyproject.toml b/pyproject.toml index db76b85..9214a83 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ravin-moodle-downloader" -version = "0.11.0" +version = "0.12.0" description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials" readme = "README.md" requires-python = ">=3.10" diff --git a/src/ravin/cli.py b/src/ravin/cli.py index 05a71a2..9f1affb 100644 --- a/src/ravin/cli.py +++ b/src/ravin/cli.py @@ -346,11 +346,13 @@ def main(argv: list[str] | None = None) -> int: ) update_download_state(public, item, path) downloaded.append(str(path)) - scan_offline(public, [args.course_id]) + catalog = 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) into {public / 'courses' / str(args.course_id)}") + print(f"Checked {len(downloaded)} LMS file entries in {public / 'courses' / str(args.course_id)}") + print() + print(format_scan(catalog)) return 0 except (MoodleError, KeyboardInterrupt) as exc: if isinstance(exc, KeyboardInterrupt): diff --git a/src/ravin/client.py b/src/ravin/client.py index 7bd7e25..6a2c03f 100644 --- a/src/ravin/client.py +++ b/src/ravin/client.py @@ -22,6 +22,7 @@ from .paths import ( _clean_name, _filename_from_headers, _is_cloudflare_challenge, + _legacy_mojibake_name, _unique, ) @@ -462,6 +463,11 @@ class MoodleClient: if destination.exists() and not overwrite: if item.filesize is None or destination.stat().st_size == item.filesize: return destination + legacy_name = _legacy_mojibake_name(suggested_filename, activity) + legacy_destination = directory / legacy_name if legacy_name else None + if legacy_destination and legacy_destination.exists() and not overwrite: + if item.filesize is None or legacy_destination.stat().st_size == item.filesize: + return legacy_destination temporary = destination.with_name(destination.name + ".part") if overwrite: temporary.unlink(missing_ok=True) diff --git a/src/ravin/constants.py b/src/ravin/constants.py index 82ddf15..fdc9ae9 100644 --- a/src/ravin/constants.py +++ b/src/ravin/constants.py @@ -5,7 +5,7 @@ from pathlib import Path DEFAULT_SITE = "https://training.ravinacademy.com" DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/" -__version__ = "0.11.0" +__version__ = "0.12.0" USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)" DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"} LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"} diff --git a/src/ravin/paths.py b/src/ravin/paths.py index 7e42cb2..4464b25 100644 --- a/src/ravin/paths.py +++ b/src/ravin/paths.py @@ -106,9 +106,32 @@ def _filename_from_headers(headers: Any, url: str, fallback: str) -> str: content_type = headers.get_content_type() if hasattr(headers, "get_content_type") else "" extension = mimetypes.guess_extension(content_type) or "" name = fallback + extension + name = _repair_utf8_header_name(name) return _clean_name(name, fallback) +def _repair_utf8_header_name(value: str) -> str: + """Repair UTF-8 bytes that an HTTP header exposed as Latin-1 text.""" + suspicious = any("\x80" <= character <= "\x9f" for character in value) + suspicious = suspicious or any(marker in value for marker in ("Ã", "Â", "Ø", "Ù", "Û", "Ú", "Ð", "Ñ")) + if not suspicious: + return value + try: + return value.encode("latin-1").decode("utf-8") + except (UnicodeEncodeError, UnicodeDecodeError): + return value + + +def _legacy_mojibake_name(value: str, fallback: str = "file") -> str | None: + """Return the exact filename produced by older broken header decoding.""" + try: + mojibake = value.encode("utf-8").decode("latin-1") + except (UnicodeEncodeError, UnicodeDecodeError): + return None + cleaned = _clean_name(mojibake, fallback) + return cleaned if cleaned != value else None + + def _unique(items: Iterable[FileItem]) -> list[FileItem]: result: list[FileItem] = [] seen: set[str] = set() diff --git a/src/ravin/scan.py b/src/ravin/scan.py index 27c33a1..8c35424 100644 --- a/src/ravin/scan.py +++ b/src/ravin/scan.py @@ -19,6 +19,7 @@ from .paths import ( _clean_name, _course_content_root, _discover_artifacts, + _legacy_mojibake_name, _read_json_object, _relative_browser_path, ) @@ -176,10 +177,17 @@ def _download_state(activity_directory: Path, item: dict[str, Any]) -> tuple[str if expected_size is not None and int(expected_size) != final.stat().st_size: return "error", final return "complete", final + legacy_name = _legacy_mojibake_name(filename, "file") if filename else None + legacy = files_directory / legacy_name if legacy_name else None + if legacy and legacy.is_file(): + expected_size = item.get("remote_size") + if expected_size is not None and int(expected_size) != legacy.stat().st_size: + return "error", legacy + return "complete", legacy 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"}: + if filename: return "missing", None return "not_applicable", None @@ -232,11 +240,17 @@ 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] = {} + category_states = ("complete", "missing", "partial", "stale", "error") + + def category_counts() -> dict[str, int]: + return {"total": 0, **{state: 0 for state in category_states}} + state_counts = { - "downloads": {"complete": 0, "total": 0}, - "transcripts": {"complete": 0, "total": 0}, - "summaries": {"complete": 0, "total": 0}, - "assessments": {"complete": 0, "total": 0}, + "downloads": category_counts(), + "transcripts": category_counts(), + "summaries": category_counts(), + "assessments": category_counts(), + "recordings": category_counts(), "partial": 0, "stale": 0, "errors": 0, @@ -249,6 +263,7 @@ 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" + recording_applicable = item.get("activity_type") in LIVE_CLASS_MODULES transcript_state = _artifact_state( activity_directory, "transcript", @@ -303,15 +318,19 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: item["local_url"] = None if download_state != "not_applicable": state_counts["downloads"]["total"] += 1 - state_counts["downloads"]["complete"] += int(download_state == "complete") + state_counts["downloads"][download_state] += 1 if media_applicable: state_counts["transcripts"]["total"] += 1 - state_counts["transcripts"]["complete"] += int(transcript_state == "complete") + state_counts["transcripts"][transcript_state] += 1 state_counts["summaries"]["total"] += 1 - state_counts["summaries"]["complete"] += int(summary_state == "complete") + state_counts["summaries"][summary_state] += 1 if assessment_applicable: state_counts["assessments"]["total"] += 1 - state_counts["assessments"]["complete"] += int(questions_state == "complete") + state_counts["assessments"][questions_state] += 1 + if recording_applicable: + recording_state = download_state if download_state != "not_applicable" else "missing" + state_counts["recordings"]["total"] += 1 + state_counts["recordings"][recording_state] += 1 state_counts["partial"] += int(download_state == "partial") state_counts["stale"] += sum(value == "stale" for value in (transcript_state, summary_state)) state_counts["errors"] += sum( @@ -327,7 +346,13 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]: "downloaded_count": state_counts["downloads"]["complete"], "downloaded_bytes": downloaded_bytes, "type_counts": type_counts, - "states": state_counts, + "states": { + key: ( + {state: value for state, value in counts.items() if state in {"total", "complete"} or value} + if isinstance(counts, dict) else counts + ) + for key, counts in state_counts.items() + }, } ) return course @@ -447,6 +472,7 @@ def scan_output(catalog: dict[str, Any]) -> list[dict[str, Any]]: "transcripts": course.get("states", {}).get("transcripts", {}), "summaries": course.get("states", {}).get("summaries", {}), "assessments": course.get("states", {}).get("assessments", {}), + "recordings": course.get("states", {}).get("recordings", {}), "partial": course.get("states", {}).get("partial", 0), "stale": course.get("states", {}).get("stale", 0), "errors": course.get("states", {}).get("errors", 0), @@ -458,24 +484,106 @@ def scan_output(catalog: dict[str, Any]) -> list[dict[str, Any]]: def format_scan(catalog: dict[str, Any]) -> str: blocks = [] for course in scan_output(catalog): - def count(name: str) -> str: + def count(name: str, label: str = "complete") -> str: state = course[name] - return f"{int(state.get('complete') or 0):>3} / {int(state.get('total') or 0):<3} complete" + complete = int(state.get("complete") or 0) + total = int(state.get("total") or 0) + details = [ + f"{int(state.get(value) or 0)} {value}" + for value in ("missing", "partial", "stale", "error") + if int(state.get(value) or 0) + ] + suffix = f" · {', '.join(details)}" if details else "" + return f"{complete:>3} / {total:<3} {label}{suffix}" + + actions: list[tuple[str, str]] = [] + + def pending(name: str) -> int: + state = course[name] + return max(int(state.get("total") or 0) - int(state.get("complete") or 0), 0) + + def quantity(value: int, singular: str, plural: str | None = None) -> str: + return f"{value} {singular if value == 1 else (plural or singular + 's')}" + + course_id = int(course["id"] or 0) + if pending("downloads"): + actions.append( + ( + f"ravin download {course_id}", + f"fetch or repair {quantity(pending('downloads'), 'course file')}", + ) + ) + if pending("transcripts"): + actions.append( + ( + f"ravin transcribe {course_id}", + f"create or refresh {quantity(pending('transcripts'), 'transcript')}", + ) + ) + if pending("summaries"): + actions.append( + ( + f"ravin summarize {course_id}", + f"create or refresh {quantity(pending('summaries'), 'summary', 'summaries')}", + ) + ) + if pending("assessments"): + actions.append( + ( + f"ravin questions {course_id}", + f"add questions for {quantity(pending('assessments'), 'assessment')}", + ) + ) + optional_actions: list[tuple[str, str]] = [] + if pending("recordings"): + optional_actions.append( + ( + f"ravin recording {course_id}", + f"attach a video to {quantity(pending('recordings'), 'live class', 'live classes')}", + ) + ) + + next_lines = [""] + if actions: + next_lines.append("Next:") + next_lines.extend( + f" {index}. {command} # {description}" + for index, (command, description) in enumerate(actions, start=1) + ) + elif optional_actions: + next_lines.append("Next (optional):") + else: + next_lines.append("Next:") + next_lines.append(" Nothing — all available course work is complete.") + if optional_actions: + if actions: + next_lines.extend(("", "Optional:")) + next_lines.extend( + f" {command} # {description}" + for command, description in optional_actions + ) + + status_lines = [ + f"Downloads {count('downloads')}", + f"Transcripts {count('transcripts')}", + f"Summaries {count('summaries')}", + f"Assessments {count('assessments')}", + ] + if int(course["recordings"].get("total") or 0): + status_lines.append(f"Recordings {count('recordings', 'attached')} (optional)") + status_lines.append( + f"Issues {course['partial']} partial · {course['stale']} stale · {course['errors']} errors" + ) 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']}", - ) + *status_lines, + *next_lines, + ] ) ) return "\n\n".join(blocks) diff --git a/tests/test_ravin.py b/tests/test_ravin.py index 6ba6c99..ff03b7e 100644 --- a/tests/test_ravin.py +++ b/tests/test_ravin.py @@ -34,7 +34,7 @@ from ravin.paths import ( _is_cloudflare_challenge, _unique, ) -from ravin.scan import scan_offline, scan_remote +from ravin.scan import format_scan, scan_offline, scan_remote class _FakeResponse: @@ -281,6 +281,12 @@ class ParserTests(unittest.TestCase): headers["Content-Disposition"] = "attachment; filename*=UTF-8''lesson%201.mp4" self.assertEqual(_filename_from_headers(headers, "https://x/file.php/1", "lesson"), "lesson 1.mp4") + def test_filename_repairs_utf8_exposed_as_latin1(self): + headers = email.message.Message() + expected = "برنامه زمانبندی.pdf" + headers["Content-Disposition"] = f'attachment; filename="{expected.encode("utf-8").decode("latin-1")}"' + self.assertEqual(_filename_from_headers(headers, "https://x/file.php/1", "lesson"), expected) + def test_sanitizes_names_and_deduplicates_files(self): self.assertEqual(_clean_name('Week 1: Intro/Setup?'), "Week 1_ Intro_Setup_") self.assertEqual(_activity_directory_name(17, 2, 5201), "017--002--5201") @@ -489,6 +495,91 @@ class ParserTests(unittest.TestCase): self.assertEqual(downloaded.read_bytes(), b"replacement video") self.assertEqual(old_file.read_bytes(), b"old video preserved") + def test_offline_scan_recognizes_legacy_mojibake_and_ignores_empty_resources(self): + with tempfile.TemporaryDirectory() as directory: + output = Path(directory) / "public" + activity = output / "courses" / "51" / "content" / "001--001--5685" + expected = "برنامه زمانبندی.pdf" + legacy = _clean_name(expected.encode("utf-8").decode("latin-1"), "file") + downloaded = activity / "files" / legacy + downloaded.parent.mkdir(parents=True) + downloaded.write_bytes(b"schedule") + manifest_path = output / "courses" / "51" / "manifest.json" + manifest_path.write_text( + json.dumps( + { + "schema_version": 1, + "course": { + "id": 51, + "fullname": "LPIC", + "sections": [{ + "number": 1, + "items": [ + { + "filename": expected, + "activity_type": "resource", + "kind": "document", + "title": "Schedule", + "section_number": 1, + "activity_position": 1, + "activity_id": 5685, + }, + { + "filename": "", + "activity_type": "resource", + "kind": "resource", + "title": "Empty resource", + "section_number": 1, + "activity_position": 2, + "activity_id": 5686, + }, + ], + }], + }, + } + ), + encoding="utf-8", + ) + + catalog = scan_offline(output, [51]) + + refreshed = json.loads(manifest_path.read_text(encoding="utf-8")) + first, second = refreshed["course"]["sections"][0]["items"] + self.assertEqual(first["state"]["download"], "complete") + self.assertIsNotNone(first["local_url"]) + self.assertEqual(second["state"]["download"], "not_applicable") + self.assertEqual(refreshed["course"]["states"]["downloads"], {"total": 1, "complete": 1}) + self.assertIn("Downloads 1 / 1 complete", format_scan(catalog)) + + def test_scan_output_lists_state_details_and_ordered_next_commands(self): + catalog = { + "courses": [{ + "id": 51, + "fullname": "LPIC", + "section_count": 2, + "activity_count": 10, + "states": { + "downloads": {"total": 8, "complete": 7, "missing": 1}, + "transcripts": {"total": 6, "complete": 4, "missing": 1, "stale": 1}, + "summaries": {"total": 6, "complete": 0, "missing": 6}, + "assessments": {"total": 1, "complete": 0, "missing": 1}, + "recordings": {"total": 2, "complete": 1, "missing": 1}, + "partial": 0, + "stale": 1, + "errors": 0, + }, + }] + } + + output = format_scan(catalog) + + self.assertIn("Downloads 7 / 8 complete · 1 missing", output) + self.assertIn("Transcripts 4 / 6 complete · 1 missing, 1 stale", output) + self.assertLess(output.index("ravin download 51"), output.index("ravin transcribe 51")) + self.assertLess(output.index("ravin transcribe 51"), output.index("ravin summarize 51")) + self.assertIn("ravin questions 51", output) + self.assertIn("ravin recording 51", output) + def test_changed_same_name_download_archives_previous_file(self): response = _FakeResponse([b"new version"]) client = _FakeDownloadClient([response]) @@ -516,6 +607,31 @@ class ParserTests(unittest.TestCase): self.assertEqual(len(archived), 1) self.assertEqual(archived[0].read_bytes(), b"old") + def test_download_reuses_legacy_mojibake_path_without_requesting_it_again(self): + expected = "برنامه زمانبندی.pdf" + legacy = _clean_name(expected.encode("utf-8").decode("latin-1"), "file") + client = _FakeDownloadClient([]) + item = FileItem( + 51, + "Course files", + "Schedule", + expected, + "https://training.example/file.pdf", + section_number=1, + activity_id=5685, + activity_position=1, + ) + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + destination = root / "courses" / "51" / "content" / "001--001--5685" / "files" / legacy + destination.parent.mkdir(parents=True) + destination.write_bytes(b"schedule") + + reused = client.download(item, root) + + self.assertEqual(reused, destination) + self.assertEqual(client.request_headers, []) + 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"