feat: add live class recording import wizard

This commit is contained in:
Meghdad committed 2026-08-13 17:12:11 +03:30
1 parent 3869d94cfe
commit 26ba7367d9
14 files changed
+670 -107

No files matched your search

+8
View File
@@ -2,6 +2,14 @@
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.
- 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.
+30
View File
@@ -41,6 +41,7 @@ ravin download COURSE_ID
ravin transcribe COURSE_ID
ravin summarize COURSE_ID
ravin questions
ravin recording
ravin serve --open
```
@@ -158,6 +159,31 @@ ravin questions 44 5679 revised-questions.fa.md
The import is local and requires no LMS login. Files are written atomically, the original attachment names are preserved, and the course manifest is refreshed immediately so the library exposes the exam under its **Questions** button.
## Live-class recordings
Add a video you recorded or received for a Moodle live-class activity with:
```bash
ravin recording
```
The wizard lists courses with live classes, lets you select the class, and prompts for the local video. You can paste or drag a path into the terminal, including an unquoted path containing spaces. For scripting, provide all values directly:
```bash
ravin recording 44 5097 ~/Downloads/group-a-class.mp4
```
The video is copied into the live class's ordered activity bundle and appears in the library as its current playable file. Re-importing the same filename preserves the previous copy under `files/archive/`; importing a differently named recording keeps the previous file as an archived version. The selected current recording survives later online scans.
Imported recordings use the normal media pipeline:
```bash
ravin transcribe 44
ravin summarize 44
```
If a recording is replaced, any transcript and summary generated from the older version are marked stale and will be regenerated by those commands.
## Whisper transcription
After downloading a course, transcribe its video and audio in LMS order:
@@ -313,6 +339,7 @@ ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH]
ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE]
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 serve [--host ADDRESS] [--port PORT] [--open] [--public PATH]
```
@@ -334,6 +361,9 @@ src/ravin/
├── transcribe.py # resilient manifest-driven Whisper batches
├── summarize.py # resilient Codex CLI study-guide batches
├── questions.py # local exam-question and attachment imports
├── recordings.py # local live-class recording imports
├── local_files.py # atomic local copies and archived versions
├── wizard.py # shared interactive import helpers
├── migration.py # previous-layout migration
├── server.py # local range-aware HTTP server
└── models.py # shared value objects and errors
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ravin-moodle-downloader"
version = "0.10.0"
version = "0.11.0"
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
readme = "README.md"
requires-python = ">=3.10"
+30 -7
View File
@@ -10,10 +10,11 @@ from pathlib import Path
from typing import Any, Iterable
from .client import MoodleClient
from .constants import LIVE_CLASS_MODULES
from .models import FileItem, MoodleError
from .paths import (
_activity_directory_name, _activity_root, _clean_name, _course_content_root,
_discover_artifacts, _relative_browser_path,
_discover_artifacts, _read_json_object, _relative_browser_path,
)
@@ -29,9 +30,9 @@ def _format_size(size: int | None) -> str:
return str(size)
def _resource_kind(item: FileItem) -> str:
mimetype = item.mimetype.casefold()
suffix = Path(item.filename).suffix.casefold()
def _media_kind(filename: str, mimetype: str = "") -> str:
mimetype = mimetype.casefold()
suffix = Path(filename).suffix.casefold()
if mimetype.startswith("video/") or suffix in {".mp4", ".mkv", ".webm", ".mov", ".m4v"}:
return "video"
if mimetype.startswith("audio/") or suffix in {".mp3", ".m4a", ".wav", ".ogg", ".flac"}:
@@ -47,6 +48,10 @@ def _resource_kind(item: FileItem) -> str:
return "file"
def _resource_kind(item: FileItem) -> str:
return _media_kind(item.filename, item.mimetype)
def _local_resource(item: FileItem, library: Path) -> tuple[str, Path | None]:
directory = _activity_root(library, item) / "files"
expected = directory / _clean_name(item.filename, _clean_name(item.activity, "activity"))
@@ -84,7 +89,18 @@ def _local_activity_record(
] if files_directory.is_dir() else []
if not files and not (directory / "artifacts").is_dir():
return None
return {"files": files}, directory
metadata = _read_json_object(directory / "artifacts" / "recording.meta.json")
current: str | None = None
source = metadata.get("source")
if isinstance(source, str):
candidate = (directory / "artifacts" / source).resolve()
try:
candidate.relative_to(directory.resolve())
except ValueError:
candidate = Path()
if candidate.is_file():
current = candidate.relative_to(directory.resolve()).as_posix()
return {"files": files, "current": current}, directory
def _build_library_catalog(
@@ -205,9 +221,16 @@ def _build_library_catalog(
for relative in local_metadata.get("files", [])
if local_directory and (local_directory / str(relative)).is_file()
]
local_path = local_files[0] if local_files else None
current_relative = local_metadata.get("current")
current_path = local_directory / str(current_relative) if local_directory and current_relative else None
local_path = current_path if current_path and current_path.is_file() else (local_files[0] if local_files else None)
local_bytes = local_path.stat().st_size if local_path else 0
local_kind = "assessment" if activity_type == "quiz" and local_activity else type_names.get(activity_type, "activity")
if activity_type == "quiz" and local_activity:
local_kind = "assessment"
elif activity_type in LIVE_CLASS_MODULES and local_path:
local_kind = _media_kind(local_path.name, mimetypes.guess_type(local_path.name)[0] or "")
else:
local_kind = type_names.get(activity_type, "activity")
if local_path:
downloaded_count += 1
downloaded_bytes += local_bytes
+28 -1
View File
@@ -20,6 +20,7 @@ from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE,
from .migration import migrate_library_to_public
from .models import MoodleError
from .questions import format_questions_result, import_questions, questions_wizard
from .recordings import format_recording_result, import_recording, recording_wizard
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
from .server import _serve_library
from .summarize import SummaryOptions, format_summary_result, summarize_courses
@@ -155,6 +156,18 @@ def build_parser() -> argparse.ArgumentParser:
questions_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
questions_parser.add_argument("--json", action="store_true", help="print imported paths as JSON")
recording_parser = subparsers.add_parser(
"recording",
aliases=["recordings"],
help="interactively add a local recording to a live class",
description="Add a video recording with a course-and-live-class wizard; all values are optional.",
)
recording_parser.add_argument("course_id", nargs="?", type=int, help="course containing the live class")
recording_parser.add_argument("activity_id", nargs="?", type=int, help="Moodle live-class activity ID")
recording_parser.add_argument("video", nargs="?", type=Path, help="local video recording")
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")
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")
@@ -202,7 +215,7 @@ 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"}:
if args.command in {"scan", "download", "transcribe", "summarize", "questions", "recording", "recordings"}:
_maybe_migrate(public)
if args.command == "scan" and args.offline:
@@ -289,6 +302,20 @@ def main(argv: list[str] | None = None) -> int:
)
return 0
if args.command in {"recording", "recordings"}:
course_id, activity_id, recording_path = recording_wizard(
public,
args.course_id,
args.activity_id,
args.video,
)
result = import_recording(public, course_id, activity_id, recording_path)
print(
json.dumps(result.to_dict(), ensure_ascii=False, indent=2)
if args.json else format_recording_result(result)
)
return 0
args.env_values = _load_env_file(args.env_file)
if args.command == "login":
_client, mode = _authenticate_browser_session(args)
+2 -21
View File
@@ -4,9 +4,7 @@ import http.client
import http.cookiejar
import json
import mimetypes
import os
import re
import shutil
import sys
import time
import urllib.error
@@ -16,6 +14,7 @@ from pathlib import Path
from typing import Any
from .constants import DOWNLOADABLE_MODULES, USER_AGENT
from .local_files import archive_existing_file
from .models import Course, FileItem, MoodleError
from .parsers import _CourseStructureParser, _FormParser, _LinkParser, _parse_moodle_config
from .paths import (
@@ -26,24 +25,6 @@ from .paths import (
_unique,
)
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,
@@ -560,7 +541,7 @@ class MoodleClient:
f"connection closed early at {downloaded} of {expected_total} bytes"
)
if destination.exists():
archived = _archive_existing_download(destination)
archived = archive_existing_file(destination)
print(f" archived previous version as {archived.name}", file=sys.stderr)
temporary.replace(destination)
if sys.stderr.isatty():
+2 -1
View File
@@ -5,9 +5,10 @@ from pathlib import Path
DEFAULT_SITE = "https://training.ravinacademy.com"
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
__version__ = "0.10.0"
__version__ = "0.11.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
DEFAULT_ENV_FILE = Path.cwd() / ".env"
ENV_KEYS = {
"username": "RAVIN_USERNAME",
+52
View File
@@ -0,0 +1,52 @@
"""Safe local file installation and version preservation."""
from __future__ import annotations
import os
import shutil
import tempfile
import time
from pathlib import Path
def atomic_copy(source: Path, destination: Path) -> None:
"""Copy a local file into place without exposing a partial destination."""
destination.parent.mkdir(parents=True, exist_ok=True)
if source.resolve() == destination.resolve():
os.chmod(destination, 0o644)
return
temporary_path: Path | None = None
try:
with source.open("rb") as input_file, tempfile.NamedTemporaryFile(
mode="wb",
dir=destination.parent,
prefix=f".{destination.name}.",
suffix=".tmp",
delete=False,
) as output_file:
shutil.copyfileobj(input_file, output_file, length=1024 * 1024)
output_file.flush()
os.fsync(output_file.fileno())
temporary_path = Path(output_file.name)
os.chmod(temporary_path, 0o644)
os.replace(temporary_path, destination)
finally:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
def archive_existing_file(path: Path) -> Path:
"""Preserve a file under its activity's archive directory."""
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
+10 -75
View File
@@ -3,18 +3,16 @@
from __future__ import annotations
import mimetypes
import os
import shlex
import shutil
import sys
import tempfile
from dataclasses import asdict, dataclass
from pathlib import Path
from typing import Any, Callable, TextIO
from .local_files import atomic_copy
from .models import MoodleError
from .paths import _activity_directory_name, _clean_name, _read_json_object
from .scan import _atomic_json, _manifest_lock, scan_offline
from .wizard import prompt, prompt_path, select_number
@dataclass(frozen=True)
@@ -32,23 +30,6 @@ class QuestionsImportResult:
return value
def _prompt(input_func: Callable[[str], str], message: str) -> str:
try:
return input_func(message).strip()
except EOFError as exc:
raise MoodleError("interactive input ended before the questions import was complete") from exc
def _prompt_path_value(value: str) -> Path:
try:
parts = shlex.split(value)
except ValueError as exc:
raise MoodleError(f"invalid file path: {exc}") from exc
if len(parts) != 1:
raise MoodleError("enter exactly one file path")
return Path(parts[0]).expanduser()
def _course_choices(public: Path) -> list[tuple[int, str, dict[str, Any]]]:
choices: list[tuple[int, str, dict[str, Any]]] = []
for manifest_path in sorted((public / "courses").glob("*/manifest.json")):
@@ -85,27 +66,6 @@ def _quiz_choices(course: dict[str, Any]) -> list[tuple[int, str, str, str]]:
return choices
def _select_number(
choices: list[tuple[Any, ...]],
prompt_message: str,
input_func: Callable[[str], str],
output: TextIO,
) -> int:
valid_ids = {int(choice[0]) for choice in choices}
while True:
value = _prompt(input_func, prompt_message)
try:
selected = int(value)
except ValueError:
print("Please enter a list number or ID.", file=output)
continue
if 1 <= selected <= len(choices):
return int(choices[selected - 1][0])
if selected in valid_ids:
return selected
print("That selection is not in the list. Please try again.", file=output)
def questions_wizard(
public: Path,
course_id: int | None = None,
@@ -130,7 +90,7 @@ def questions_wizard(
for index, (candidate_id, title, course) in enumerate(courses, start=1):
quiz_count = len(_quiz_choices(course))
print(f" [{index}] {title} (course {candidate_id}, {quiz_count} exam(s))", file=output)
course_id = _select_number(courses, "Select a course: ", input_func, output)
course_id = select_number(courses, "Select a course: ", input_func, output)
if course_id not in courses_by_id:
raise MoodleError(f"course {course_id} has no local quiz activities; run `ravin scan {course_id}` first")
@@ -144,14 +104,14 @@ def questions_wizard(
f" [{index}] {title} (activity {candidate_id}, section: {section_title}, questions: {status})",
file=output,
)
activity_id = _select_number(quizzes, "Select an exam: ", input_func, output)
activity_id = select_number(quizzes, "Select an exam: ", input_func, output)
if activity_id not in quiz_ids:
raise MoodleError(f"activity {activity_id} is not a quiz in course {course_id}")
while questions_path is None:
value = _prompt(input_func, "Questions Markdown file: ")
value = prompt(input_func, "Questions Markdown file: ")
try:
candidate = _prompt_path_value(value)
candidate = prompt_path(value)
questions_path = _questions_source(candidate)
except MoodleError as exc:
print(f"Invalid questions file: {exc}", file=output)
@@ -160,11 +120,11 @@ def questions_wizard(
attachments = _attachment_sources(attachment_paths)
if prompt_for_attachment and not attachments:
while True:
value = _prompt(input_func, "Exam PDF (optional; press Enter to skip): ")
value = prompt(input_func, "Exam PDF (optional; press Enter to skip): ")
if not value:
break
try:
candidate = _prompt_path_value(value)
candidate = prompt_path(value)
attachments = _attachment_sources((candidate,))
break
except MoodleError as exc:
@@ -173,31 +133,6 @@ def questions_wizard(
return course_id, activity_id, questions_path, attachments
def _atomic_copy(source: Path, destination: Path) -> None:
destination.parent.mkdir(parents=True, exist_ok=True)
if source.resolve() == destination.resolve():
os.chmod(destination, 0o644)
return
temporary_path: Path | None = None
try:
with source.open("rb") as input_file, tempfile.NamedTemporaryFile(
mode="wb",
dir=destination.parent,
prefix=f".{destination.name}.",
suffix=".tmp",
delete=False,
) as output_file:
shutil.copyfileobj(input_file, output_file, length=1024 * 1024)
output_file.flush()
os.fsync(output_file.fileno())
temporary_path = Path(output_file.name)
os.chmod(temporary_path, 0o644)
os.replace(temporary_path, destination)
finally:
if temporary_path is not None:
temporary_path.unlink(missing_ok=True)
def _questions_source(path: Path) -> Path:
source = path.expanduser().resolve()
if not source.is_file():
@@ -271,12 +206,12 @@ def import_questions(
)
activity_directory = public / "courses" / str(course_id) / "content" / key
questions_destination = activity_directory / "artifacts" / "questions.fa.md"
_atomic_copy(questions_source, questions_destination)
atomic_copy(questions_source, questions_destination)
copied_files: list[str] = []
for source in attachment_sources:
filename = _clean_name(source.name, "exam-file")
_atomic_copy(source, activity_directory / "files" / filename)
atomic_copy(source, activity_directory / "files" / filename)
copied_files.append(filename)
# Persist enough local information for an offline scan to expose the exam
+243
View File
@@ -0,0 +1,243 @@
"""Import local recordings for Moodle live-class activities."""
from __future__ import annotations
import mimetypes
import sys
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, TextIO
from .constants import LIVE_CLASS_MODULES
from .local_files import archive_existing_file, atomic_copy
from .models import MoodleError
from .paths import _activity_directory_name, _clean_name, _read_json_object
from .scan import _atomic_json, _manifest_lock, scan_offline
from .wizard import prompt, prompt_path, select_number
VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov", ".m4v"}
@dataclass(frozen=True)
class RecordingImportResult:
course_id: int
activity_id: int
activity_key: str
activity_title: str
recording: str
archived: tuple[str, ...]
def to_dict(self) -> dict[str, Any]:
value = asdict(self)
value["archived"] = list(self.archived)
return value
def _is_live_activity(item: dict[str, Any]) -> bool:
return (
str(item.get("activity_type") or "").casefold() in LIVE_CLASS_MODULES
or str(item.get("kind") or "").casefold() == "live class"
)
def _recording_choices(course: dict[str, Any]) -> list[tuple[int, str, str, str, str]]:
choices: list[tuple[int, str, str, str, str]] = []
for section in course.get("sections", []):
if not isinstance(section, dict):
continue
section_title = str(section.get("name") or f"Section {section.get('number', '')}")
for item in section.get("items", []):
if not isinstance(item, dict) or not _is_live_activity(item):
continue
activity_id = int(item.get("activity_id") or 0)
if not activity_id:
continue
title = str(item.get("title") or f"Live class {activity_id}")
recording = str(item.get("filename") or "missing")
transcript = str(item.get("state", {}).get("transcript") or "not available")
choices.append((activity_id, title, section_title, recording, transcript))
return choices
def _course_choices(public: Path) -> list[tuple[int, str, dict[str, Any]]]:
choices: list[tuple[int, str, dict[str, Any]]] = []
for manifest_path in sorted((public / "courses").glob("*/manifest.json")):
manifest = _read_json_object(manifest_path)
course = manifest.get("course")
if not isinstance(course, dict) or not _recording_choices(course):
continue
course_id = int(course.get("id") or 0)
if course_id:
title = str(course.get("fullname") or course.get("shortname") or f"Course {course_id}")
choices.append((course_id, title, course))
choices.sort(key=lambda value: value[0])
return choices
def _recording_source(path: Path) -> Path:
source = path.expanduser().resolve()
if not source.is_file():
raise MoodleError(f"recording file not found: {source}")
mimetype = mimetypes.guess_type(source.name)[0] or ""
if source.suffix.casefold() not in VIDEO_EXTENSIONS and not mimetype.startswith("video/"):
formats = ", ".join(sorted(VIDEO_EXTENSIONS))
raise MoodleError(f"recording must be a video file ({formats})")
if source.stat().st_size == 0:
raise MoodleError("recording file is empty")
return source
def _find_live_activity(
course: dict[str, Any],
activity_id: int,
) -> tuple[dict[str, Any], dict[str, Any]]:
matches: list[tuple[dict[str, Any], dict[str, Any]]] = []
for section in course.get("sections", []):
if not isinstance(section, dict):
continue
for item in section.get("items", []):
if isinstance(item, dict) and int(item.get("activity_id") or 0) == activity_id:
matches.append((section, item))
if not matches:
raise MoodleError(f"activity {activity_id} was not found in course {course.get('id')}; run `ravin scan` first")
if len(matches) > 1:
raise MoodleError(f"activity {activity_id} appears more than once in the course manifest")
section, item = matches[0]
if not _is_live_activity(item):
raise MoodleError(f"activity {activity_id} is not a live class")
return section, item
def recording_wizard(
public: Path,
course_id: int | None = None,
activity_id: int | None = None,
recording_path: Path | None = None,
*,
input_func: Callable[[str], str] = input,
output: TextIO | None = None,
) -> tuple[int, int, Path]:
"""Interactively fill omitted recording-import arguments."""
public = public.expanduser().resolve()
output = output or sys.stderr
courses = _course_choices(public)
if not courses:
raise MoodleError(f"no local courses with live classes found in {public / 'courses'}; run `ravin scan` first")
courses_by_id = {choice[0]: choice for choice in courses}
if course_id is None:
print("\nCourses with live classes:", file=output)
for index, (candidate_id, title, course) in enumerate(courses, start=1):
count = len(_recording_choices(course))
print(f" [{index}] {title} (course {candidate_id}, {count} live class(es))", file=output)
course_id = select_number(courses, "Select a course: ", input_func, output)
if course_id not in courses_by_id:
raise MoodleError(f"course {course_id} has no local live classes; run `ravin scan {course_id}` first")
course = courses_by_id[course_id][2]
activities = _recording_choices(course)
activity_ids = {choice[0] for choice in activities}
if activity_id is None:
print("\nLive classes:", file=output)
for index, (candidate_id, title, section, recording, transcript) in enumerate(activities, start=1):
print(
f" [{index}] {title} (activity {candidate_id}, section: {section}, "
f"recording: {recording}, transcript: {transcript})",
file=output,
)
activity_id = select_number(activities, "Select a live class: ", input_func, output)
if activity_id not in activity_ids:
raise MoodleError(f"activity {activity_id} is not a live class in course {course_id}")
while recording_path is None:
value = prompt(input_func, "Video recording file: ")
try:
recording_path = _recording_source(prompt_path(value))
except MoodleError as exc:
print(f"Invalid recording file: {exc}", file=output)
return course_id, activity_id, _recording_source(recording_path)
def import_recording(
public: Path,
course_id: int,
activity_id: int,
recording_path: Path,
) -> RecordingImportResult:
"""Install a live-class recording and reconcile it as normal course media."""
public = public.expanduser().resolve()
source = _recording_source(recording_path)
manifest_path = public / "courses" / str(course_id) / "manifest.json"
manifest = _read_json_object(manifest_path)
course = manifest.get("course")
if not isinstance(course, dict):
raise MoodleError(f"course manifest not found: {manifest_path}; run `ravin scan {course_id}` first")
section, item = _find_live_activity(course, activity_id)
key = str(item.get("key") or "") or _activity_directory_name(
item.get("section_number", section.get("number")),
item.get("activity_position"),
activity_id,
)
activity_directory = public / "courses" / str(course_id) / "content" / key
filename = _clean_name(source.name, "recording.mp4")
destination = activity_directory / "files" / filename
archived_paths: list[Path] = []
try:
if destination.is_file() and source.resolve() != destination.resolve():
archived_paths.append(archive_existing_file(destination))
atomic_copy(source, destination)
except OSError as exc:
raise MoodleError(f"could not import recording: {exc}") from exc
destination_stat = destination.stat()
_atomic_json(
activity_directory / "artifacts" / "recording.meta.json",
{
"schema_version": 1,
"source": f"../files/{filename}",
"source_size": destination_stat.st_size,
"source_mtime_ns": destination_stat.st_mtime_ns,
"imported_at": datetime.now(timezone.utc).isoformat(),
},
)
mimetype = mimetypes.guess_type(filename)[0] or "video/mp4"
with _manifest_lock(public / "courses"):
current = _read_json_object(manifest_path)
current_course = current.get("course")
if not isinstance(current_course, dict):
raise MoodleError(f"course manifest changed while importing recording: {manifest_path}")
_current_section, current_item = _find_live_activity(current_course, activity_id)
current_item.update(
{
"key": key,
"bundle_path": f"content/{key}",
"filename": filename,
"extension": destination.suffix.removeprefix(".").casefold(),
"kind": "video",
"mimetype": mimetype,
}
)
current_item.pop("remote_size", None)
current["course"] = current_course
_atomic_json(manifest_path, current)
scan_offline(public, [course_id])
return RecordingImportResult(
course_id=course_id,
activity_id=activity_id,
activity_key=key,
activity_title=str(item.get("title") or f"Activity {activity_id}"),
recording=destination.relative_to(public).as_posix(),
archived=tuple(path.relative_to(public).as_posix() for path in archived_paths),
)
def format_recording_result(result: RecordingImportResult) -> str:
archived = " The previous same-name recording was archived." if result.archived else ""
return (
f"Added recording for {result.activity_title} "
f"(course {result.course_id}, activity {result.activity_id}).{archived}"
)
+6 -1
View File
@@ -12,6 +12,7 @@ from typing import Any, Iterable, Iterator
from .catalog import _build_library_catalog
from .client import MoodleClient
from .constants import LIVE_CLASS_MODULES
from .models import FileItem, MoodleError
from .paths import (
_activity_directory_name,
@@ -283,7 +284,11 @@ 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"):
versioned_activity = (
item.get("activity_type") == "resource"
or item.get("activity_type") in LIVE_CLASS_MODULES
)
if versioned_activity and item.get("filename"):
item["file_versions"] = _file_versions(public, activity_directory, local_path)
else:
item.pop("file_versions", None)
+50
View File
@@ -0,0 +1,50 @@
"""Shared helpers for interactive local-import commands."""
from __future__ import annotations
import shlex
from pathlib import Path
from typing import Any, Callable, TextIO
from .models import MoodleError
def prompt(input_func: Callable[[str], str], message: str) -> str:
try:
return input_func(message).strip()
except EOFError as exc:
raise MoodleError("interactive input ended before the import was complete") from exc
def prompt_path(value: str) -> Path:
direct = Path(value).expanduser()
if direct.exists():
return direct
try:
parts = shlex.split(value)
except ValueError as exc:
raise MoodleError(f"invalid file path: {exc}") from exc
if len(parts) != 1:
raise MoodleError("enter exactly one file path")
return Path(parts[0]).expanduser()
def select_number(
choices: list[tuple[Any, ...]],
prompt_message: str,
input_func: Callable[[str], str],
output: TextIO,
) -> int:
valid_ids = {int(choice[0]) for choice in choices}
while True:
value = prompt(input_func, prompt_message)
try:
selected = int(value)
except ValueError:
print("Please enter a list number or ID.", file=output)
continue
if 1 <= selected <= len(choices):
return int(choices[selected - 1][0])
if selected in valid_ids:
return selected
print("That selection is not in the list. Please try again.", file=output)
+8
View File
@@ -111,6 +111,14 @@ class ParserTests(unittest.TestCase):
self.assertIsNone(questions_wizard.course_id)
self.assertIsNone(questions_wizard.activity_id)
self.assertIsNone(questions_wizard.questions)
recording = build_parser().parse_args(["recording", "44", "5097", "class.mp4"])
self.assertEqual(recording.course_id, 44)
self.assertEqual(recording.activity_id, 5097)
self.assertEqual(recording.video, Path("class.mp4"))
recordings_wizard = build_parser().parse_args(["recordings"])
self.assertIsNone(recordings_wizard.course_id)
self.assertIsNone(recordings_wizard.activity_id)
self.assertIsNone(recordings_wizard.video)
serve = build_parser().parse_args(["serve", "--port", "9000"])
self.assertEqual(serve.port, 9000)
+200
View File
@@ -0,0 +1,200 @@
from __future__ import annotations
import io
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
from ravin.models import MoodleError
from ravin.recordings import import_recording, recording_wizard
from ravin.scan import scan_remote
from ravin.summarize import CourseSummarizer, SummaryOptions
from ravin.transcribe import CourseTranscriber, TranscriptionOptions
class FakeModel:
device = "cpu"
def transcribe(self, source: str, **_kwargs: object) -> dict[str, str]:
return {"text": f"transcript for {Path(source).name}"}
class RecordingImportTests(unittest.TestCase):
def setUp(self) -> None:
self.temporary_directory = tempfile.TemporaryDirectory()
self.root = Path(self.temporary_directory.name)
self.public = self.root / "public"
self.manifest_path = self.public / "courses" / "44" / "manifest.json"
self.manifest_path.parent.mkdir(parents=True)
self.manifest_path.write_text(
json.dumps(
{
"schema_version": 1,
"course": {
"id": 44,
"fullname": "Network +",
"sections": [
{
"number": 27,
"name": "Live support classes",
"items": [
{
"activity_id": 5097,
"activity_position": 1,
"activity_type": "bigbluebuttonbn",
"title": "Group A live class",
"kind": "live class",
"key": "027--001--5097",
"bundle_path": "content/027--001--5097",
"filename": "",
}
],
}
],
},
}
),
encoding="utf-8",
)
self.video = self.root / "class recording.mp4"
self.video.write_bytes(b"synthetic recording")
def tearDown(self) -> None:
self.temporary_directory.cleanup()
def test_wizard_lists_courses_and_live_classes(self) -> None:
answers = iter(["1", "1", str(self.video)])
output = io.StringIO()
values = recording_wizard(
self.public,
input_func=lambda _prompt: next(answers),
output=output,
)
self.assertEqual(values, (44, 5097, self.video.resolve()))
display = output.getvalue()
self.assertIn("Courses with live classes:", display)
self.assertIn("Network + (course 44, 1 live class(es))", display)
self.assertIn("Group A live class (activity 5097", display)
self.assertIn("recording: missing", display)
def test_import_becomes_transcribable_and_summarizable_media(self) -> None:
result = import_recording(self.public, 44, 5097, self.video)
bundle = self.public / "courses" / "44" / "content" / "027--001--5097"
recording = bundle / "files" / "class recording.mp4"
self.assertEqual(recording.read_bytes(), b"synthetic recording")
self.assertEqual(result.recording, "courses/44/content/027--001--5097/files/class recording.mp4")
metadata = json.loads((bundle / "artifacts" / "recording.meta.json").read_text(encoding="utf-8"))
self.assertEqual(metadata["source"], "../files/class recording.mp4")
self.assertNotIn(str(self.root), json.dumps(metadata))
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
item = manifest["course"]["sections"][0]["items"][0]
self.assertEqual(item["kind"], "video")
self.assertEqual(item["state"]["download"], "complete")
self.assertEqual(item["state"]["transcript"], "missing")
self.assertEqual(item["state"]["summary"], "missing")
self.assertEqual(item["file_versions"][0]["state"], "current")
transcriber = CourseTranscriber(
TranscriptionOptions(
public=self.public,
course_ids=(44,),
model="tiny",
device="cpu",
keep_awake=False,
),
model_loader=lambda _name, _device: (FakeModel(), None, "cpu"),
media_validator=lambda _source: None,
)
transcribed = transcriber.run()
self.assertEqual(transcribed.succeeded, 1)
summary = CourseSummarizer(
SummaryOptions(public=self.public, course_ids=(44,), dry_run=True, keep_awake=False)
).run()
self.assertEqual(summary.total, 1)
self.assertEqual(summary.unavailable, 0)
def test_same_name_replacement_archives_previous_recording(self) -> None:
import_recording(self.public, 44, 5097, self.video)
replacement_directory = self.root / "replacement"
replacement_directory.mkdir()
replacement = replacement_directory / self.video.name
replacement.write_bytes(b"replacement recording")
result = import_recording(self.public, 44, 5097, replacement)
bundle = self.public / "courses" / "44" / "content" / "027--001--5097"
self.assertEqual((bundle / "files" / self.video.name).read_bytes(), b"replacement recording")
archives = list((bundle / "files" / "archive").glob(f"*--{self.video.name}"))
self.assertEqual(len(archives), 1)
self.assertEqual(archives[0].read_bytes(), b"synthetic recording")
self.assertEqual(len(result.archived), 1)
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
versions = manifest["course"]["sections"][0]["items"][0]["file_versions"]
self.assertEqual([version["state"] for version in versions], ["current", "archived"])
def test_online_scan_keeps_the_selected_live_class_recording(self) -> None:
import_recording(self.public, 44, 5097, self.video)
class FakeClient:
site = "https://training.example"
@staticmethod
def list_courses() -> list[Course]:
return [Course(44, "Network +")]
@staticmethod
def list_files(_course_id: int) -> list[object]:
return []
@staticmethod
def course_structure(_course_id: int) -> list[dict[str, object]]:
return [
{
"number": 27,
"name": "Live support classes",
"activities": [
{
"id": 5097,
"position": 1,
"type": "bigbluebuttonbn",
"name": "Group A live class",
}
],
}
]
scan_remote(FakeClient(), self.public, [44])
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
item = manifest["course"]["sections"][0]["items"][0]
self.assertEqual(item["filename"], "class recording.mp4")
self.assertEqual(item["kind"], "video")
self.assertEqual(item["state"]["download"], "complete")
def test_rejects_non_video_and_non_live_activity(self) -> None:
text_file = self.root / "notes.txt"
text_file.write_text("not video", encoding="utf-8")
with self.assertRaisesRegex(MoodleError, "must be a video file"):
import_recording(self.public, 44, 5097, text_file)
manifest = json.loads(self.manifest_path.read_text(encoding="utf-8"))
item = manifest["course"]["sections"][0]["items"][0]
item["activity_type"] = "forum"
item["kind"] = "discussion"
self.manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
with self.assertRaisesRegex(MoodleError, "not a live class"):
import_recording(self.public, 44, 5097, self.video)
if __name__ == "__main__":
unittest.main()