feat: add safe URL-based course import and restore
This commit is contained in:
8 files changed
+499
-2
No files matched your search
@@ -2,6 +2,14 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented here.
|
All notable changes to this project will be documented here.
|
||||||
|
|
||||||
|
## 0.14.0 - 2026-08-13
|
||||||
|
|
||||||
|
- Add `ravin import URL` for restoring backups and updating course mirrors from direct export links.
|
||||||
|
- Validate ZIP structure, paths, links, duplicate entries, manifests, and file integrity before merging.
|
||||||
|
- Preserve local-only files while giving archive files priority at matching paths.
|
||||||
|
- Replace imported files atomically and automatically reconcile the complete library with an offline scan.
|
||||||
|
- Add `--timeout`, `--public`, and machine-readable `--json` import options.
|
||||||
|
|
||||||
## 0.13.0 - 2026-08-13
|
## 0.13.0 - 2026-08-13
|
||||||
|
|
||||||
- Add a local `ravin export` command that creates timestamped archives under `public/exports/` from all scanned courses.
|
- Add a local `ravin export` command that creates timestamped archives under `public/exports/` from all scanned courses.
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ ravin summarize COURSE_ID
|
|||||||
ravin questions
|
ravin questions
|
||||||
ravin recording
|
ravin recording
|
||||||
ravin export
|
ravin export
|
||||||
|
ravin import EXPORT_URL
|
||||||
ravin serve --open
|
ravin serve --open
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -148,6 +149,18 @@ 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.
|
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.
|
||||||
|
|
||||||
|
### Restore or update from an export
|
||||||
|
|
||||||
|
Import directly from another library server or backup location:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ravin import https://mirror.example/exports/2026-08-13_14-35-22.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
The import is additive. Local files that are not present in the ZIP remain in place, while files at matching paths are replaced by the versions from the ZIP. Ravin downloads and fully validates the archive before changing local course data, rejects unsafe paths, merges each file atomically, and automatically runs an offline scan afterward. This makes the command suitable for restoring a backup or updating a mirror/clone.
|
||||||
|
|
||||||
|
Use `--public PATH` for another library root, `--timeout SECONDS` for slow servers, or `--json` for machine-readable import and scan results. The URL must point directly to an export ZIP over HTTP or HTTPS.
|
||||||
|
|
||||||
## Exam questions and answers
|
## Exam questions and answers
|
||||||
|
|
||||||
Start the interactive import wizard:
|
Start the interactive import wizard:
|
||||||
@@ -370,6 +383,7 @@ ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS
|
|||||||
ravin questions [COURSE_ID] [ACTIVITY_ID] [QUESTIONS.md] [--file ATTACHMENT ...]
|
ravin questions [COURSE_ID] [ACTIVITY_ID] [QUESTIONS.md] [--file ATTACHMENT ...]
|
||||||
ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO]
|
ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO]
|
||||||
ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH]
|
ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH]
|
||||||
|
ravin import URL [--timeout SECONDS] [--json] [--public PATH]
|
||||||
ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH]
|
ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH]
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -393,6 +407,7 @@ src/ravin/
|
|||||||
├── questions.py # local exam-question and attachment imports
|
├── questions.py # local exam-question and attachment imports
|
||||||
├── recordings.py # local live-class recording imports
|
├── recordings.py # local live-class recording imports
|
||||||
├── exporter.py # atomic course ZIP exports
|
├── exporter.py # atomic course ZIP exports
|
||||||
|
├── importer.py # safe URL restores and mirror updates
|
||||||
├── local_files.py # atomic local copies and archived versions
|
├── local_files.py # atomic local copies and archived versions
|
||||||
├── wizard.py # shared interactive import helpers
|
├── wizard.py # shared interactive import helpers
|
||||||
├── migration.py # previous-layout migration
|
├── migration.py # previous-layout migration
|
||||||
|
|||||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "ravin-moodle-downloader"
|
name = "ravin-moodle-downloader"
|
||||||
version = "0.13.0"
|
version = "0.14.0"
|
||||||
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
|
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ from .auth import (
|
|||||||
from .client import MoodleClient
|
from .client import MoodleClient
|
||||||
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
|
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
|
||||||
from .exporter import export_courses, format_export_result
|
from .exporter import export_courses, format_export_result
|
||||||
|
from .importer import format_import_result, import_courses
|
||||||
from .migration import migrate_library_to_public
|
from .migration import migrate_library_to_public
|
||||||
from .models import MoodleError
|
from .models import MoodleError
|
||||||
from .questions import format_questions_result, import_questions, questions_wizard
|
from .questions import format_questions_result, import_questions, questions_wizard
|
||||||
@@ -187,6 +188,21 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
)
|
)
|
||||||
export_parser.add_argument("--json", action="store_true", help="print export details as JSON")
|
export_parser.add_argument("--json", action="store_true", help="print export details as JSON")
|
||||||
|
|
||||||
|
import_parser = subparsers.add_parser(
|
||||||
|
"import",
|
||||||
|
help="restore or update local courses from an export URL",
|
||||||
|
description="Download a Ravin course ZIP, merge it over local courses, and run an offline scan.",
|
||||||
|
)
|
||||||
|
import_parser.add_argument("url", help="direct http:// or https:// URL to a Ravin export ZIP")
|
||||||
|
import_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||||
|
import_parser.add_argument(
|
||||||
|
"--timeout",
|
||||||
|
type=int,
|
||||||
|
default=60,
|
||||||
|
help="network read timeout in seconds (default: 60)",
|
||||||
|
)
|
||||||
|
import_parser.add_argument("--json", action="store_true", help="print import and scan details as JSON")
|
||||||
|
|
||||||
serve_parser = subparsers.add_parser("serve", help="serve the public learning library locally")
|
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("--public", type=Path, default=Path("public"), help="public web root")
|
||||||
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address")
|
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address")
|
||||||
@@ -236,6 +252,7 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
public = getattr(args, "public", Path("public")).expanduser().resolve()
|
public = getattr(args, "public", Path("public")).expanduser().resolve()
|
||||||
if args.command in {
|
if args.command in {
|
||||||
"scan", "download", "transcribe", "summarize", "questions", "recording", "recordings", "export",
|
"scan", "download", "transcribe", "summarize", "questions", "recording", "recordings", "export",
|
||||||
|
"import",
|
||||||
}:
|
}:
|
||||||
_maybe_migrate(public)
|
_maybe_migrate(public)
|
||||||
|
|
||||||
@@ -252,6 +269,25 @@ def main(argv: list[str] | None = None) -> int:
|
|||||||
)
|
)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
|
if args.command == "import":
|
||||||
|
result, catalog = import_courses(
|
||||||
|
public,
|
||||||
|
args.url,
|
||||||
|
timeout=args.timeout,
|
||||||
|
progress=None if args.json else lambda message: print(message, file=sys.stderr),
|
||||||
|
)
|
||||||
|
if args.json:
|
||||||
|
print(json.dumps(
|
||||||
|
{"import": result.to_dict(), "scan": scan_output(catalog)},
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2,
|
||||||
|
))
|
||||||
|
else:
|
||||||
|
print(format_import_result(result))
|
||||||
|
print()
|
||||||
|
print(format_scan(catalog))
|
||||||
|
return 0
|
||||||
|
|
||||||
if args.command == "scan" and args.offline:
|
if args.command == "scan" and args.offline:
|
||||||
catalog = scan_offline(public, args.course_ids)
|
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))
|
print(json.dumps(scan_output(catalog), ensure_ascii=False, indent=2) if args.json else format_scan(catalog))
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
DEFAULT_SITE = "https://training.ravinacademy.com"
|
DEFAULT_SITE = "https://training.ravinacademy.com"
|
||||||
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
||||||
__version__ = "0.13.0"
|
__version__ = "0.14.0"
|
||||||
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
||||||
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
||||||
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
|
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
|
||||||
|
|||||||
@@ -0,0 +1,284 @@
|
|||||||
|
"""Restore or mirror course exports from a direct ZIP URL."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import http.client
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import stat
|
||||||
|
import tempfile
|
||||||
|
import urllib.error
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import zipfile
|
||||||
|
from dataclasses import asdict, dataclass
|
||||||
|
from pathlib import Path, PurePosixPath
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
from .constants import USER_AGENT
|
||||||
|
from .models import MoodleError
|
||||||
|
from .scan import _manifest_lock, scan_offline
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ImportResult:
|
||||||
|
source: str
|
||||||
|
archive_bytes: int
|
||||||
|
courses: int
|
||||||
|
files: int
|
||||||
|
added: int
|
||||||
|
replaced: int
|
||||||
|
|
||||||
|
def to_dict(self) -> dict[str, Any]:
|
||||||
|
return asdict(self)
|
||||||
|
|
||||||
|
|
||||||
|
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 _display_url(url: str) -> str:
|
||||||
|
parsed = urllib.parse.urlsplit(url)
|
||||||
|
hostname = parsed.hostname or ""
|
||||||
|
if ":" in hostname:
|
||||||
|
hostname = f"[{hostname}]"
|
||||||
|
port = parsed.port
|
||||||
|
netloc = f"{hostname}:{port}" if port is not None else hostname
|
||||||
|
return urllib.parse.urlunsplit((parsed.scheme, netloc, parsed.path, "", ""))
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_url(url: str) -> None:
|
||||||
|
parsed = urllib.parse.urlsplit(url)
|
||||||
|
if parsed.scheme.casefold() not in {"http", "https"} or not parsed.netloc:
|
||||||
|
raise MoodleError("import source must be a direct http:// or https:// URL")
|
||||||
|
try:
|
||||||
|
parsed.port
|
||||||
|
except ValueError as exc:
|
||||||
|
raise MoodleError(f"invalid import URL: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _download(
|
||||||
|
url: str,
|
||||||
|
destination: Path,
|
||||||
|
*,
|
||||||
|
timeout: int,
|
||||||
|
progress: Callable[[str], None] | None,
|
||||||
|
) -> int:
|
||||||
|
request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
|
||||||
|
display_url = _display_url(url)
|
||||||
|
if progress:
|
||||||
|
progress(f"Downloading {display_url}...")
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||||
|
status = response.getcode()
|
||||||
|
if status is not None and not 200 <= status < 300:
|
||||||
|
raise MoodleError(f"export download returned HTTP {status}")
|
||||||
|
expected_value = response.headers.get("Content-Length")
|
||||||
|
expected = int(expected_value) if expected_value and expected_value.isdigit() else None
|
||||||
|
downloaded = 0
|
||||||
|
next_update = 64 * 1024 * 1024
|
||||||
|
with destination.open("wb") as target:
|
||||||
|
while True:
|
||||||
|
chunk = response.read(1024 * 1024)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
target.write(chunk)
|
||||||
|
downloaded += len(chunk)
|
||||||
|
if progress and downloaded >= next_update:
|
||||||
|
suffix = f" / {_format_size(expected)}" if expected is not None else ""
|
||||||
|
progress(f" downloaded {_format_size(downloaded)}{suffix}")
|
||||||
|
next_update += 64 * 1024 * 1024
|
||||||
|
except MoodleError:
|
||||||
|
raise
|
||||||
|
except urllib.error.HTTPError as exc:
|
||||||
|
raise MoodleError(f"could not download export: HTTP {exc.code}") from exc
|
||||||
|
except urllib.error.URLError as exc:
|
||||||
|
raise MoodleError(f"could not download export: {exc.reason}") from exc
|
||||||
|
except http.client.HTTPException as exc:
|
||||||
|
raise MoodleError(f"could not download export: {exc}") from exc
|
||||||
|
except OSError as exc:
|
||||||
|
raise MoodleError(f"could not save downloaded export: {exc}") from exc
|
||||||
|
if downloaded == 0:
|
||||||
|
raise MoodleError("downloaded export is empty")
|
||||||
|
if expected is not None and downloaded != expected:
|
||||||
|
raise MoodleError(f"export download was incomplete: expected {expected} bytes, received {downloaded}")
|
||||||
|
return downloaded
|
||||||
|
|
||||||
|
|
||||||
|
def _member_path(info: zipfile.ZipInfo) -> PurePosixPath:
|
||||||
|
name = info.filename
|
||||||
|
if not name or "\\" in name or "\0" in name:
|
||||||
|
raise MoodleError(f"unsafe path in export archive: {name!r}")
|
||||||
|
path = PurePosixPath(name)
|
||||||
|
if path.is_absolute() or any(part in {"", ".", ".."} for part in path.parts):
|
||||||
|
raise MoodleError(f"unsafe path in export archive: {name!r}")
|
||||||
|
root_directory = info.is_dir() and path.parts == ("courses",)
|
||||||
|
if not path.parts or path.parts[0] != "courses" or (len(path.parts) < 2 and not root_directory):
|
||||||
|
raise MoodleError(f"unexpected path in export archive: {name!r}; expected courses/...")
|
||||||
|
mode = info.external_attr >> 16
|
||||||
|
if stat.S_ISLNK(mode):
|
||||||
|
raise MoodleError(f"symbolic links are not allowed in export archives: {name!r}")
|
||||||
|
if info.flag_bits & 0x1:
|
||||||
|
raise MoodleError(f"encrypted files are not supported in export archives: {name!r}")
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _validated_members(archive: zipfile.ZipFile) -> tuple[list[tuple[zipfile.ZipInfo, PurePosixPath]], set[int]]:
|
||||||
|
members: list[tuple[zipfile.ZipInfo, PurePosixPath]] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
file_paths: set[tuple[str, ...]] = set()
|
||||||
|
for info in archive.infolist():
|
||||||
|
path = _member_path(info)
|
||||||
|
key = path.as_posix().casefold().rstrip("/")
|
||||||
|
if key in seen:
|
||||||
|
raise MoodleError(f"duplicate path in export archive: {path.as_posix()!r}")
|
||||||
|
seen.add(key)
|
||||||
|
if not info.is_dir():
|
||||||
|
file_paths.add(tuple(part.casefold() for part in path.parts))
|
||||||
|
members.append((info, path))
|
||||||
|
|
||||||
|
for parts in file_paths:
|
||||||
|
if any(parts[:index] in file_paths for index in range(2, len(parts))):
|
||||||
|
raise MoodleError(f"file/directory conflict in export archive: {'/'.join(parts)!r}")
|
||||||
|
|
||||||
|
course_ids: set[int] = set()
|
||||||
|
for info, path in members:
|
||||||
|
if len(path.parts) != 3 or path.parts[2] != "manifest.json":
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
course_id = int(path.parts[1])
|
||||||
|
manifest = json.loads(archive.read(info))
|
||||||
|
manifest_course_id = int(manifest["course"]["id"])
|
||||||
|
except (KeyError, TypeError, ValueError, json.JSONDecodeError, UnicodeDecodeError) as exc:
|
||||||
|
raise MoodleError(f"invalid course manifest in export: {path.as_posix()}") from exc
|
||||||
|
if course_id <= 0 or manifest_course_id != course_id:
|
||||||
|
raise MoodleError(f"course ID does not match manifest path: {path.as_posix()}")
|
||||||
|
course_ids.add(course_id)
|
||||||
|
if not course_ids:
|
||||||
|
raise MoodleError("archive contains no valid courses; expected courses/COURSE_ID/manifest.json")
|
||||||
|
return members, course_ids
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_to_staging(
|
||||||
|
archive: zipfile.ZipFile,
|
||||||
|
members: list[tuple[zipfile.ZipInfo, PurePosixPath]],
|
||||||
|
staging: Path,
|
||||||
|
) -> None:
|
||||||
|
try:
|
||||||
|
for info, path in members:
|
||||||
|
target = staging.joinpath(*path.parts)
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
with archive.open(info) as source, target.open("wb") as output:
|
||||||
|
shutil.copyfileobj(source, output, length=1024 * 1024)
|
||||||
|
except (OSError, RuntimeError, zipfile.BadZipFile) as exc:
|
||||||
|
raise MoodleError(f"could not validate export contents: {exc}") from exc
|
||||||
|
|
||||||
|
|
||||||
|
def _merge_staging(staging_courses: Path, courses_root: Path) -> tuple[int, int]:
|
||||||
|
sources = sorted(path for path in staging_courses.rglob("*") if path.is_file())
|
||||||
|
if courses_root.is_symlink():
|
||||||
|
raise MoodleError(f"course directory cannot be a symbolic link during import: {courses_root}")
|
||||||
|
courses_root.mkdir(parents=True, exist_ok=True)
|
||||||
|
resolved_root = courses_root.resolve()
|
||||||
|
plans: list[tuple[Path, Path, bool]] = []
|
||||||
|
for source in sources:
|
||||||
|
relative = source.relative_to(staging_courses)
|
||||||
|
target = courses_root / relative
|
||||||
|
try:
|
||||||
|
target.resolve(strict=False).relative_to(resolved_root)
|
||||||
|
except ValueError as exc:
|
||||||
|
raise MoodleError(f"unsafe existing path blocks import: {target}") from exc
|
||||||
|
if target.exists() and not target.is_file():
|
||||||
|
raise MoodleError(f"cannot replace non-file path during import: {target}")
|
||||||
|
parent = target.parent
|
||||||
|
while parent != courses_root:
|
||||||
|
if parent.exists() and not parent.is_dir():
|
||||||
|
raise MoodleError(f"cannot create import directory over a file: {parent}")
|
||||||
|
parent = parent.parent
|
||||||
|
plans.append((source, target, target.is_file()))
|
||||||
|
|
||||||
|
added = 0
|
||||||
|
replaced = 0
|
||||||
|
with _manifest_lock(courses_root):
|
||||||
|
for source, target, existed in plans:
|
||||||
|
target.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
descriptor, temporary_name = tempfile.mkstemp(
|
||||||
|
prefix=f".{target.name}.ravin-import-",
|
||||||
|
dir=target.parent,
|
||||||
|
)
|
||||||
|
os.close(descriptor)
|
||||||
|
temporary = Path(temporary_name)
|
||||||
|
try:
|
||||||
|
shutil.copy2(source, temporary)
|
||||||
|
os.replace(temporary, target)
|
||||||
|
finally:
|
||||||
|
temporary.unlink(missing_ok=True)
|
||||||
|
replaced += int(existed)
|
||||||
|
added += int(not existed)
|
||||||
|
return added, replaced
|
||||||
|
|
||||||
|
|
||||||
|
def import_courses(
|
||||||
|
public: Path,
|
||||||
|
url: str,
|
||||||
|
*,
|
||||||
|
timeout: int = 60,
|
||||||
|
progress: Callable[[str], None] | None = None,
|
||||||
|
) -> tuple[ImportResult, dict[str, Any]]:
|
||||||
|
"""Download, validate, merge, and offline-scan a course export."""
|
||||||
|
_validate_url(url)
|
||||||
|
if timeout <= 0:
|
||||||
|
raise MoodleError("import timeout must be greater than zero")
|
||||||
|
public = public.expanduser().resolve()
|
||||||
|
courses_root = public / "courses"
|
||||||
|
with tempfile.TemporaryDirectory(prefix="ravin-import-") as temporary_directory:
|
||||||
|
temporary_root = Path(temporary_directory)
|
||||||
|
archive_path = temporary_root / "download.zip"
|
||||||
|
staging = temporary_root / "staging"
|
||||||
|
archive_bytes = _download(url, archive_path, timeout=timeout, progress=progress)
|
||||||
|
try:
|
||||||
|
with zipfile.ZipFile(archive_path) as archive:
|
||||||
|
members, course_ids = _validated_members(archive)
|
||||||
|
if progress:
|
||||||
|
progress(f"Validating {len(members)} file(s) from {len(course_ids)} course(s)...")
|
||||||
|
_extract_to_staging(archive, members, staging)
|
||||||
|
except zipfile.BadZipFile as exc:
|
||||||
|
raise MoodleError(f"downloaded file is not a valid ZIP archive: {exc}") from exc
|
||||||
|
|
||||||
|
if progress:
|
||||||
|
progress("Merging imported files; archive versions take priority...")
|
||||||
|
try:
|
||||||
|
added, replaced = _merge_staging(staging / "courses", courses_root)
|
||||||
|
except MoodleError:
|
||||||
|
raise
|
||||||
|
except OSError as exc:
|
||||||
|
raise MoodleError(f"could not merge imported course files: {exc}") from exc
|
||||||
|
|
||||||
|
if progress:
|
||||||
|
progress("Running offline scan...")
|
||||||
|
catalog = scan_offline(public)
|
||||||
|
return (
|
||||||
|
ImportResult(
|
||||||
|
source=_display_url(url),
|
||||||
|
archive_bytes=archive_bytes,
|
||||||
|
courses=len(course_ids),
|
||||||
|
files=len(members),
|
||||||
|
added=added,
|
||||||
|
replaced=replaced,
|
||||||
|
),
|
||||||
|
catalog,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def format_import_result(result: ImportResult) -> str:
|
||||||
|
return (
|
||||||
|
f"Imported {result.courses} course(s) from {result.source}\n"
|
||||||
|
f"{result.files} file(s): {result.added} added, {result.replaced} replaced "
|
||||||
|
f"({_format_size(result.archive_bytes)} downloaded)."
|
||||||
|
)
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
import zipfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
|
||||||
|
|
||||||
|
from ravin.importer import format_import_result, import_courses
|
||||||
|
from ravin.models import MoodleError
|
||||||
|
|
||||||
|
|
||||||
|
class _Response:
|
||||||
|
def __init__(self, body: bytes, *, declared_size: int | None = None):
|
||||||
|
self._body = io.BytesIO(body)
|
||||||
|
size = len(body) if declared_size is None else declared_size
|
||||||
|
self.headers = {"Content-Length": str(size)}
|
||||||
|
|
||||||
|
def __enter__(self):
|
||||||
|
return self
|
||||||
|
|
||||||
|
def __exit__(self, *_args):
|
||||||
|
return False
|
||||||
|
|
||||||
|
def getcode(self):
|
||||||
|
return 200
|
||||||
|
|
||||||
|
def read(self, size: int):
|
||||||
|
return self._body.read(size)
|
||||||
|
|
||||||
|
|
||||||
|
def _manifest(course_id: int, title: str) -> bytes:
|
||||||
|
return json.dumps(
|
||||||
|
{
|
||||||
|
"schema_version": 1,
|
||||||
|
"course": {
|
||||||
|
"id": course_id,
|
||||||
|
"fullname": title,
|
||||||
|
"shortname": "",
|
||||||
|
"sections": [],
|
||||||
|
"section_count": 0,
|
||||||
|
"activity_count": 0,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
).encode()
|
||||||
|
|
||||||
|
|
||||||
|
def _archive(files: dict[str, bytes], *, explicit_directories: bool = False) -> bytes:
|
||||||
|
output = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(output, "w", compression=zipfile.ZIP_DEFLATED) as archive:
|
||||||
|
if explicit_directories:
|
||||||
|
archive.writestr("courses/", b"")
|
||||||
|
archive.writestr("courses/44/", b"")
|
||||||
|
for name, value in files.items():
|
||||||
|
archive.writestr(name, value)
|
||||||
|
return output.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
class CourseImportTests(unittest.TestCase):
|
||||||
|
def setUp(self) -> None:
|
||||||
|
self.temporary_directory = tempfile.TemporaryDirectory()
|
||||||
|
self.root = Path(self.temporary_directory.name)
|
||||||
|
self.public = self.root / "public"
|
||||||
|
course = self.public / "courses" / "44"
|
||||||
|
course.mkdir(parents=True)
|
||||||
|
(course / "manifest.json").write_bytes(_manifest(44, "Old title"))
|
||||||
|
(course / "conflict.txt").write_text("local version", encoding="utf-8")
|
||||||
|
(course / "local-only.txt").write_text("keep me", encoding="utf-8")
|
||||||
|
|
||||||
|
def tearDown(self) -> None:
|
||||||
|
self.temporary_directory.cleanup()
|
||||||
|
|
||||||
|
def test_import_merges_archive_priority_and_runs_offline_scan(self) -> None:
|
||||||
|
body = _archive(
|
||||||
|
{
|
||||||
|
"courses/catalog.json": b"{}",
|
||||||
|
"courses/44/manifest.json": _manifest(44, "Imported title"),
|
||||||
|
"courses/44/conflict.txt": b"archive version",
|
||||||
|
"courses/44/imported.txt": b"new file",
|
||||||
|
"courses/51/manifest.json": _manifest(51, "Second course"),
|
||||||
|
},
|
||||||
|
explicit_directories=True,
|
||||||
|
)
|
||||||
|
url = "https://mirror.example/exports/backup.zip?signature=secret"
|
||||||
|
|
||||||
|
with patch("ravin.importer.urllib.request.urlopen", return_value=_Response(body)) as urlopen:
|
||||||
|
result, catalog = import_courses(self.public, url)
|
||||||
|
|
||||||
|
request = urlopen.call_args.args[0]
|
||||||
|
self.assertEqual(request.full_url, url)
|
||||||
|
self.assertEqual(result.source, "https://mirror.example/exports/backup.zip")
|
||||||
|
self.assertEqual(result.courses, 2)
|
||||||
|
self.assertEqual(result.files, 5)
|
||||||
|
self.assertEqual(result.added, 3)
|
||||||
|
self.assertEqual(result.replaced, 2)
|
||||||
|
self.assertEqual((self.public / "courses/44/conflict.txt").read_text(), "archive version")
|
||||||
|
self.assertEqual((self.public / "courses/44/local-only.txt").read_text(), "keep me")
|
||||||
|
self.assertEqual((self.public / "courses/44/imported.txt").read_text(), "new file")
|
||||||
|
self.assertEqual(catalog["stats"]["courses"], 2)
|
||||||
|
refreshed = json.loads((self.public / "courses/44/manifest.json").read_text())
|
||||||
|
self.assertEqual(refreshed["course"]["fullname"], "Imported title")
|
||||||
|
self.assertIn("3 added, 2 replaced", format_import_result(result))
|
||||||
|
|
||||||
|
def test_unsafe_archive_is_rejected_before_existing_files_change(self) -> None:
|
||||||
|
body = _archive(
|
||||||
|
{
|
||||||
|
"courses/44/manifest.json": _manifest(44, "Imported title"),
|
||||||
|
"courses/../../outside.txt": b"unsafe",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch("ravin.importer.urllib.request.urlopen", return_value=_Response(body)):
|
||||||
|
with self.assertRaisesRegex(MoodleError, "unsafe path"):
|
||||||
|
import_courses(self.public, "https://mirror.example/unsafe.zip")
|
||||||
|
|
||||||
|
self.assertEqual((self.public / "courses/44/conflict.txt").read_text(), "local version")
|
||||||
|
current = json.loads((self.public / "courses/44/manifest.json").read_text())
|
||||||
|
self.assertEqual(current["course"]["fullname"], "Old title")
|
||||||
|
self.assertFalse((self.root / "outside.txt").exists())
|
||||||
|
|
||||||
|
def test_rejects_invalid_url_zip_manifest_and_incomplete_download(self) -> None:
|
||||||
|
with self.assertRaisesRegex(MoodleError, "direct http"):
|
||||||
|
import_courses(self.public, "file:///tmp/export.zip")
|
||||||
|
|
||||||
|
with patch("ravin.importer.urllib.request.urlopen", return_value=_Response(b"not a zip")):
|
||||||
|
with self.assertRaisesRegex(MoodleError, "not a valid ZIP"):
|
||||||
|
import_courses(self.public, "https://mirror.example/not-a-zip")
|
||||||
|
|
||||||
|
mismatched = _archive({"courses/44/manifest.json": _manifest(51, "Wrong")})
|
||||||
|
with patch("ravin.importer.urllib.request.urlopen", return_value=_Response(mismatched)):
|
||||||
|
with self.assertRaisesRegex(MoodleError, "does not match"):
|
||||||
|
import_courses(self.public, "https://mirror.example/mismatch.zip")
|
||||||
|
|
||||||
|
valid = _archive({"courses/44/manifest.json": _manifest(44, "Course")})
|
||||||
|
with patch(
|
||||||
|
"ravin.importer.urllib.request.urlopen",
|
||||||
|
return_value=_Response(valid, declared_size=len(valid) + 10),
|
||||||
|
):
|
||||||
|
with self.assertRaisesRegex(MoodleError, "incomplete"):
|
||||||
|
import_courses(self.public, "https://mirror.example/incomplete.zip")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -127,6 +127,11 @@ class ParserTests(unittest.TestCase):
|
|||||||
self.assertEqual(export.public, Path("site"))
|
self.assertEqual(export.public, Path("site"))
|
||||||
default_export = build_parser().parse_args(["export"])
|
default_export = build_parser().parse_args(["export"])
|
||||||
self.assertIsNone(default_export.output)
|
self.assertIsNone(default_export.output)
|
||||||
|
import_archive = build_parser().parse_args(
|
||||||
|
["import", "https://mirror.example/exports/latest.zip", "--timeout", "120"]
|
||||||
|
)
|
||||||
|
self.assertEqual(import_archive.url, "https://mirror.example/exports/latest.zip")
|
||||||
|
self.assertEqual(import_archive.timeout, 120)
|
||||||
serve = build_parser().parse_args(["serve", "--port", "9000"])
|
serve = build_parser().parse_args(["serve", "--port", "9000"])
|
||||||
self.assertEqual(serve.port, 9000)
|
self.assertEqual(serve.port, 9000)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user