isolate library web root and add secure Nginx setup

This commit is contained in:
Meghdad committed 2026-08-03 00:56:33 +03:30
1 parent c8ede57792
commit af78a66366
4 files changed
+285 -21

No files matched your search

+188 -15
View File
@@ -223,7 +223,7 @@ class _CourseStructureParser(HTMLParser):
if self._activity is not None:
activity_name = values.get("data-activityname")
if activity_name and not self._activity["name"]:
self._activity["name"] = " ".join(activity_name.split())
self._activity["name"] = " ".join(html.unescape(activity_name).split())
if tag == "a" and values.get("href") and "/mod/" in (values.get("href") or ""):
self._activity["url"] = urllib.parse.urljoin(self.base_url, values["href"] or "")
if "activity-description" in classes:
@@ -439,6 +439,8 @@ class MoodleClient:
raise MoodleError(f"HTTP {exc.code} from {url}: {detail or exc.reason}") from exc
except urllib.error.URLError as exc:
raise MoodleError(f"Could not connect to {url}: {exc.reason}") from exc
except (TimeoutError, http.client.HTTPException) as exc:
raise MoodleError(f"connection to {url} failed: {exc}") from exc
def _read_text(self, path_or_url: str, **kwargs: Any) -> tuple[str, str, Any]:
with self._request(path_or_url, **kwargs) as response:
@@ -1334,12 +1336,12 @@ def _resource_kind(item: FileItem) -> str:
return "file"
def _browser_path(path: Path, relative_to: Path) -> str:
relative = Path(os.path.relpath(path, relative_to))
return "/".join(
part if part in {".", ".."} else urllib.parse.quote(part)
for part in relative.parts
)
def _media_browser_path(path: Path, downloads: Path) -> str:
try:
relative = path.resolve().relative_to(downloads.resolve())
except ValueError as exc:
raise MoodleError(f"downloaded file is outside the configured download root: {path}") from exc
return "media/" + "/".join(urllib.parse.quote(part) for part in relative.parts)
def _local_resource(item: FileItem, downloads: Path) -> tuple[str, Path | None]:
@@ -1431,7 +1433,7 @@ def _build_library_catalog(
"status": status,
"size": local_bytes if status == "downloaded" else item.filesize,
"local_bytes": local_bytes,
"local_url": _browser_path(local_path, output) if status == "downloaded" and local_path else None,
"local_url": _media_browser_path(local_path, downloads) if status == "downloaded" and local_path else None,
"source_url": activity_metadata.get("url") or f"{client.site}/course/view.php?id={course.id}",
"lms_completed": activity_metadata.get("lms_completed"),
}
@@ -1571,8 +1573,9 @@ def _build_library_catalog(
}
def _write_library_site(output: Path, catalog: dict[str, Any]) -> Path:
def _write_library_site(output: Path, catalog: dict[str, Any], downloads: Path) -> Path:
output.mkdir(parents=True, exist_ok=True)
downloads.mkdir(parents=True, exist_ok=True)
asset_root = resources.files("ravin_downloader_assets")
for name in LIBRARY_ASSETS:
(output / name).write_bytes(asset_root.joinpath(name).read_bytes())
@@ -1581,9 +1584,162 @@ def _write_library_site(output: Path, catalog: dict[str, Any]) -> Path:
json.dumps(catalog, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
media_link = output / "media"
relative_target = Path(os.path.relpath(downloads.resolve(), output.resolve()))
if os.path.lexists(media_link):
if not media_link.is_symlink() or media_link.resolve() != downloads.resolve():
raise MoodleError(
f"{media_link} already exists and is not the expected download symlink; "
"move it aside and rebuild the library"
)
else:
try:
media_link.symlink_to(relative_target, target_is_directory=True)
except OSError as exc:
raise MoodleError(f"could not create media symlink {media_link}: {exc}") from exc
quoted_root = json.dumps(str(output.resolve()))
(output / "nginx-server.conf").write_text(
f"""# Generated by ravin-downloader. 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 /media/ {{
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(output: Path, downloads: Path) -> dict[str, Any]:
catalog_path = output / "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
total_files = 0
total_downloaded = 0
total_downloaded_bytes = 0
for course in catalog.get("courses", []):
course_id = int(course.get("id") or 0)
course_root = downloads / _clean_name(str(course_id), "course")
mapped_files: dict[str, str] = {}
files_map = course_root / "files-map.txt"
if files_map.is_file():
for line in files_map.read_text(encoding="utf-8", errors="replace").splitlines():
parts = line.strip().split(" / ")
if len(parts) < 3:
continue
activity_name = re.sub(r"\s*فایل\s*$", "", html.unescape(parts[-2])).strip().casefold()
mapped_files[activity_name] = parts[-1].strip()
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 ""))
local_url = item.get("local_url")
if local_url and not str(local_url).startswith("media/"):
previous_path = (output / urllib.parse.unquote(str(local_url))).resolve()
item["local_url"] = _media_browser_path(previous_path, downloads)
filename = str(item.get("filename") or "")
if not filename and item.get("activity_type") == "resource":
activity_key = re.sub(
r"\s*فایل\s*$",
"",
html.unescape(str(item.get("title") or "")),
).strip().casefold()
filename = mapped_files.get(activity_key, "")
if filename:
item["filename"] = filename
item["extension"] = Path(filename).suffix.removeprefix(".").casefold()
guessed_type = mimetypes.guess_type(filename)[0] or ""
item["mimetype"] = guessed_type
synthetic = FileItem(
course_id=course_id,
section="Course files",
activity=str(item.get("title") or filename),
filename=filename,
url="",
mimetype=guessed_type,
)
item["kind"] = _resource_kind(synthetic)
if not filename:
continue
course_file_count += 1
matching = [
path
for path in course_root.rglob(filename)
if path.is_file() and not path.name.endswith(".part")
] if course_root.is_dir() else []
if len(matching) == 1:
local_path = matching[0]
local_bytes = local_path.stat().st_size
item.update(
{
"status": "downloaded",
"size": local_bytes,
"local_bytes": local_bytes,
"local_url": _media_browser_path(local_path, downloads),
}
)
course_downloaded += 1
course_downloaded_bytes += local_bytes
elif item.get("status") == "downloaded":
item.update({"status": "missing", "local_bytes": 0, "local_url": None})
course["file_count"] = course_file_count
course["downloaded_count"] = course_downloaded
course["downloaded_bytes"] = course_downloaded_bytes
total_files += course_file_count
total_downloaded += course_downloaded
total_downloaded_bytes += course_downloaded_bytes
stats = catalog.setdefault("stats", {})
stats.update(
{
"files": total_files,
"downloaded_files": total_downloaded,
"downloaded_bytes": total_downloaded_bytes,
}
)
catalog["prepared_at"] = datetime.now(timezone.utc).isoformat()
return catalog
class _RangeRequestHandler(http.server.SimpleHTTPRequestHandler):
"""Static-file handler with byte ranges for efficient local media playback."""
@@ -1591,6 +1747,11 @@ class _RangeRequestHandler(http.server.SimpleHTTPRequestHandler):
def send_head(self) -> Any:
self._byte_range = None
request_path = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path)
request_parts = [part for part in request_path.split("/") if part]
if any(part.startswith(".") for part in request_parts) or request_path.casefold().endswith(".part"):
self.send_error(404, "File not found")
return None
path = self.translate_path(self.path)
if os.path.isdir(path):
return super().send_head()
@@ -1658,16 +1819,16 @@ def _serve_library(site_dir: Path, downloads: Path, host: str, port: int, open_b
downloads = downloads.expanduser().resolve()
if not (site_dir / "index.html").is_file() or not (site_dir / "courses.json").is_file():
raise MoodleError(f"{site_dir} is not built yet; run `ravin-downloader library` first")
if site_dir.parent != downloads.parent:
raise MoodleError("the site directory and downloads directory must share the same parent")
handler = functools.partial(_RangeRequestHandler, directory=str(site_dir.parent))
media_link = site_dir / "media"
if not media_link.is_symlink() or media_link.resolve() != downloads:
raise MoodleError(f"the media symlink is missing or incorrect; run `ravin-downloader library` again")
handler = functools.partial(_RangeRequestHandler, directory=str(site_dir))
try:
server = http.server.ThreadingHTTPServer((host, port), handler)
except OSError as exc:
raise MoodleError(f"could not start the library server on {host}:{port}: {exc}") from exc
display_host = "localhost" if host in {"127.0.0.1", "0.0.0.0", "::"} else host
site_name = urllib.parse.quote(site_dir.name)
url = f"http://{display_host}:{server.server_port}/{site_name}/"
url = f"http://{display_host}:{server.server_port}/"
print(f"Learning Library: {url}")
print("Press Ctrl+C to stop.")
if open_browser:
@@ -1755,6 +1916,11 @@ def build_parser() -> argparse.ArgumentParser:
library_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all courses")
library_parser.add_argument("--output", type=Path, default=Path("library"), help="generated site directory")
library_parser.add_argument("--downloads", type=Path, default=Path("downloads"), help="download root to index")
library_parser.add_argument(
"--reuse-catalog",
action="store_true",
help="prepare pages, media symlink, and Nginx config without contacting the LMS",
)
serve_parser = subparsers.add_parser("serve-library", help="serve the generated library locally")
serve_parser.add_argument("--site-dir", type=Path, default=Path("library"), help="generated site directory")
serve_parser.add_argument("--downloads", type=Path, default=Path("downloads"), help="download root")
@@ -1770,6 +1936,13 @@ def main(argv: list[str] | None = None) -> int:
if args.command == "serve-library":
_serve_library(args.site_dir, args.downloads, args.host, args.port, args.open)
return 0
if args.command == "library" and args.reuse_catalog:
output = args.output.expanduser().resolve()
downloads = args.downloads.expanduser().resolve()
catalog = _reuse_library_catalog(output, downloads)
catalog_path = _write_library_site(output, catalog, downloads)
print(f"Prepared {catalog_path}, media symlink, and Nginx configuration from existing data.")
return 0
args.env_values = _load_env_file(args.env_file)
if args.command == "login":
client, mode = _authenticate_browser_session(args)
@@ -1817,7 +1990,7 @@ def main(argv: list[str] | None = None) -> int:
output = args.output.expanduser().resolve()
downloads = args.downloads.expanduser().resolve()
catalog = _build_library_catalog(client, downloads, output, args.course_ids)
catalog_path = _write_library_site(output, catalog)
catalog_path = _write_library_site(output, catalog, downloads)
print(f"Generated {catalog_path} and the static library pages.")
print("View it with: ravin-downloader serve-library --open")
return 0