From 0a0ce2a62453b7dba875d0aaac1700a2296d2e02 Mon Sep 17 00:00:00 2001 From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Thu, 13 Aug 2026 22:05:29 +0330 Subject: [PATCH] feat: add timestamped public course exports --- .gitignore | 2 + CHANGELOG.md | 12 ++- README.md | 29 ++++++++ pyproject.toml | 2 +- src/ravin/cli.py | 36 ++++++++- src/ravin/constants.py | 2 +- src/ravin/exporter.py | 161 +++++++++++++++++++++++++++++++++++++++++ tests/test_exporter.py | 105 +++++++++++++++++++++++++++ tests/test_ravin.py | 8 ++ 9 files changed, 352 insertions(+), 5 deletions(-) create mode 100644 src/ravin/exporter.py create mode 100644 tests/test_exporter.py diff --git a/.gitignore b/.gitignore index bff65da..323eb9b 100644 --- a/.gitignore +++ b/.gitignore @@ -15,7 +15,9 @@ dist/ downloads/ library/ public/courses/ +public/exports/ public/nginx.local.conf +/courses.zip eggs/ .eggs/ lib/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 02c256b..864a844 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,14 @@ All notable changes to this project will be documented here. +## 0.13.0 - 2026-08-13 + +- Add a local `ravin export` command that creates timestamped archives under `public/exports/` from all scanned courses. +- Exclude current and archived videos by default while retaining other course files and learning artifacts. +- Add `--include-videos`, `--output`, `--public`, and machine-readable `--json` options. +- Build ZIP files atomically with ZIP64 support and skip partial downloads, locks, and platform metadata. +- Keep export destinations outside the course data directory and ignore generated public exports in Git. + ## 0.12.0 - 2026-08-13 - Add per-category missing, partial, stale, and error details to scan output. @@ -14,12 +22,12 @@ All notable changes to this project will be documented here. ## 0.11.0 - 2026-08-13 -- Add a `ravin recording` wizard for attaching local videos to Moodle live-class activities. +[- Add a `ravin recording` wizard for attaching local videos to Moodle live-class activities. - Make imported recordings available to the existing Whisper transcription and Codex summarization pipelines. - Preserve replaced recordings as archived versions and expose current and archived files in the library. - Keep the selected current recording across later online LMS scans with portable local metadata. - Accept pasted interactive file paths containing spaces without requiring shell quoting. - +]() ## 0.10.0 - 2026-08-13 - Track the Moodle-selected resource as current while retaining other local files as archived versions. diff --git a/README.md b/README.md index 4d389eb..74fb4f3 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ ravin transcribe COURSE_ID ravin summarize COURSE_ID ravin questions ravin recording +ravin export ravin serve --open ``` @@ -121,6 +122,32 @@ Empty LMS resource activities that expose no actual file are not counted as down 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. +## Course exports + +Create a timestamped ZIP from every local course: + +```bash +ravin export +``` + +By default, the archive is written to a path such as `public/exports/2026-08-13_14-35-22.zip`. Each run therefore produces a versioned file that can be downloaded directly from `/exports/2026-08-13_14-35-22.zip` when `public/` is your web server's document root. Generated exports are ignored by Git. + +Videos are excluded by default, including archived video versions. The ZIP still contains the course catalog and manifests, documents, compressed attachments, audio, transcripts, summaries, exam questions and attachments, recording metadata, and other non-video course files. Partial downloads and transient lock files are omitted. + +Include current and archived videos when you need a complete backup: + +```bash +ravin export --include-videos +``` + +Choose a different destination with `--output`: + +```bash +ravin export --output ~/Backups/ravin-courses.zip +``` + +The archive always contains a top-level `courses/` directory, so it can be extracted into a compatible `public/` web root. Exports are built beside the destination and installed atomically; an interrupted run does not leave a broken ZIP. The destination must be outside `public/courses/`; use `--output` when you do not want an export exposed by the library server. + ## Exam questions and answers Start the interactive import wizard: @@ -342,6 +369,7 @@ ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language L ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS] ravin questions [COURSE_ID] [ACTIVITY_ID] [QUESTIONS.md] [--file ATTACHMENT ...] ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO] +ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH] ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH] ``` @@ -364,6 +392,7 @@ src/ravin/ ├── summarize.py # resilient Codex CLI study-guide batches ├── questions.py # local exam-question and attachment imports ├── recordings.py # local live-class recording imports +├── exporter.py # atomic course ZIP exports ├── local_files.py # atomic local copies and archived versions ├── wizard.py # shared interactive import helpers ├── migration.py # previous-layout migration diff --git a/pyproject.toml b/pyproject.toml index 9214a83..dc7533b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "ravin-moodle-downloader" -version = "0.12.0" +version = "0.13.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 9f1affb..4ff9a3a 100644 --- a/src/ravin/cli.py +++ b/src/ravin/cli.py @@ -17,6 +17,7 @@ from .auth import ( ) from .client import MoodleClient from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__ +from .exporter import export_courses, format_export_result from .migration import migrate_library_to_public from .models import MoodleError from .questions import format_questions_result, import_questions, questions_wizard @@ -168,6 +169,24 @@ def build_parser() -> argparse.ArgumentParser: recording_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root") recording_parser.add_argument("--json", action="store_true", help="print imported paths as JSON") + export_parser = subparsers.add_parser( + "export", + help="create a ZIP archive of all local course data", + description="Export public/courses as a portable ZIP; videos are excluded unless explicitly included.", + ) + export_parser.add_argument( + "--output", + type=Path, + help="destination ZIP path (default: PUBLIC/exports/YYYY-MM-DD_HH-MM-SS.zip)", + ) + export_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root") + export_parser.add_argument( + "--include-videos", + action="store_true", + help="include current and archived video files (can make the ZIP very large)", + ) + export_parser.add_argument("--json", action="store_true", help="print export details 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") @@ -215,9 +234,24 @@ def main(argv: list[str] | None = None) -> int: return 0 public = getattr(args, "public", Path("public")).expanduser().resolve() - if args.command in {"scan", "download", "transcribe", "summarize", "questions", "recording", "recordings"}: + if args.command in { + "scan", "download", "transcribe", "summarize", "questions", "recording", "recordings", "export", + }: _maybe_migrate(public) + if args.command == "export": + result = export_courses( + public, + args.output, + include_videos=args.include_videos, + progress=None if args.json else lambda message: print(message, file=sys.stderr), + ) + print( + json.dumps(result.to_dict(), ensure_ascii=False, indent=2) + if args.json else format_export_result(result) + ) + return 0 + 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)) diff --git a/src/ravin/constants.py b/src/ravin/constants.py index fdc9ae9..f65cee4 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.12.0" +__version__ = "0.13.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/exporter.py b/src/ravin/exporter.py new file mode 100644 index 0000000..9f0792b --- /dev/null +++ b/src/ravin/exporter.py @@ -0,0 +1,161 @@ +"""Portable ZIP exports of local course data.""" + +from __future__ import annotations + +import mimetypes +import os +import tempfile +import zipfile +from dataclasses import asdict, dataclass +from datetime import datetime +from pathlib import Path +from typing import Any, Callable + +from .models import MoodleError + + +VIDEO_EXTENSIONS = { + ".3gp", ".asf", ".avi", ".divx", ".f4v", ".flv", ".m2ts", ".m4v", + ".mkv", ".mov", ".mp4", ".mpeg", ".mpg", ".mts", ".ogv", ".rm", + ".rmvb", ".ts", ".vob", ".webm", ".wmv", +} +TRANSIENT_NAMES = {".DS_Store", ".manifest.lock"} + + +@dataclass(frozen=True) +class ExportResult: + output: str + courses: int + files: int + source_bytes: int + archive_bytes: int + videos_included: int + videos_skipped: int + skipped_video_bytes: int + + def to_dict(self) -> dict[str, Any]: + return asdict(self) + + +def _is_video(path: Path) -> bool: + mimetype = mimetypes.guess_type(path.name)[0] or "" + return mimetype.startswith("video/") or path.suffix.casefold() in VIDEO_EXTENSIONS + + +def _exportable_files(courses_root: Path) -> list[Path]: + return sorted( + ( + path + for path in courses_root.rglob("*") + if path.is_file() + and not path.is_symlink() + and path.name not in TRANSIENT_NAMES + and not path.name.endswith(".part") + ), + key=lambda path: path.relative_to(courses_root).as_posix().casefold(), + ) + + +def export_courses( + public: Path, + output: Path | None = None, + *, + include_videos: bool = False, + progress: Callable[[str], None] | None = None, +) -> ExportResult: + """Create an atomic ZIP containing all local course data.""" + public = public.expanduser().resolve() + courses_root = (public / "courses").resolve() + if not courses_root.is_dir() or not any(courses_root.glob("*/manifest.json")): + raise MoodleError(f"no local courses found in {courses_root}; run `ravin scan` first") + + if output is None: + timestamp = datetime.now().astimezone().strftime("%Y-%m-%d_%H-%M-%S") + output = public / "exports" / f"{timestamp}.zip" + output = output.expanduser().resolve() + if output.suffix.casefold() != ".zip": + raise MoodleError("export output must use a .zip extension") + try: + output.relative_to(courses_root) + except ValueError: + pass + else: + raise MoodleError("export output must be outside public/courses so it is not exposed by the library server") + if output.exists() and not output.is_file(): + raise MoodleError(f"export output is not a file: {output}") + + candidates = _exportable_files(courses_root) + videos = [path for path in candidates if _is_video(path)] + included = candidates if include_videos else [path for path in candidates if not _is_video(path)] + source_bytes = sum(path.stat().st_size for path in included) + skipped_video_bytes = 0 if include_videos else sum(path.stat().st_size for path in videos) + course_count = sum(1 for _path in courses_root.glob("*/manifest.json")) + if progress: + video_note = "including videos" if include_videos else f"excluding {len(videos)} video(s)" + progress(f"Creating {output.name} from {len(included)} file(s), {video_note}...") + + output.parent.mkdir(parents=True, exist_ok=True) + temporary: Path | None = None + try: + descriptor, temporary_name = tempfile.mkstemp( + prefix=f".{output.name}.", + suffix=".tmp", + dir=output.parent, + ) + os.close(descriptor) + temporary = Path(temporary_name) + with zipfile.ZipFile( + temporary, + mode="w", + compression=zipfile.ZIP_DEFLATED, + compresslevel=6, + allowZip64=True, + strict_timestamps=False, + ) as archive: + for index, path in enumerate(included, start=1): + archive_name = (Path("courses") / path.relative_to(courses_root)).as_posix() + compression = zipfile.ZIP_STORED if _is_video(path) else zipfile.ZIP_DEFLATED + archive.write(path, archive_name, compress_type=compression) + if progress and (index % 100 == 0 or index == len(included)): + progress(f" added {index}/{len(included)} file(s)") + os.replace(temporary, output) + temporary = None + except (OSError, zipfile.BadZipFile, RuntimeError) as exc: + raise MoodleError(f"could not create course export: {exc}") from exc + finally: + if temporary is not None: + temporary.unlink(missing_ok=True) + + return ExportResult( + output=str(output), + courses=course_count, + files=len(included), + source_bytes=source_bytes, + archive_bytes=output.stat().st_size, + videos_included=len(videos) if include_videos else 0, + videos_skipped=0 if include_videos else len(videos), + skipped_video_bytes=skipped_video_bytes, + ) + + +def _format_size(size: int) -> str: + value = float(size) + for unit in ("B", "KiB", "MiB", "GiB", "TiB"): + if value < 1024 or unit == "TiB": + return f"{value:.1f} {unit}" + value /= 1024 + return f"{size} B" + + +def format_export_result(result: ExportResult) -> str: + video_detail = ( + f"included {result.videos_included} video(s)" + if result.videos_included + else f"skipped {result.videos_skipped} video(s) ({_format_size(result.skipped_video_bytes)})" + ) + return ( + f"Created {result.output}\n" + f"{result.courses} course(s), {result.files} file(s), {video_detail}.\n" + f"Archive size: {_format_size(result.archive_bytes)} " + f"from {_format_size(result.source_bytes)} of included data." + ) diff --git a/tests/test_exporter.py b/tests/test_exporter.py new file mode 100644 index 0000000..c52ebda --- /dev/null +++ b/tests/test_exporter.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import json +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from re import fullmatch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +from ravin.exporter import export_courses, format_export_result +from ravin.models import MoodleError + + +class CourseExportTests(unittest.TestCase): + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory() + self.root = Path(self.temporary_directory.name) + self.public = self.root / "public" + courses = self.public / "courses" + (courses / "44" / "content" / "001--001--100" / "files" / "archive").mkdir(parents=True) + (courses / "51").mkdir(parents=True) + (courses / "catalog.json").write_text('{"courses": []}\n', encoding="utf-8") + for course_id in (44, 51): + (courses / str(course_id) / "manifest.json").write_text( + json.dumps({"course": {"id": course_id}}), + encoding="utf-8", + ) + bundle = courses / "44" / "content" / "001--001--100" + (bundle / "files" / "notes.pdf").write_bytes(b"pdf notes") + (bundle / "files" / "lesson.mp4").write_bytes(b"current video") + (bundle / "files" / "archive" / "old.MKV").write_bytes(b"archived video") + (bundle / "files" / "audio.ogg").write_bytes(b"audio remains included") + (bundle / "files" / "unfinished.mp4.part").write_bytes(b"partial") + (bundle / "artifacts").mkdir() + (bundle / "artifacts" / "transcript.fa.txt").write_text("transcript", encoding="utf-8") + (courses / ".manifest.lock").write_text("", encoding="utf-8") + (courses / ".DS_Store").write_bytes(b"metadata") + + def tearDown(self) -> None: + self.temporary_directory.cleanup() + + def archive_names(self, path: Path) -> set[str]: + with zipfile.ZipFile(path) as archive: + self.assertIsNone(archive.testzip()) + return set(archive.namelist()) + + def test_default_export_excludes_videos_but_keeps_course_data(self) -> None: + result = export_courses(self.public) + output = Path(result.output) + names = self.archive_names(output) + + self.assertEqual(output.parent, (self.public / "exports").resolve()) + self.assertIsNotNone(fullmatch(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.zip", output.name)) + self.assertIn("courses/catalog.json", names) + self.assertIn("courses/44/manifest.json", names) + self.assertIn("courses/51/manifest.json", names) + self.assertIn("courses/44/content/001--001--100/files/notes.pdf", names) + self.assertIn("courses/44/content/001--001--100/files/audio.ogg", names) + self.assertIn("courses/44/content/001--001--100/artifacts/transcript.fa.txt", names) + self.assertNotIn("courses/44/content/001--001--100/files/lesson.mp4", names) + self.assertNotIn("courses/44/content/001--001--100/files/archive/old.MKV", names) + self.assertFalse(any(name.endswith(".part") for name in names)) + self.assertFalse(any(name.endswith(".DS_Store") or name.endswith(".manifest.lock") for name in names)) + self.assertEqual(result.courses, 2) + self.assertEqual(result.videos_skipped, 2) + self.assertEqual(result.videos_included, 0) + self.assertIn("skipped 2 video(s)", format_export_result(result)) + + def test_include_videos_exports_current_and_archived_videos(self) -> None: + output = self.root / "complete-courses.zip" + + result = export_courses(self.public, output, include_videos=True) + names = self.archive_names(output) + + self.assertIn("courses/44/content/001--001--100/files/lesson.mp4", names) + self.assertIn("courses/44/content/001--001--100/files/archive/old.MKV", names) + self.assertEqual(result.videos_included, 2) + self.assertEqual(result.videos_skipped, 0) + + def test_export_atomically_replaces_an_existing_zip(self) -> None: + output = self.root / "courses.zip" + output.write_bytes(b"not a zip") + + export_courses(self.public, output) + + self.assertIn("courses/catalog.json", self.archive_names(output)) + self.assertEqual(list(self.root.glob(".courses.zip.*.tmp")), []) + + def test_rejects_output_inside_public_courses(self) -> None: + with self.assertRaisesRegex(MoodleError, "outside public/courses"): + export_courses(self.public, self.public / "courses" / "export.zip") + + def test_requires_scanned_courses_and_zip_extension(self) -> None: + empty_public = self.root / "empty" + with self.assertRaisesRegex(MoodleError, "run `ravin scan` first"): + export_courses(empty_public, self.root / "empty.zip") + with self.assertRaisesRegex(MoodleError, r"\.zip extension"): + export_courses(self.public, self.root / "courses.backup") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_ravin.py b/tests/test_ravin.py index ff03b7e..1db7637 100644 --- a/tests/test_ravin.py +++ b/tests/test_ravin.py @@ -119,6 +119,14 @@ class ParserTests(unittest.TestCase): self.assertIsNone(recordings_wizard.course_id) self.assertIsNone(recordings_wizard.activity_id) self.assertIsNone(recordings_wizard.video) + export = build_parser().parse_args( + ["export", "--output", "backup.zip", "--include-videos", "--public", "site"] + ) + self.assertEqual(export.output, Path("backup.zip")) + self.assertTrue(export.include_videos) + self.assertEqual(export.public, Path("site")) + default_export = build_parser().parse_args(["export"]) + self.assertIsNone(default_export.output) serve = build_parser().parse_args(["serve", "--port", "9000"]) self.assertEqual(serve.port, 9000)