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

+2
View File
@@ -9,6 +9,8 @@ All notable changes to this project will be documented here.
- Add course search, file filters, video playback, dark mode, and local completion tracking.
- Preserve Moodle chapter ordering and include forums, quizzes, live classes, and course links.
- Stream local media with HTTP byte-range support for efficient seeking.
- Make `library/` a standalone safe web root with a `media` download symlink and generated Nginx server block.
- Add offline catalog reuse for rebuilding the static/Nginx layout without contacting the LMS.
- Add `library` and `serve-library` commands while keeping generated enrollment data private.
## 0.2.0 - 2026-08-02
+37 -3
View File
@@ -93,9 +93,9 @@ ravin-downloader library
ravin-downloader serve-library --open
```
The first command refreshes `library/courses.json` from the LMS and copies the static HTML, CSS, and JavaScript pages into `library/`. The catalog preserves the LMS chapter order and includes section IDs and summaries, every activity and its type, lesson descriptions, LMS completion state, original filenames, MIME types, sizes, extensions, local download status, and safe LMS activity links. It does not copy the large course files. The pages link to the originals under `downloads/`, keeping their original filenames.
The first command refreshes `library/courses.json` from the LMS and prepares `library/` as a self-contained web root. The catalog preserves the LMS chapter order and includes section IDs and summaries, every activity and its type, lesson descriptions, LMS completion state, original filenames, MIME types, sizes, extensions, local download status, and safe LMS activity links. Large course files are not copied: `library/media` is a relative symlink that points only to `downloads/`.
The second command serves both directories locally at `http://localhost:8765/library/`. The library includes course search, true chapter grouping, offline progress, resource filters, efficient seekable video playback, document links, online LMS activities, dark mode, and completion checkboxes saved in your browser. Run `ravin-downloader library` again after downloading new files to refresh the catalog.
The second command serves only the prepared web root at `http://localhost:8765/`. The library includes course search, true chapter grouping, offline progress, resource filters, efficient seekable video playback, document links, online LMS activities, dark mode, and completion checkboxes saved in your browser. Run `ravin-downloader library` again after downloading new files to refresh the catalog.
To build only selected courses or choose other directories:
@@ -104,7 +104,41 @@ ravin-downloader library 44 --output library --downloads downloads
ravin-downloader serve-library --site-dir library --downloads downloads --port 8765
```
The generated `library/` directory is Git-ignored because its JSON contains details about your enrollments. No passwords, cookies, session tokens, or remote file URLs are written to the catalog.
If the catalog data is already current and you only need to rebuild the pages, symlink, or Nginx configuration, no LMS connection is required:
```bash
ravin-downloader library --reuse-catalog
```
The generated directory contains:
```text
library/
├── index.html
├── course.html
├── app.js
├── styles.css
├── courses.json
├── nginx-server.conf
└── media -> ../downloads
```
For Nginx, include the generated server block inside the `http {}` section of your main configuration:
```nginx
include /absolute/path/to/your/clone/library/nginx-server.conf;
```
Then check and reload Nginx:
```bash
nginx -t
brew services restart nginx
```
Open `http://localhost:8765/`. Nginx now uses `library/` as its complete document root. The repository, `.env`, browser profile, source code, and Git metadata are outside that root and cannot be requested through the site. Only the explicit `media` symlink exposes `downloads/`.
The generated `library/` directory is Git-ignored because its JSON contains details about your enrollments. No passwords, cookies, session tokens, or remote protected-file URLs are written to the catalog.
The saved session is checked on every run. When it expires or Cloudflare rejects it, the authentication browser opens automatically and replaces the saved values. You can force that refresh yourself with:
+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
+58 -3
View File
@@ -25,6 +25,7 @@ from ravin_downloader import (
_is_cloudflare_challenge,
_load_env_file,
_parse_moodle_config,
_reuse_library_catalog,
_save_env_values,
_write_library_site,
_unique,
@@ -80,9 +81,10 @@ class ParserTests(unittest.TestCase):
self.assertFalse(args.manual_session)
def test_library_commands_parse(self):
build = build_parser().parse_args(["library", "44", "--output", "my-library"])
build = build_parser().parse_args(["library", "44", "--output", "my-library", "--reuse-catalog"])
self.assertEqual(build.course_ids, [44])
self.assertEqual(build.output, Path("my-library"))
self.assertTrue(build.reuse_catalog)
serve = build_parser().parse_args(["serve-library", "--port", "9000"])
self.assertEqual(serve.port, 9000)
@@ -322,13 +324,66 @@ class ParserTests(unittest.TestCase):
self.assertEqual(items[0]["title"], "Introduction")
self.assertEqual(items[0]["kind"], "video")
self.assertEqual(items[0]["status"], "downloaded")
self.assertEqual(items[0]["local_url"], "../downloads/44/Course%20files/1.mp4")
self.assertEqual(items[0]["local_url"], "media/44/Course%20files/1.mp4")
self.assertEqual(items[1]["status"], "missing")
catalog_path = _write_library_site(output, catalog)
catalog_path = _write_library_site(output, catalog, downloads)
written = json.loads(catalog_path.read_text(encoding="utf-8"))
self.assertEqual(written["schema_version"], 2)
self.assertTrue((output / "index.html").is_file())
self.assertTrue((output / "course.html").is_file())
self.assertTrue((output / "media").is_symlink())
self.assertEqual((output / "media").resolve(), downloads.resolve())
nginx_config = (output / "nginx-server.conf").read_text(encoding="utf-8")
self.assertIn(f"root \"{output.resolve()}\";", nginx_config)
self.assertNotIn(str(root / ".env"), nginx_config)
def test_reuses_catalog_and_migrates_old_download_links(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
output = root / "library"
downloads = root / "downloads"
media = downloads / "44" / "Course files" / "1.mp4"
media.parent.mkdir(parents=True)
media.write_bytes(b"video")
(downloads / "44" / "files-map.txt").write_text(
" 1. ? Course files / Introduction to Networks فایل / 1.mp4\n",
encoding="utf-8",
)
output.mkdir()
(output / "courses.json").write_text(
json.dumps(
{
"courses": [
{
"id": 44,
"sections": [
{
"items": [
{"local_url": "../downloads/44/Course%20files/1.mp4"},
{
"local_url": None,
"filename": "",
"activity_type": "resource",
"title": "Introduction to Networks",
"status": "online",
},
]
}
]
}
]
}
),
encoding="utf-8",
)
catalog = _reuse_library_catalog(output, downloads)
item = catalog["courses"][0]["sections"][0]["items"][0]
self.assertEqual(item["local_url"], "media/44/Course%20files/1.mp4")
recovered = catalog["courses"][0]["sections"][0]["items"][1]
self.assertEqual(recovered["filename"], "1.mp4")
self.assertEqual(recovered["status"], "downloaded")
self.assertEqual(recovered["kind"], "video")
self.assertIn("prepared_at", catalog)
def test_interrupted_download_retries_with_range(self):
first = _FakeResponse(