feat: unify course scanning and add manifest-based public library

This commit is contained in:
Meghdad committed 2026-08-04 21:55:15 +03:30
1 parent 2580d86984
commit 114b472643
20 files changed
+809 -796

No files matched your search

+10 -167
View File
@@ -1,24 +1,19 @@
"""Build, write, and refresh the static course catalog."""
import hashlib
import html
import json
import mimetypes
import os
import re
import sys
import urllib.parse
from datetime import datetime, timezone
from importlib import resources
from pathlib import Path
from typing import Any, Iterable
from .client import MoodleClient
from .constants import LIBRARY_ASSETS
from .models import FileItem, MoodleError
from .paths import (
_activity_directory_name, _activity_root, _clean_name, _course_content_root,
_discover_artifacts, _read_json_object, _relative_browser_path,
_discover_artifacts, _relative_browser_path,
)
@@ -81,10 +76,15 @@ def _local_activity_record(
fallback=f"{course_id}\0{activity.get('url', '')}\0{activity.get('name', '')}",
)
directory = _course_content_root(library, course_id) / key
metadata = _read_json_object(directory / "item.json")
if not metadata:
files_directory = directory / "files"
files = [
path.relative_to(directory).as_posix()
for path in sorted(files_directory.iterdir())
if path.is_file() and not path.name.endswith(".part")
] if files_directory.is_dir() else []
if not files and not (directory / "artifacts").is_dir():
return None
return metadata, directory
return {"files": files}, directory
def _build_library_catalog(
@@ -154,6 +154,7 @@ def _build_library_catalog(
"extension": Path(item.filename).suffix.removeprefix(".").casefold(),
"kind": _resource_kind(item),
"mimetype": item.mimetype,
"remote_size": item.filesize,
"status": status,
"size": local_bytes if status == "downloaded" else item.filesize,
"local_bytes": local_bytes,
@@ -315,161 +316,3 @@ def _build_library_catalog(
},
"courses": catalog_courses,
}
def _write_library_site(library: Path, catalog: dict[str, Any]) -> Path:
library.mkdir(parents=True, exist_ok=True)
legacy_media_link = library / "media"
if legacy_media_link.is_symlink():
legacy_media_link.unlink()
elif legacy_media_link.exists():
raise MoodleError(f"{legacy_media_link} is not a symlink; move it aside before rebuilding")
asset_root = resources.files("ravin.assets")
for name in LIBRARY_ASSETS:
(library / name).write_bytes(asset_root.joinpath(name).read_bytes())
catalog_path = library / "courses.json"
catalog_path.write_text(
json.dumps(catalog, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
for course in catalog.get("courses", []):
course_id = int(course.get("id") or 0)
course_root = library / "courses" / str(course_id)
course_root.mkdir(parents=True, exist_ok=True)
(course_root / "course.json").write_text(
json.dumps(course, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
quoted_root = json.dumps(str(library.resolve()))
(library / "nginx-server.conf").write_text(
f"""# Generated by ravin. Include this file inside nginx's http block.
server {{
listen 127.0.0.1:8765;
server_name localhost;
root {quoted_root};
index index.html;
charset utf-8;
autoindex off;
location = / {{
try_files /index.html =404;
}}
location = /courses.json {{
try_files $uri =404;
default_type application/json;
add_header Cache-Control "no-store" always;
}}
location /courses/ {{
try_files $uri =404;
sendfile on;
tcp_nopush on;
add_header Accept-Ranges bytes always;
add_header X-Content-Type-Options nosniff always;
}}
location / {{
try_files $uri $uri/ =404;
}}
location ~ (^|/)\\. {{ return 404; }}
location ~ \\.part$ {{ return 404; }}
}}
""",
encoding="utf-8",
)
return catalog_path
def _reuse_library_catalog(library: Path) -> dict[str, Any]:
catalog_path = library / "courses.json"
if not catalog_path.is_file():
raise MoodleError(f"{catalog_path} does not exist; build the library online first")
try:
catalog = json.loads(catalog_path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError) as exc:
raise MoodleError(f"could not read the existing course catalog: {exc}") from exc
catalog["schema_version"] = 3
total_files = 0
total_records = 0
total_downloaded = 0
total_downloaded_bytes = 0
for course in catalog.get("courses", []):
course_id = int(course.get("id") or 0)
course_file_count = 0
course_downloaded = 0
course_downloaded_bytes = 0
for section in course.get("sections", []):
for item in section.get("items", []):
item["title"] = html.unescape(str(item.get("title") or ""))
item["description"] = html.unescape(str(item.get("description") or ""))
key = _activity_directory_name(
item.get("section_number", section.get("number")),
item.get("activity_position"),
item.get("activity_id"),
fallback=f"{course_id}\0{item.get('source_url', '')}\0{item.get('title', '')}",
)
activity_directory = _course_content_root(library, course_id) / key
metadata = _read_json_object(activity_directory / "item.json")
local_files = [
activity_directory / str(relative)
for relative in metadata.get("files", [])
if (activity_directory / str(relative)).is_file()
]
filename = str(item.get("filename") or "")
if filename:
course_file_count += 1
if not local_files and filename:
expected = activity_directory / "files" / filename
if expected.is_file():
local_files = [expected]
local_path = next((path for path in local_files if not filename or path.name == filename), None)
local_path = local_path or (local_files[0] if local_files else None)
if local_path:
local_bytes = local_path.stat().st_size
if not filename:
course_file_count += 1
item.update(
{
"filename": local_path.name,
"extension": local_path.suffix.removeprefix(".").casefold(),
"status": "downloaded",
"size": local_bytes,
"local_bytes": local_bytes,
"local_url": _relative_browser_path(local_path, library),
"artifacts": _discover_artifacts(activity_directory, library),
}
)
if item.get("activity_type") == "quiz":
item["kind"] = "assessment"
course_downloaded += 1
course_downloaded_bytes += local_bytes
elif item.get("status") == "downloaded":
item.update({"status": "missing", "local_bytes": 0, "local_url": None, "artifacts": {}})
course["file_count"] = course_file_count
course["downloaded_count"] = course_downloaded
course["downloaded_bytes"] = course_downloaded_bytes
course_records = [item for section in course.get("sections", []) for item in section.get("items", [])]
type_counts: dict[str, int] = {}
for item in course_records:
kind = str(item.get("kind") or "activity")
type_counts[kind] = type_counts.get(kind, 0) + 1
course["record_count"] = len(course_records)
course["type_counts"] = type_counts
total_files += course_file_count
total_records += len(course_records)
total_downloaded += course_downloaded
total_downloaded_bytes += course_downloaded_bytes
stats = catalog.setdefault("stats", {})
stats.update(
{
"files": total_files,
"records": total_records,
"downloaded_files": total_downloaded,
"downloaded_bytes": total_downloaded_bytes,
}
)
catalog["prepared_at"] = datetime.now(timezone.utc).isoformat()
return catalog