refactor: restructure package and rename CLI to ravin

This commit is contained in:
Meghdad committed 2026-08-04 17:09:02 +03:30
1 parent af78a66366
commit 2580d86984
26 files changed
+2923 -2118

No files matched your search

+1
View File
@@ -1,4 +1,5 @@
# Byte-compiled / optimized / DLL files
.DS_Store
__pycache__/
*.py[cod]
*$py.class
+19
View File
@@ -2,6 +2,25 @@
All notable changes to this project will be documented here.
## 0.5.0 - 2026-08-04
- Replace the `ravin-downloader` console command with the shorter `ravin` command.
- Make browser automation part of the default installation, so `python3 -m pip install .` is sufficient.
- Move the project into a standard `src/ravin/` package layout.
- Split the former monolithic module into dedicated CLI, authentication, client, parser, path, catalog, migration, server, and model modules.
- Move static library assets into the package and move tests under `tests/`.
- Remove the old root module and its legacy installed package files.
## 0.4.0 - 2026-08-04
- Store downloads directly in ordered library activity bundles named `SECTION_NUMBER--ACTIVITY_POSITION--ACTIVITY_ID`.
- Preserve original filenames while keeping LMS titles and activity metadata in portable `item.json` files.
- Add an offline `migrate-library` command for the previous flat download layout.
- Normalize transcript metadata and summary references so they contain no machine-specific absolute paths.
- Place local exams in their actual LMS position and expose them as assessment records.
- Add built-in transcript, summary, and Markdown exam-question readers to the static library.
- Remove the download-directory media symlink; the library is now the only served content root.
## 0.3.0 - 2026-08-02
- Add a generated static Learning Library with responsive course and resource pages.
+2 -2
View File
@@ -10,8 +10,8 @@ Contributions are welcome. Keep changes focused, dependency-free where practical
4. Run:
```bash
python3 -m unittest -v
python3 -m py_compile ravin_downloader.py
python3 -m unittest discover -s tests -v
python3 -m compileall -q src tests
```
5. Open a pull request describing the problem, approach, and test coverage.
+2
View File
@@ -4,3 +4,5 @@ include CONTRIBUTING.md
include SECURITY.md
include CHANGELOG.md
include .env.example
recursive-include src/ravin/assets *.html *.css *.js
recursive-include tests *.py
+66 -33
View File
@@ -1,6 +1,6 @@
# Ravin Moodle Downloader
A dependency-free command-line client that lists your enrolled Moodle courses and downloads accessible course files. It defaults to Ravin Academy, but accepts another Moodle base URL through `--site`.
A lightweight command-line client that lists your enrolled Moodle courses, downloads accessible course files, and builds a private learning library. It defaults to Ravin Academy, but accepts another Moodle base URL through `--site`.
The client first tries Moodle's official mobile web-service API and falls back to a normal web login plus Moodle's authenticated AJAX interface. For sites protected by Cloudflare, it can establish and refresh an authenticated browser session automatically.
@@ -12,50 +12,50 @@ The client first tries Moodle's official mobile web-service API and falls back t
- Python 3.10 or newer
- An active enrollment on the target Moodle site
The downloader itself uses only Python's standard library. Automatic browser login uses the optional Selenium package with an installed Zen, Firefox, Chrome, Chromium, or Brave browser.
The downloader core uses Python's standard library. Selenium is installed automatically because browser authentication is the normal path for Cloudflare-protected LMS sites. You also need an installed Zen, Firefox, Chrome, Chromium, or Brave browser.
## Installation
After cloning or downloading the repository, install the command from its root directory:
```bash
python3 -m pip install '.[browser]'
python3 -m pip install .
```
You can then use `ravin-downloader` from any shell. Running `python3 ravin_downloader.py` directly from the repository remains supported.
You can then use `ravin` from any shell. The equivalent module entry point is `python3 -m ravin`.
## Quick start
```bash
ravin-downloader login
ravin-downloader courses
ravin-downloader files COURSE_ID
ravin-downloader download COURSE_ID
ravin-downloader library
ravin-downloader serve-library --open
ravin login
ravin courses
ravin files COURSE_ID
ravin download COURSE_ID
ravin library
ravin serve-library --open
```
Files are saved under `downloads/<course-id>/...`. Existing completed files are skipped; interrupted downloads use a temporary `.part` suffix and resume automatically with HTTP byte-range requests. Use `--overwrite` if you want to replace existing files, or `--retries` to change the default five retries per file.
Files are saved directly in the private static library under `library/courses/<course-id>/content/`. Every activity uses the sortable `SECTION_NUMBER--ACTIVITY_POSITION--ACTIVITY_ID` directory format, while its real LMS title and metadata live in `item.json`. Original filenames are preserved inside each activity's `files/` directory. Existing completed files are skipped; interrupted downloads use a temporary `.part` suffix and resume automatically with HTTP byte-range requests.
For scripting, use JSON output:
```bash
ravin-downloader --json courses
ravin-downloader --json files COURSE_ID
ravin --json courses
ravin --json files COURSE_ID
```
## Configuration
On first use, missing values are requested interactively and saved in `.env` in the current directory. Copy [`.env.example`](.env.example) if you prefer to configure it manually. The file is Git-ignored and written with owner-only permissions.
`ravin-downloader login` opens an installed browser using the Git-ignored `.ravin-browser-profile/` directory. For Ravin Academy it starts at `https://lms.ravinacademy.com/`, signs in there, follows the available Moodle course-launch link, and captures the resulting session on `training.ravinacademy.com`. If `.env` already contains `RAVIN_USERNAME` and `RAVIN_PASSWORD`, a compatible login form is filled automatically. Once login succeeds, the browser closes and `.env` is updated with the exact User-Agent and cookies. Use `--browser-executable /path/to/browser` to override automatic detection.
`ravin login` opens an installed browser using the Git-ignored `.ravin-browser-profile/` directory. For Ravin Academy it starts at `https://lms.ravinacademy.com/`, signs in there, follows the available Moodle course-launch link, and captures the resulting session on `training.ravinacademy.com`. If `.env` already contains `RAVIN_USERNAME` and `RAVIN_PASSWORD`, a compatible login form is filled automatically. Once login succeeds, the browser closes and `.env` is updated with the exact User-Agent and cookies. Use `--browser-executable /path/to/browser` to override automatic detection.
Never commit or share `.env`. It may contain both account credentials and a temporary authenticated browser session.
If the academy disables its mobile token service, the fallback is automatic. You can force that path for troubleshooting:
```bash
ravin-downloader --web-only --username YOUR_USERNAME courses
ravin --web-only --username YOUR_USERNAME courses
```
## Browser login and Cloudflare
@@ -63,8 +63,8 @@ ravin-downloader --web-only --username YOUR_USERNAME courses
Ravin Academy protects its account portal and Moodle with a browser check. Set up the browser helper once:
```bash
python3 -m pip install '.[browser]'
ravin-downloader login
python3 -m pip install .
ravin login
```
After authentication, `.env` can contain these values:
@@ -80,8 +80,8 @@ RAVIN_COOKIE="the complete browser Cookie header"
Later commands reuse `.env`, so you can simply run:
```bash
ravin-downloader files 44
ravin-downloader download 44
ravin files 44
ravin download 44
```
## Static course library
@@ -89,25 +89,25 @@ ravin-downloader download 44
Build a clean local website from your enrolled courses and downloaded files:
```bash
ravin-downloader library
ravin-downloader serve-library --open
ravin library
ravin serve-library --open
```
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 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 availability, learning artifacts, and safe LMS activity links. Course files already live inside this web root, so no project-level directories or symlinks are exposed.
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.
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 and exam links, transcript and summary readers, Markdown exam questions, online LMS activities, dark mode, and completion checkboxes saved in your browser.
To build only selected courses or choose other directories:
```bash
ravin-downloader library 44 --output library --downloads downloads
ravin-downloader serve-library --site-dir library --downloads downloads --port 8765
ravin library 44 --output library
ravin serve-library --site-dir library --port 8765
```
If the catalog data is already current and you only need to rebuild the pages, symlink, or Nginx configuration, no LMS connection is required:
If the catalog data is already current and you only need to rescan local artifacts or rebuild the pages and Nginx configuration, no LMS connection is required:
```bash
ravin-downloader library --reuse-catalog
ravin library --reuse-catalog
```
The generated directory contains:
@@ -120,7 +120,14 @@ library/
├── styles.css
├── courses.json
├── nginx-server.conf
└── media -> ../downloads
└── courses/
└── COURSE_ID/
├── course.json
└── content/
└── SECTION--POSITION--ACTIVITY/
├── item.json
├── files/
└── artifacts/
```
For Nginx, include the generated server block inside the `http {}` section of your main configuration:
@@ -136,31 +143,57 @@ 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/`.
Open `http://localhost:8765/`. Nginx uses `library/` as its complete document root. The repository, `.env`, browser profile, source code, and Git metadata remain outside that root and cannot be requested through the site.
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.
### Migrating the legacy download layout
Repositories created before version 0.4 can migrate their existing files without downloading them again:
```bash
ravin migrate-library --source downloads --library library
```
The migration uses the existing LMS catalog to place resources and exams in course order, moves transcripts and summaries into `artifacts/`, converts machine-specific metadata paths to relative paths, and writes a per-course `migration.json` journal.
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:
```bash
ravin-downloader --refresh-session courses
ravin --refresh-session courses
```
If browser automation is unavailable, manual header entry remains available as a fallback:
```bash
ravin-downloader --manual-session --refresh-session courses
ravin --manual-session --refresh-session courses
```
Never send `.env`, `.ravin-browser-profile/`, your password, or its Cookie value to another person; they grant access to your LMS account or signed-in session.
## Development
The project uses a standard `src/` package layout:
```text
src/ravin/
├── cli.py # command parsing and orchestration
├── auth.py # environment and browser authentication
├── client.py # Moodle API/web client and downloads
├── parsers.py # Moodle HTML parsers
├── paths.py # portable content paths and metadata
├── catalog.py # static catalog generation
├── migration.py # legacy layout migration
├── server.py # local range-aware HTTP server
├── models.py # shared data objects and errors
└── assets/ # packaged static library UI
```
Run the test suite without installing additional packages:
```bash
python3 -m unittest -v
python3 -m py_compile ravin_downloader.py
python3 -m unittest discover -s tests -v
python3 -m compileall -q src tests
```
See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidance and [SECURITY.md](SECURITY.md) for reporting security issues.
+8 -9
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ravin-moodle-downloader"
version = "0.3.0"
version = "0.5.0"
description = "List and download authorized course files from Ravin Academy or another Moodle site"
readme = "README.md"
requires-python = ">=3.10"
@@ -24,17 +24,16 @@ classifiers = [
"Programming Language :: Python :: 3.14",
"Topic :: Education",
]
dependencies = []
[project.optional-dependencies]
browser = ["selenium>=4.46,<5"]
dependencies = ["selenium>=4.46,<5"]
[project.scripts]
ravin-downloader = "ravin_downloader:main"
ravin = "ravin.cli:main"
[tool.setuptools]
py-modules = ["ravin_downloader"]
packages = ["ravin_downloader_assets"]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
ravin_downloader_assets = ["*.html", "*.css", "*.js"]
"ravin.assets" = ["*.html", "*.css", "*.js"]
-2034
View File
File diff suppressed because it is too large. Load diff
+7
View File
@@ -0,0 +1,7 @@
"""Ravin Academy Moodle downloader and private learning library."""
from .client import MoodleClient
from .constants import __version__
from .models import Course, FileItem, MoodleError
__all__ = ["Course", "FileItem", "MoodleClient", "MoodleError", "__version__"]
+6
View File
@@ -0,0 +1,6 @@
"""Allow ``python -m ravin`` to run the CLI."""
from .cli import main
raise SystemExit(main())
File renamed without changes.
@@ -25,6 +25,108 @@ function setText(id, value) {
if (element) element.textContent = value;
}
function appendMarkdownInline(parent, text) {
const pattern = /(\*\*[^*]+\*\*|`[^`]+`|\[[^\]]+\]\([^)]+\))/g;
let offset = 0;
for (const match of text.matchAll(pattern)) {
parent.append(document.createTextNode(text.slice(offset, match.index)));
const token = match[0];
if (token.startsWith("**")) {
const strong = document.createElement("strong");
strong.textContent = token.slice(2, -2);
parent.append(strong);
} else if (token.startsWith("`")) {
const code = document.createElement("code");
code.textContent = token.slice(1, -1);
parent.append(code);
} else {
const parts = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
const link = document.createElement("a");
link.textContent = parts[1];
if (/^(https?:\/\/|\.\.?\/)/.test(parts[2])) {
link.href = parts[2];
link.target = "_blank";
link.rel = "noopener";
}
parent.append(link);
}
offset = match.index + token.length;
}
parent.append(document.createTextNode(text.slice(offset)));
}
function markdownCells(line) {
return line.trim().replace(/^\||\|$/g, "").split("|").map((cell) => cell.trim());
}
function renderMarkdown(target, source) {
target.innerHTML = "";
const lines = source.replace(/\r\n?/g, "\n").split("\n");
let list = null;
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
if (!line.trim()) {
list = null;
continue;
}
const heading = line.match(/^(#{1,4})\s+(.+)$/);
if (heading) {
list = null;
const element = document.createElement(`h${heading[1].length}`);
appendMarkdownInline(element, heading[2]);
target.append(element);
continue;
}
if (line.includes("|") && index + 1 < lines.length && /^\s*\|?\s*:?-{3,}/.test(lines[index + 1])) {
list = null;
const table = document.createElement("table");
const head = document.createElement("thead");
const headRow = document.createElement("tr");
markdownCells(line).forEach((cell) => {
const th = document.createElement("th");
appendMarkdownInline(th, cell);
headRow.append(th);
});
head.append(headRow);
table.append(head);
const body = document.createElement("tbody");
index += 2;
while (index < lines.length && lines[index].includes("|") && lines[index].trim()) {
const row = document.createElement("tr");
markdownCells(lines[index]).forEach((cell) => {
const td = document.createElement("td");
appendMarkdownInline(td, cell);
row.append(td);
});
body.append(row);
index += 1;
}
index -= 1;
table.append(body);
target.append(table);
continue;
}
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
const numbered = line.match(/^\s*\d+[.)]\s+(.+)$/);
if (bullet || numbered) {
const type = bullet ? "ul" : "ol";
if (!list || list.tagName.toLowerCase() !== type) {
list = document.createElement(type);
target.append(list);
}
const item = document.createElement("li");
appendMarkdownInline(item, (bullet || numbered)[1]);
list.append(item);
continue;
}
list = null;
const quote = line.match(/^>\s?(.*)$/);
const paragraph = document.createElement(quote ? "blockquote" : "p");
appendMarkdownInline(paragraph, quote ? quote[1] : line);
target.append(paragraph);
}
}
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
localStorage.setItem("ravin-library-theme", theme);
@@ -54,7 +156,7 @@ function showLoadError(error) {
const title = document.createElement("strong");
title.textContent = "The course data could not be loaded";
const detail = document.createElement("span");
detail.textContent = "Open this library with ‘ravin-downloader serve-library’, then refresh the page.";
detail.textContent = "Open this library with ‘ravin serve-library’, then refresh the page.";
box.append(title, detail);
target.append(box);
console.error(error);
@@ -164,6 +266,25 @@ function resourceRow(item, index) {
description.textContent = item.description;
main.append(description);
}
const artifactLabels = {
questions: "Questions",
summary: "Summary",
transcript: "Transcript",
};
const availableArtifacts = Object.keys(artifactLabels).filter((kind) => item.artifacts?.[kind]?.url);
if (availableArtifacts.length) {
const artifactActions = document.createElement("div");
artifactActions.className = "artifact-actions";
availableArtifacts.forEach((kind) => {
const button = document.createElement("button");
button.type = "button";
button.className = "artifact-button";
button.textContent = artifactLabels[kind];
button.addEventListener("click", () => openArtifact(item, kind));
artifactActions.append(button);
});
main.append(artifactActions);
}
const meta = document.createElement("div");
meta.className = "resource-meta";
@@ -274,6 +395,39 @@ function closeVideo() {
dialog.close();
}
async function openArtifact(item, kind) {
const artifact = item.artifacts?.[kind];
if (!artifact) return;
const dialog = byId("artifactDialog");
const content = byId("artifactContent");
const labels = { questions: "Exam questions", summary: "Lesson summary", transcript: "Transcript" };
setText("artifactEyebrow", labels[kind] || "Course material");
setText("artifactTitle", item.title);
content.innerHTML = '<p class="artifact-loading">Loading…</p>';
dialog.showModal();
try {
const response = await fetch(artifact.url, { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load ${artifact.url} (${response.status})`);
const source = await response.text();
if (artifact.format === "markdown") renderMarkdown(content, source);
else {
content.innerHTML = "";
const transcript = document.createElement("pre");
transcript.className = "transcript-text";
transcript.textContent = source;
content.append(transcript);
}
} catch (error) {
content.textContent = "This material could not be loaded.";
console.error(error);
}
}
function closeArtifact() {
byId("artifactDialog").close();
byId("artifactContent").innerHTML = "";
}
function renderCourse() {
const id = new URLSearchParams(window.location.search).get("id");
state.course = state.catalog.courses.find((course) => String(course.id) === String(id));
@@ -308,6 +462,10 @@ function renderCourse() {
byId("mediaDialog").addEventListener("click", (event) => {
if (event.target === byId("mediaDialog")) closeVideo();
});
byId("closeArtifact").addEventListener("click", closeArtifact);
byId("artifactDialog").addEventListener("click", (event) => {
if (event.target === byId("artifactDialog")) closeArtifact();
});
renderResources();
}
@@ -47,6 +47,7 @@
<button class="filter-chip active" type="button" data-filter="all">All</button>
<button class="filter-chip" type="button" data-filter="video">Videos</button>
<button class="filter-chip" type="button" data-filter="document">Documents</button>
<button class="filter-chip" type="button" data-filter="assessment">Exams</button>
<button class="filter-chip" type="button" data-filter="downloaded">Offline</button>
<button class="filter-chip" type="button" data-filter="missing">Missing</button>
</div>
@@ -67,6 +68,14 @@
<video id="mediaPlayer" controls preload="metadata"></video>
</dialog>
<dialog class="artifact-dialog" id="artifactDialog">
<div class="dialog-heading">
<div><p class="eyebrow" id="artifactEyebrow">Course material</p><h2 id="artifactTitle"></h2></div>
<button class="icon-button" id="closeArtifact" type="button" aria-label="Close course material">×</button>
</div>
<article class="artifact-content" id="artifactContent" dir="auto"></article>
</dialog>
<footer>
<a href="index.html">← All courses</a>
<span id="generatedAt"></span>
File renamed without changes.
@@ -336,6 +336,9 @@ main {
.resource-title { display: block; overflow: hidden; font-weight: 730; text-overflow: ellipsis; white-space: nowrap; }
.resource-file { display: block; overflow: hidden; margin-top: 4px; color: var(--muted); font-size: .78rem; text-overflow: ellipsis; white-space: nowrap; }
.resource-description { display: -webkit-box; overflow: hidden; margin-top: 5px; color: var(--muted); font-size: .76rem; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
.artifact-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 9px; }
.artifact-button { padding: 5px 9px; border: 1px solid color-mix(in srgb, var(--blue) 24%, var(--line)); border-radius: 8px; color: var(--blue); background: var(--blue-soft); cursor: pointer; font-size: .7rem; font-weight: 750; }
.artifact-button:hover { border-color: var(--blue); }
.resource-meta { display: flex; gap: 8px; align-items: center; color: var(--muted); font-size: .74rem; white-space: nowrap; }
.type-pill { padding: 4px 8px; border-radius: 8px; color: var(--blue); background: var(--blue-soft); font-weight: 750; }
.status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-strong); }
@@ -356,6 +359,19 @@ main {
.dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 16px; }
.dialog-heading h2 { margin: 4px 0 0; font-size: 1.2rem; }
.media-dialog video { display: block; width: 100%; max-height: 72vh; border-radius: 15px; background: #000; }
.artifact-dialog { width: min(920px, calc(100% - 30px)); max-height: min(88vh, 1000px); padding: 22px; border: 1px solid var(--line); border-radius: 24px; color: var(--ink); background: var(--surface); box-shadow: 0 30px 100px rgba(0,0,0,.4); }
.artifact-dialog::backdrop { background: rgba(8, 15, 17, .76); backdrop-filter: blur(7px); }
.artifact-content { overflow: auto; max-height: calc(88vh - 105px); padding: 4px 10px 24px; line-height: 1.85; }
.artifact-content h1, .artifact-content h2, .artifact-content h3, .artifact-content h4 { margin: 1.5em 0 .55em; line-height: 1.35; }
.artifact-content h1:first-child, .artifact-content h2:first-child { margin-top: .4em; }
.artifact-content p, .artifact-content li { font-size: .94rem; }
.artifact-content blockquote { margin: 1em 0; padding: 10px 16px; border-inline-start: 4px solid var(--blue); color: var(--muted); background: var(--blue-soft); }
.artifact-content code { padding: 2px 5px; border-radius: 5px; background: var(--paper); font-size: .88em; }
.artifact-content table { width: 100%; margin: 18px 0; border-collapse: collapse; font-size: .86rem; }
.artifact-content th, .artifact-content td { padding: 9px 11px; border: 1px solid var(--line); text-align: start; vertical-align: top; }
.artifact-content th { background: var(--surface-strong); }
.transcript-text { margin: 0; font: inherit; line-height: 2; white-space: pre-wrap; word-break: break-word; }
.artifact-loading { color: var(--muted); }
footer { width: min(1184px, calc(100% - 40px)); margin: 0 auto; padding: 28px 0 40px; display: flex; justify-content: space-between; gap: 20px; border-top: 1px solid var(--line); color: var(--muted); font-size: .78rem; }
footer a { text-decoration: none; font-weight: 700; }
+422
View File
@@ -0,0 +1,422 @@
"""Environment configuration and interactive browser authentication."""
import argparse
import getpass
import json
import os
import re
import shutil
import sys
import tempfile
import time
import urllib.parse
from pathlib import Path
from .client import MoodleClient
from .constants import DEFAULT_RAVIN_LOGIN_URL, ENV_KEYS
from .models import MoodleError
def _env_value(args: argparse.Namespace, key: str) -> str:
return os.environ.get(key) or args.env_values.get(key, "")
def _credentials(args: argparse.Namespace, *, fresh: bool = False) -> tuple[str, str]:
username = "" if fresh else args.username or _env_value(args, ENV_KEYS["username"])
password = "" if fresh else _env_value(args, ENV_KEYS["password"])
if not username:
username = input("LMS username: ").strip()
if not password:
password = getpass.getpass("LMS password: ")
if not username or not password:
raise MoodleError("username and password are required")
return username, password
def _load_env_file(path: Path) -> dict[str, str]:
if not path.exists():
return {}
values: dict[str, str] = {}
try:
lines = path.read_text(encoding="utf-8").splitlines()
except OSError as exc:
print(f"warning: could not read {path} ({exc})", file=sys.stderr)
return {}
for line in lines:
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
if stripped.startswith("export "):
stripped = stripped[7:].lstrip()
key, separator, raw_value = stripped.partition("=")
key = key.strip()
if not separator or not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", key):
continue
raw_value = raw_value.strip()
try:
if raw_value.startswith('"') and raw_value.endswith('"'):
value = json.loads(raw_value)
elif raw_value.startswith("'") and raw_value.endswith("'"):
value = raw_value[1:-1]
else:
value = raw_value
except json.JSONDecodeError:
value = raw_value.strip('"')
values[key] = value
return values
def _save_env_values(path: Path, updates: dict[str, str]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
try:
existing_lines = path.read_text(encoding="utf-8").splitlines() if path.exists() else []
except OSError as exc:
raise MoodleError(f"could not read {path}: {exc}") from exc
rendered = {key: f"{key}={json.dumps(value, ensure_ascii=False)}" for key, value in updates.items()}
output_lines: list[str] = []
written: set[str] = set()
assignment = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=")
for line in existing_lines:
match = assignment.match(line)
key = match.group(1) if match else ""
if key in rendered:
if key not in written:
output_lines.append(rendered[key])
written.add(key)
continue
output_lines.append(line)
for key, line in rendered.items():
if key not in written:
output_lines.append(line)
payload = "\n".join(output_lines).rstrip() + "\n"
temporary_name = ""
try:
with tempfile.NamedTemporaryFile(
mode="w",
encoding="utf-8",
dir=path.parent,
prefix=f".{path.name}.",
suffix=".tmp",
delete=False,
) as temporary:
temporary_name = temporary.name
temporary.write(payload)
os.chmod(temporary_name, 0o600)
os.replace(temporary_name, path)
os.chmod(path, 0o600)
finally:
if temporary_name:
try:
Path(temporary_name).unlink(missing_ok=True)
except OSError:
pass
def _browser_session_values(args: argparse.Namespace, *, fresh: bool = False) -> tuple[str, str] | None:
if fresh:
return None
user_agent = args.browser_user_agent or _env_value(args, ENV_KEYS["user_agent"])
cookie_header = _env_value(args, ENV_KEYS["cookie"])
if user_agent and cookie_header:
return user_agent, cookie_header
return None
def _prompt_browser_session(args: argparse.Namespace, *, fresh: bool = False) -> tuple[str, str]:
stored = _browser_session_values(args, fresh=fresh)
user_agent, cookie_header = stored or ("", "")
if not user_agent:
user_agent = input("Browser User-Agent header: ").strip()
if not cookie_header:
cookie_header = getpass.getpass("Browser Cookie header (hidden): ").strip()
if not user_agent or not cookie_header:
raise MoodleError("both the browser User-Agent and Cookie headers are required")
return user_agent, cookie_header
def _find_browser_executable(explicit: Path | None = None) -> Path | None:
if explicit:
candidate = explicit.expanduser().resolve()
return candidate if candidate.is_file() else None
candidates = [
Path("/Applications/Zen.app/Contents/MacOS/zen"),
Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
Path("/Applications/Chromium.app/Contents/MacOS/Chromium"),
Path("/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"),
Path("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
Path("/Applications/Firefox.app/Contents/MacOS/firefox"),
]
for command in ("zen", "firefox", "google-chrome", "chromium", "chromium-browser", "brave-browser"):
found = shutil.which(command)
if found:
candidates.append(Path(found))
return next((candidate for candidate in candidates if candidate.is_file()), None)
def _browser_login_url(args: argparse.Namespace) -> str:
configured = getattr(args, "login_url", None) or _env_value(args, ENV_KEYS["login_url"])
if configured:
return configured
hostname = (urllib.parse.urlsplit(args.site).hostname or "").casefold()
if hostname == "training.ravinacademy.com":
return DEFAULT_RAVIN_LOGIN_URL
return urllib.parse.urljoin(args.site.rstrip("/") + "/", "my/courses.php")
def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]:
"""Open an installed browser through Selenium and capture its authenticated session."""
try:
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
except ImportError as exc:
raise MoodleError(
"automatic browser login is not installed. Run:\n"
" python3 -m pip install ravin-moodle-downloader"
) from exc
executable = _find_browser_executable(args.browser_executable)
if executable is None:
raise MoodleError(
"no supported browser was found. Install Firefox/Zen/Chrome, or pass "
"--browser-executable /path/to/browser"
)
profile = args.browser_profile.expanduser().resolve()
profile.mkdir(parents=True, exist_ok=True, mode=0o700)
try:
os.chmod(profile, 0o700)
except OSError:
pass
browser_name = executable.name.casefold()
try:
if "firefox" in browser_name or "zen" in browser_name:
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
options = Options()
options.binary_location = str(executable)
options.add_argument("-profile")
options.add_argument(str(profile))
driver_path = shutil.which("geckodriver")
service = Service(executable_path=driver_path) if driver_path else Service()
driver = webdriver.Firefox(options=options, service=service)
else:
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = str(executable)
options.add_argument(f"--user-data-dir={profile}")
options.add_argument("--no-first-run")
driver = webdriver.Chrome(options=options)
except WebDriverException as exc:
raise MoodleError(
f"could not launch {executable.name}: {exc}. "
"Selenium Manager may need network access once to install the matching driver."
) from exc
login_url = _browser_login_url(args)
username = _env_value(args, ENV_KEYS["username"])
password = _env_value(args, ENV_KEYS["password"])
deadline = time.monotonic() + max(args.login_timeout, 30)
print(f"Opening {executable.name} for LMS authentication...", file=sys.stderr)
print("Complete Cloudflare or LMS login in that window if requested.", file=sys.stderr)
try:
driver.get(login_url)
submitted_credentials = False
credential_attempts = 0
last_location = ""
while time.monotonic() < deadline:
current_location = urllib.parse.urlsplit(driver.current_url)._replace(query="", fragment="").geturl()
if current_location != last_location:
print(f"Browser is at {current_location}", file=sys.stderr)
last_location = current_location
try:
logged_in = bool(
driver.execute_script(
"""return Boolean(
window.M && M.cfg && Number(M.cfg.userId) > 0 &&
document.querySelector('a[href*="/login/logout.php"]')
);"""
)
)
except WebDriverException:
logged_in = False
if logged_in:
cookies = driver.get_cookies()
user_agent = str(driver.execute_script("return navigator.userAgent;"))
cookie_header = "; ".join(
f"{cookie['name']}={cookie['value']}"
for cookie in cookies
if cookie.get("name") and cookie.get("value")
)
if not cookie_header:
raise MoodleError("browser login succeeded, but no site cookies were available")
return user_agent, cookie_header
# Ravin's account portal owns the login. Its Moodle launch link creates
# the session on training.ravinacademy.com and redirects there.
launch_links = driver.find_elements(
By.CSS_SELECTOR,
'a[href*="/moodle/login_student_user/"]',
)
launch_urls = [
element.get_attribute("href")
for element in launch_links
if element.is_displayed() and element.get_attribute("href")
]
if launch_urls:
print("LMS login accepted; opening the Moodle course portal.", file=sys.stderr)
driver.get(launch_urls[0])
submitted_credentials = False
continue
if submitted_credentials:
error_elements = driver.find_elements(
By.CSS_SELECTOR,
".loginerrors, .alert-danger, .invalid-feedback, "
".field-validation-error, .error-message, .toast-error, "
".swal2-validation-message, [data-region=\"login-error\"], [role=\"alert\"]",
)
error_messages = [
" ".join(element.text.split())
for element in error_elements
if element.is_displayed() and element.text.strip()
]
if error_messages:
if credential_attempts >= 3:
raise MoodleError(f"the LMS rejected the login: {error_messages[0][:300]}")
print(f"The LMS rejected the saved login: {error_messages[0][:300]}", file=sys.stderr)
print("Enter fresh credentials in this terminal.", file=sys.stderr)
username, password = _credentials(args, fresh=True)
_save_env_values(
args.env_file,
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
},
)
args.env_values.update(
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
}
)
submitted_credentials = False
if username and password and not submitted_credentials:
login_controls = driver.execute_script(
"""const visible = (element) => {
const style = window.getComputedStyle(element);
const box = element.getBoundingClientRect();
return !element.disabled && style.display !== 'none' &&
style.visibility !== 'hidden' && box.width > 0 && box.height > 0;
};
const passwords = [...document.querySelectorAll('input[type="password"]')]
.filter(visible);
if (passwords.length !== 1) return null;
const password = passwords[0];
const form = password.form || password.closest('form');
if (!form) return null;
const candidates = [...form.querySelectorAll('input')].filter((element) => {
const type = (element.type || 'text').toLowerCase();
return visible(element) && ![
'password', 'hidden', 'submit', 'button', 'checkbox',
'radio', 'file', 'reset'
].includes(type);
});
const preferred = /user|mobile|phone|email|login|national/i;
const username = candidates.find((element) => preferred.test(
`${element.name} ${element.id} ${element.autocomplete}`
)) || candidates[0];
const submits = [...form.querySelectorAll('button, input[type="submit"]')]
.filter((element) => visible(element) && element.type === 'submit');
return username && submits.length ? [username, password, submits[0]] : null;"""
)
if login_controls:
username_input, password_input, submit_button = login_controls
driver.execute_script(
"""const setValue = (element, value) => {
const setter = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value'
).set;
setter.call(element, value);
element.dispatchEvent(new Event('input', {bubbles: true}));
element.dispatchEvent(new Event('change', {bubbles: true}));
};
setValue(arguments[0], arguments[1]);
setValue(arguments[2], arguments[3]);
const form = arguments[0].closest('form');
if (form && form.requestSubmit) {
form.requestSubmit(arguments[4]);
} else {
arguments[4].click();
}""",
username_input,
username,
password_input,
password,
submit_button,
)
submitted_credentials = True
credential_attempts += 1
print("Submitted the stored LMS credentials.", file=sys.stderr)
time.sleep(1)
raise MoodleError(f"browser login did not finish within {max(args.login_timeout, 30)} seconds")
except WebDriverException as exc:
raise MoodleError(f"browser authentication failed: {exc}") from exc
finally:
driver.quit()
def _authenticate_browser_session(
args: argparse.Namespace,
saved: tuple[str, str] | None = None,
) -> tuple[MoodleClient, str]:
from_saved = saved is not None and not args.refresh_session
if from_saved:
user_agent, cookie_header = saved
elif args.manual_session:
user_agent, cookie_header = _prompt_browser_session(args, fresh=True)
else:
user_agent, cookie_header = _capture_browser_session(args)
client = MoodleClient(
args.site,
cookie_header=cookie_header,
browser_user_agent=user_agent,
)
try:
mode = client.authenticate()
except MoodleError as exc:
if not from_saved:
raise
print(f"Saved browser session is no longer valid ({exc}).", file=sys.stderr)
if args.manual_session:
print("Please paste fresh headers from a logged-in browser request.", file=sys.stderr)
user_agent, cookie_header = _prompt_browser_session(args, fresh=True)
else:
print("Opening the authentication browser to refresh it.", file=sys.stderr)
user_agent, cookie_header = _capture_browser_session(args)
client = MoodleClient(
args.site,
cookie_header=cookie_header,
browser_user_agent=user_agent,
)
mode = client.authenticate()
_save_env_values(
args.env_file,
{
ENV_KEYS["login_url"]: _browser_login_url(args),
ENV_KEYS["user_agent"]: user_agent,
ENV_KEYS["cookie"]: cookie_header,
},
)
args.env_values.update(
{
ENV_KEYS["login_url"]: _browser_login_url(args),
ENV_KEYS["user_agent"]: user_agent,
ENV_KEYS["cookie"]: cookie_header,
}
)
return client, mode
+475
View File
@@ -0,0 +1,475 @@
"""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,
)
def _format_size(size: int | None) -> str:
if size is None:
return "?"
units = ["B", "KiB", "MiB", "GiB"]
value = float(size)
for unit in units:
if value < 1024 or unit == units[-1]:
return f"{value:.1f} {unit}"
value /= 1024
return str(size)
def _resource_kind(item: FileItem) -> str:
mimetype = item.mimetype.casefold()
suffix = Path(item.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"}:
return "audio"
if (
mimetype.startswith("text/")
or mimetype in {"application/pdf", "application/msword"}
or suffix in {".pdf", ".doc", ".docx", ".ppt", ".pptx", ".txt", ".md"}
):
return "document"
if suffix in {".zip", ".rar", ".7z", ".tar", ".gz"}:
return "archive"
return "file"
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"))
if expected.is_file():
return "downloaded", expected
partial = expected.with_name(expected.name + ".part")
if partial.is_file():
return "partial", partial
if directory.is_dir():
expected_name = expected.name.casefold()
matches = [path for path in directory.iterdir() if path.is_file() and path.name.casefold() == expected_name]
if len(matches) == 1:
return "downloaded", matches[0]
return "missing", None
def _local_activity_record(
library: Path,
course_id: int,
section: dict[str, Any],
activity: dict[str, Any],
) -> tuple[dict[str, Any], Path] | None:
key = _activity_directory_name(
section.get("number"),
activity.get("position"),
activity.get("id"),
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:
return None
return metadata, directory
def _build_library_catalog(
client: MoodleClient,
library: Path,
selected_course_ids: Iterable[int] = (),
) -> dict[str, Any]:
selected_ids = set(selected_course_ids)
available_courses = client.list_courses()
courses = [course for course in available_courses if not selected_ids or course.id in selected_ids]
missing_ids = selected_ids - {course.id for course in courses}
if missing_ids:
missing = ", ".join(str(course_id) for course_id in sorted(missing_ids))
raise MoodleError(f"course ID(s) not found in your enrollments: {missing}")
catalog_courses: list[dict[str, Any]] = []
total_files = 0
total_activities = 0
total_records = 0
total_downloaded = 0
total_downloaded_bytes = 0
for course in courses:
print(f"Reading course {course.id}: {course.fullname}", file=sys.stderr)
downloaded_count = 0
downloaded_bytes = 0
items = client.list_files(course.id)
try:
structure_method = getattr(client, "course_structure")
structure = structure_method(course.id)
except (AttributeError, MoodleError):
structure = []
consumed: set[int] = set()
def file_record(
item: FileItem,
item_index: int,
section_metadata: dict[str, Any] | None = None,
activity_metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
nonlocal downloaded_count, downloaded_bytes
section_metadata = section_metadata or {}
activity_metadata = activity_metadata or {}
status, local_path = _local_resource(item, library)
local_bytes = local_path.stat().st_size if local_path else 0
if status == "downloaded":
downloaded_count += 1
downloaded_bytes += local_bytes
stable_source = urllib.parse.urlsplit(item.url)._replace(query="", fragment="").geturl()
resource_id = hashlib.sha1(
f"{course.id}\0{stable_source}\0{item.filename}".encode("utf-8")
).hexdigest()[:14]
title = activity_metadata.get("name") or re.sub(r"\s*فایل\s*$", "", item.activity).strip()
consumed.add(item_index)
activity_directory = _activity_root(library, item)
return {
"id": resource_id,
"section": item.section,
"section_id": section_metadata.get("id", item.section_id),
"section_number": section_metadata.get("number", item.section_number),
"activity_id": activity_metadata.get("id", item.activity_id),
"activity_position": activity_metadata.get("position", item.activity_position),
"activity_type": activity_metadata.get("type", item.activity_type or "resource"),
"title": title or item.filename,
"description": activity_metadata.get("description") or item.description,
"badge": activity_metadata.get("badge") or Path(item.filename).suffix.removeprefix(".").upper(),
"filename": item.filename,
"extension": Path(item.filename).suffix.removeprefix(".").casefold(),
"kind": _resource_kind(item),
"mimetype": item.mimetype,
"status": status,
"size": local_bytes if status == "downloaded" else item.filesize,
"local_bytes": local_bytes,
"local_url": _relative_browser_path(local_path, library) if status == "downloaded" and local_path else None,
"artifacts": _discover_artifacts(activity_directory, library),
"source_url": activity_metadata.get("url") or f"{client.site}/course/view.php?id={course.id}",
"lms_completed": activity_metadata.get("lms_completed"),
}
files_by_activity: dict[int, list[tuple[int, FileItem]]] = {}
for item_index, item in enumerate(items):
if item.activity_id is not None:
files_by_activity.setdefault(item.activity_id, []).append((item_index, item))
catalog_sections: list[dict[str, Any]] = []
activity_count = 0
for section in structure:
section_records: list[dict[str, Any]] = []
activities = section.get("activities", [])
activity_count += len(activities)
for activity in activities:
matches = files_by_activity.get(activity.get("id"), [])
if not matches:
activity_name = re.sub(r"\s*فایل\s*$", "", str(activity.get("name") or "")).strip().casefold()
matches = [
(item_index, item)
for item_index, item in enumerate(items)
if item_index not in consumed
and re.sub(r"\s*فایل\s*$", "", item.activity).strip().casefold() == activity_name
]
if matches:
for item_index, item in matches:
if item_index not in consumed:
section_records.append(file_record(item, item_index, section, activity))
continue
activity_type = str(activity.get("type") or "activity")
type_names = {
"bigbluebuttonbn": "live class",
"forum": "discussion",
"quiz": "quiz",
"url": "link",
"resource": "resource",
}
local_activity = _local_activity_record(library, course.id, section, activity)
local_metadata, local_directory = local_activity or ({}, Path())
local_files = [
local_directory / str(relative)
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
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 local_path:
downloaded_count += 1
downloaded_bytes += local_bytes
section_records.append(
{
"id": f"activity-{activity.get('id') or hashlib.sha1(str(activity).encode()).hexdigest()[:10]}",
"section": section.get("name") or "Course",
"section_id": section.get("id"),
"section_number": section.get("number"),
"activity_id": activity.get("id"),
"activity_position": activity.get("position"),
"activity_type": activity_type,
"title": activity.get("name") or activity_type,
"description": activity.get("description") or "",
"badge": activity.get("badge") or type_names.get(activity_type, activity_type),
"filename": local_path.name if local_path else "",
"extension": local_path.suffix.removeprefix(".").casefold() if local_path else "",
"kind": local_kind,
"mimetype": mimetypes.guess_type(local_path.name)[0] if local_path else "",
"status": "downloaded" if local_path else "online",
"size": local_bytes if local_path else None,
"local_bytes": local_bytes,
"local_url": _relative_browser_path(local_path, library) if local_path else None,
"artifacts": _discover_artifacts(local_directory, library) if local_activity else {},
"source_url": activity.get("url") or f"{client.site}/course/view.php?id={course.id}",
"lms_completed": activity.get("lms_completed"),
}
)
catalog_sections.append(
{
"id": section.get("id"),
"number": section.get("number"),
"position": section.get("position"),
"name": section.get("name") or "Section",
"summary": section.get("summary") or "",
"activity_count": len(activities),
"items": section_records,
}
)
for item_index, item in enumerate(items):
if item_index in consumed:
continue
chapter_name = item.chapter or item.section
target = next((section for section in catalog_sections if section["name"] == chapter_name), None)
if target is None:
target = {
"id": item.section_id,
"number": item.section_number,
"position": len(catalog_sections) + 1,
"name": chapter_name,
"summary": "",
"activity_count": 0,
"items": [],
}
catalog_sections.append(target)
target["items"].append(file_record(item, item_index))
if not structure:
activity_count = len(items)
for section in catalog_sections:
section["activity_count"] = len(section["items"])
record_count = sum(len(section["items"]) for section in catalog_sections)
file_count = sum(
1
for section in catalog_sections
for record in section["items"]
if record.get("filename")
)
type_counts: dict[str, int] = {}
for section in catalog_sections:
for record in section["items"]:
type_counts[record["kind"]] = type_counts.get(record["kind"], 0) + 1
catalog_courses.append(
{
"id": course.id,
"fullname": course.fullname,
"shortname": course.shortname,
"source_url": f"{client.site}/course/view.php?id={course.id}",
"section_count": len(catalog_sections),
"activity_count": activity_count,
"record_count": record_count,
"file_count": file_count,
"downloaded_count": downloaded_count,
"downloaded_bytes": downloaded_bytes,
"type_counts": type_counts,
"sections": catalog_sections,
}
)
total_files += file_count
total_activities += activity_count
total_records += record_count
total_downloaded += downloaded_count
total_downloaded_bytes += downloaded_bytes
return {
"schema_version": 3,
"generated_at": datetime.now(timezone.utc).isoformat(),
"stats": {
"courses": len(catalog_courses),
"files": total_files,
"activities": total_activities,
"records": total_records,
"downloaded_files": total_downloaded,
"downloaded_bytes": total_downloaded_bytes,
},
"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
+226
View File
@@ -0,0 +1,226 @@
"""Command-line parser and application entry point."""
import argparse
import json
import re
import sys
from dataclasses import asdict
from pathlib import Path
from .auth import (
_authenticate_browser_session,
_browser_session_values,
_credentials,
_load_env_file,
_save_env_values,
)
from .client import MoodleClient
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
from .library import (
_build_library_catalog,
_format_size,
_migrate_legacy_downloads,
_reuse_library_catalog,
_serve_library,
_write_library_site,
)
from .models import MoodleError
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})")
parser.add_argument(
"--login-url",
help=(
"account portal used for browser login; defaults to "
f"{DEFAULT_RAVIN_LOGIN_URL} for Ravin Academy"
),
)
parser.add_argument("--username", help="LMS username; password is prompted securely")
parser.add_argument("--web-only", action="store_true", help="skip the Moodle mobile API and use a normal web session")
parser.add_argument(
"--browser-session",
action="store_true",
help="force saved or automatic browser-session authentication",
)
parser.add_argument(
"--browser-user-agent",
help="User-Agent copied from the logged-in browser; otherwise prompted",
)
parser.add_argument(
"--env-file",
type=Path,
default=DEFAULT_ENV_FILE,
help=f"credentials and browser-session file (default: {DEFAULT_ENV_FILE})",
)
parser.add_argument(
"--refresh-session",
action="store_true",
help="ignore the saved browser session and open the authentication browser",
)
parser.add_argument(
"--manual-session",
action="store_true",
help="prompt for User-Agent and Cookie headers instead of opening a browser",
)
parser.add_argument(
"--browser-profile",
type=Path,
default=Path.cwd() / ".ravin-browser-profile",
help="persistent profile for automatic browser login",
)
parser.add_argument(
"--browser-executable",
type=Path,
help="installed Zen, Firefox, Chrome, Chromium, or Brave executable",
)
parser.add_argument(
"--login-timeout",
type=int,
default=600,
help="seconds to wait for interactive browser login (default: 600)",
)
parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("login", help="open a browser and refresh the saved LMS session")
subparsers.add_parser("courses", help="list enrolled courses")
files_parser = subparsers.add_parser("files", help="list downloadable files in a course")
files_parser.add_argument("course_id", type=int)
download_parser = subparsers.add_parser("download", help="download files from one course")
download_parser.add_argument("course_id", type=int)
download_parser.add_argument("--output", type=Path, default=Path("library"), help="library root (default: library)")
download_parser.add_argument("--overwrite", action="store_true")
download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)")
library_parser = subparsers.add_parser(
"library",
help="generate a private static course library and courses.json",
)
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(
"--reuse-catalog",
action="store_true",
help="refresh local files and pages without contacting the LMS",
)
migrate_parser = subparsers.add_parser("migrate-library", help="move legacy downloads into the library layout")
migrate_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all catalog courses")
migrate_parser.add_argument("--source", type=Path, default=Path("downloads"), help="legacy download root")
migrate_parser.add_argument("--library", type=Path, default=Path("library"), help="library root")
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("--host", default="127.0.0.1", help="local bind address (default: 127.0.0.1)")
serve_parser.add_argument("--port", type=int, default=8765, help="local port (default: 8765)")
serve_parser.add_argument("--open", action="store_true", help="open the library in your default browser")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
try:
if args.command == "serve-library":
_serve_library(args.site_dir, args.host, args.port, args.open)
return 0
if args.command == "migrate-library":
source = args.source.expanduser().resolve()
library = args.library.expanduser().resolve()
result = _migrate_legacy_downloads(source, library, args.course_ids)
catalog = _reuse_library_catalog(library)
catalog_path = _write_library_site(library, catalog)
moved = sum(int(course.get("moved_files") or 0) for course in result.get("courses", []))
print(f"Migrated {moved} files and refreshed {catalog_path}.")
return 0
if args.command == "library" and args.reuse_catalog:
output = args.output.expanduser().resolve()
catalog = _reuse_library_catalog(output)
catalog_path = _write_library_site(output, catalog)
print(f"Prepared {catalog_path}, static pages, 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)
print(f"Authenticated using {mode}; updated {args.env_file}.")
return 0
saved_session = _browser_session_values(args, fresh=args.refresh_session)
if args.browser_session or args.refresh_session or saved_session is not None:
client, mode = _authenticate_browser_session(args, saved_session)
else:
username, password = _credentials(args)
_save_env_values(
args.env_file,
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
},
)
args.env_values.update(
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
}
)
client = MoodleClient(args.site, username, password, web_only=args.web_only)
try:
mode = client.authenticate()
except MoodleError as exc:
if "cloudflare requires a real browser session" not in str(exc).casefold():
raise
print("Cloudflare blocked password login; opening the authentication browser.", file=sys.stderr)
client, mode = _authenticate_browser_session(args)
print(f"Authenticated using {mode}.", file=sys.stderr)
if args.command == "courses":
courses = client.list_courses()
if args.json:
print(json.dumps([asdict(course) for course in courses], ensure_ascii=False, indent=2))
else:
for course in courses:
suffix = f" [{course.shortname}]" if course.shortname else ""
print(f"{course.id:>6} {course.fullname}{suffix}")
return 0
if args.command == "library":
output = args.output.expanduser().resolve()
catalog = _build_library_catalog(client, output, args.course_ids)
catalog_path = _write_library_site(output, catalog)
print(f"Generated {catalog_path} and the static library pages.")
print("View it with: ravin serve-library --open")
return 0
files = client.list_files(args.course_id)
if args.command == "files":
if args.json:
print(json.dumps([asdict(item) for item in files], ensure_ascii=False, indent=2))
else:
for number, item in enumerate(files, 1):
print(f"{number:>3}. {_format_size(item.filesize):>10} {item.section} / {item.activity} / {item.filename}")
return 0
if not files:
print("No downloadable files were found.")
return 0
downloaded: list[str] = []
for number, item in enumerate(files, 1):
print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr)
library = args.output.expanduser().resolve()
path = client.download(
item,
library,
overwrite=args.overwrite,
retries=max(args.retries, 0),
)
downloaded.append(str(path))
if args.json:
print(json.dumps(downloaded, ensure_ascii=False, indent=2))
else:
print(f"Downloaded {len(downloaded)} file(s) to {args.output.resolve()}")
return 0
except (MoodleError, KeyboardInterrupt) as exc:
if isinstance(exc, KeyboardInterrupt):
print("\nCancelled.", file=sys.stderr)
else:
print(f"error: {exc}", file=sys.stderr)
return 1
+577
View File
@@ -0,0 +1,577 @@
"""Authenticated Moodle API/web client and resumable downloader."""
import http.client
import http.cookiejar
import json
import mimetypes
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path
from typing import Any
from .constants import DOWNLOADABLE_MODULES, USER_AGENT
from .models import Course, FileItem, MoodleError
from .parsers import _CourseStructureParser, _FormParser, _LinkParser, _parse_moodle_config
from .paths import (
_activity_root,
_clean_name,
_filename_from_headers,
_is_cloudflare_challenge,
_unique,
_write_item_metadata,
)
class MoodleClient:
def __init__(
self,
site: str,
username: str = "",
password: str = "",
web_only: bool = False,
cookie_header: str = "",
browser_user_agent: str = "",
) -> None:
self.site = site.rstrip("/")
self.username = username
self.password = password
self.web_only = web_only
self.user_agent = browser_user_agent or USER_AGENT
self.cookies = http.cookiejar.CookieJar()
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookies))
if cookie_header:
self._install_cookie_header(cookie_header)
self.has_browser_session = bool(cookie_header)
self.token: str | None = None
self.user_id: int | None = None
self.sesskey: str | None = None
self.mode = ""
self._course_structure_cache: dict[int, list[dict[str, Any]]] = {}
def _install_cookie_header(self, cookie_header: str) -> None:
parsed_site = urllib.parse.urlparse(self.site)
hostname = parsed_site.hostname
if not hostname:
raise MoodleError(f"invalid Moodle site URL: {self.site}")
installed = 0
for pair in cookie_header.split(";"):
if "=" not in pair:
continue
name, value = pair.strip().split("=", 1)
if not name:
continue
cookie = http.cookiejar.Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain=hostname,
domain_specified=True,
domain_initial_dot=False,
path="/",
path_specified=True,
secure=parsed_site.scheme == "https",
expires=None,
discard=True,
comment=None,
comment_url=None,
rest={"HttpOnly": None},
rfc2109=False,
)
self.cookies.set_cookie(cookie)
installed += 1
if not installed:
raise MoodleError("the pasted Cookie header did not contain any cookies")
def _request(
self,
path_or_url: str,
*,
data: dict[str, Any] | bytes | None = None,
headers: dict[str, str] | None = None,
timeout: int = 45,
) -> Any:
url = urllib.parse.urljoin(self.site + "/", path_or_url)
body: bytes | None
if isinstance(data, dict):
body = urllib.parse.urlencode(data, doseq=True).encode()
else:
body = data
request_headers = {"User-Agent": self.user_agent, "Accept-Language": "en,fa;q=0.8"}
request_headers.update(headers or {})
request = urllib.request.Request(url, data=body, headers=request_headers)
try:
return self.opener.open(request, timeout=timeout)
except urllib.error.HTTPError as exc:
detail = exc.read(500).decode("utf-8", "replace").strip()
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:
raw = response.read()
charset = response.headers.get_content_charset() or "utf-8"
return raw.decode(charset, "replace"), response.geturl(), response.headers
def authenticate(self) -> str:
if self.has_browser_session:
self._login_browser_session()
self.mode = "browser-session"
return self.mode
mobile_error = ""
if not self.web_only:
try:
self._login_mobile_api()
self.mode = "mobile-api"
return self.mode
except MoodleError as exc:
mobile_error = str(exc)
try:
self._login_web()
self.mode = "web-session"
return self.mode
except MoodleError as exc:
if mobile_error:
raise MoodleError(
f"Mobile API login was unavailable ({mobile_error}); "
f"web login also failed ({exc})."
) from exc
raise
def _login_mobile_api(self) -> None:
text, _, _ = self._read_text(
"/login/token.php",
data={
"username": self.username,
"password": self.password,
"service": "moodle_mobile_app",
},
)
try:
payload = json.loads(text)
except json.JSONDecodeError as exc:
if _is_cloudflare_challenge(text):
raise MoodleError("Cloudflare requires a real browser session; use --browser-session") from exc
raise MoodleError("the token endpoint did not return JSON") from exc
token = payload.get("token")
if not token:
message = payload.get("error") or payload.get("message") or "token service rejected the login"
raise MoodleError(str(message))
self.token = str(token)
site_info = self.api_call("core_webservice_get_site_info")
self.user_id = int(site_info["userid"])
def _login_web(self) -> None:
login_page, login_url, _ = self._read_text("/login/index.php")
if _is_cloudflare_challenge(login_page):
raise MoodleError("Cloudflare requires a real browser session; use --browser-session")
parser = _FormParser()
parser.feed(login_page)
form = next(
(form for form in parser.forms if "username" in form["inputs"] and "password" in form["inputs"]),
None,
)
if form is None:
raise MoodleError("could not find Moodle's login form")
fields = dict(form["inputs"])
fields.update({"username": self.username, "password": self.password})
action = urllib.parse.urljoin(login_url, form["action"] or "/login/index.php")
result, final_url, _ = self._read_text(action, data=fields)
result_parser = _FormParser()
result_parser.feed(result)
still_has_login = any(
"username" in item["inputs"] and "password" in item["inputs"]
for item in result_parser.forms
)
if still_has_login or "/login/index.php" in urllib.parse.urlparse(final_url).path:
error_match = re.search(
r'class="[^"]*(?:loginerrors|alert-danger)[^"]*"[^>]*>(.*?)</',
result,
flags=re.I | re.S,
)
detail = re.sub(r"<[^>]+>", " ", error_match.group(1)) if error_match else "login rejected"
raise MoodleError(" ".join(html.unescape(detail).split()))
config = _parse_moodle_config(result)
self.sesskey = str(config.get("sesskey") or "") or None
if config.get("userId") is not None:
self.user_id = int(config["userId"])
if not self.sesskey:
dashboard, _, _ = self._read_text("/my/courses.php")
config = _parse_moodle_config(dashboard)
self.sesskey = str(config.get("sesskey") or "") or None
if config.get("userId") is not None:
self.user_id = int(config["userId"])
if not self.sesskey:
raise MoodleError("login succeeded, but Moodle's session key was not found")
def _login_browser_session(self) -> None:
dashboard, final_url, _ = self._read_text("/my/courses.php")
if _is_cloudflare_challenge(dashboard):
raise MoodleError(
"Cloudflare rejected the browser session. Copy a fresh Cookie header and use the exact same User-Agent."
)
parser = _FormParser()
parser.feed(dashboard)
login_form_present = any(
"username" in item["inputs"] and "password" in item["inputs"]
for item in parser.forms
)
if login_form_present or "/login/index.php" in urllib.parse.urlparse(final_url).path:
raise MoodleError("the pasted browser session is expired or is not logged in")
config = _parse_moodle_config(dashboard)
self.sesskey = str(config.get("sesskey") or "") or None
if config.get("userId") is not None:
self.user_id = int(config["userId"])
if not self.sesskey:
raise MoodleError("the page opened, but Moodle's session key was not found")
def api_call(self, function: str, **params: Any) -> Any:
if not self.token:
raise MoodleError("the mobile API is not authenticated")
fields = {
"wstoken": self.token,
"wsfunction": function,
"moodlewsrestformat": "json",
**params,
}
text, _, _ = self._read_text("/webservice/rest/server.php", data=fields)
try:
payload = json.loads(text)
except json.JSONDecodeError as exc:
raise MoodleError(f"{function} returned invalid JSON") from exc
if isinstance(payload, dict) and (payload.get("exception") or payload.get("errorcode")):
raise MoodleError(str(payload.get("message") or payload.get("errorcode")))
return payload
def ajax_call(self, function: str, args: dict[str, Any]) -> Any:
if not self.sesskey:
raise MoodleError("the web session is not authenticated")
body = json.dumps([{"index": 0, "methodname": function, "args": args}]).encode()
text, _, _ = self._read_text(
f"/lib/ajax/service.php?sesskey={urllib.parse.quote(self.sesskey)}&info={urllib.parse.quote(function)}",
data=body,
headers={"Content-Type": "application/json", "Accept": "application/json"},
)
try:
payload = json.loads(text)
except json.JSONDecodeError as exc:
raise MoodleError(f"{function} returned invalid JSON") from exc
if not isinstance(payload, list) or not payload:
raise MoodleError(f"{function} returned an unexpected response")
result = payload[0]
if result.get("error"):
exception = result.get("exception") or {}
raise MoodleError(str(exception.get("message") or exception.get("errorcode") or "AJAX error"))
return result.get("data")
def list_courses(self) -> list[Course]:
if self.token:
if self.user_id is None:
raise MoodleError("Moodle did not return the current user ID")
payload = self.api_call("core_enrol_get_users_courses", userid=self.user_id)
courses = [
Course(int(item["id"]), str(item.get("fullname") or item.get("displayname") or item["id"]), str(item.get("shortname") or ""))
for item in payload
]
else:
data = self.ajax_call(
"core_course_get_enrolled_courses_by_timeline_classification",
{
"classification": "all",
"limit": 0,
"offset": 0,
"sort": "fullname",
"customfieldname": "",
"customfieldvalue": "",
"requiredfields": ["id", "fullname", "shortname", "visible", "enddate"],
},
)
raw_courses = data.get("courses", []) if isinstance(data, dict) else []
courses = [
Course(int(item["id"]), str(item.get("fullname") or item.get("displayname") or item["id"]), str(item.get("shortname") or ""))
for item in raw_courses
]
return sorted(courses, key=lambda course: course.fullname.casefold())
def list_files(self, course_id: int) -> list[FileItem]:
if self.token:
try:
return self._list_files_api(course_id)
except MoodleError as exc:
print(f"warning: course-content API unavailable ({exc}); using web pages", file=sys.stderr)
self._login_web()
self.token = None
self.mode = "web-session"
return self._list_files_web(course_id)
def _list_files_api(self, course_id: int) -> list[FileItem]:
sections = self.api_call("core_course_get_contents", courseid=course_id)
files: list[FileItem] = []
for section_position, section in enumerate(sections, 1):
section_name = str(section.get("name") or f"Section {section.get('section', '')}")
for activity_position, module in enumerate(section.get("modules", []), 1):
activity = str(module.get("name") or module.get("modname") or "activity")
for content in module.get("contents", []) or []:
file_url = content.get("fileurl")
if not file_url or content.get("type", "file") != "file":
continue
files.append(
FileItem(
course_id=course_id,
section=section_name,
activity=activity,
filename=str(content.get("filename") or "file"),
url=str(file_url),
mimetype=str(content.get("mimetype") or ""),
filesize=int(content["filesize"]) if content.get("filesize") is not None else None,
chapter=section_name,
section_id=int(section["id"]) if section.get("id") is not None else None,
section_number=int(section["section"]) if section.get("section") is not None else section_position,
activity_id=int(module["id"]) if module.get("id") is not None else None,
activity_type=str(module.get("modname") or ""),
activity_position=activity_position,
description=re.sub(r"<[^>]+>", " ", str(module.get("description") or "")).strip(),
)
)
return _unique(files)
def _list_files_web(self, course_id: int) -> list[FileItem]:
page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}")
structure_parser = _CourseStructureParser(final_url)
structure_parser.feed(page)
structure = structure_parser.result()
self._course_structure_cache[course_id] = structure
activity_by_url: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {}
for section in structure:
for activity_metadata in section["activities"]:
if activity_metadata["url"]:
key = urllib.parse.urlsplit(activity_metadata["url"])._replace(fragment="").geturl()
activity_by_url[key] = (section, activity_metadata)
parser = _LinkParser(final_url)
parser.feed(page)
module_links: list[tuple[str, str]] = []
direct_files: list[FileItem] = []
for url, label in parser.links:
parsed = urllib.parse.urlparse(url)
module_match = re.search(r"/mod/([^/]+)/view\.php$", parsed.path)
if module_match and module_match.group(1) in DOWNLOADABLE_MODULES:
module_links.append((url, label or module_match.group(1)))
elif "/pluginfile.php/" in parsed.path:
direct_files.append(self._web_file_item(course_id, "Course files", label, url))
for url in parser.media:
if "/pluginfile.php/" in urllib.parse.urlparse(url).path:
direct_files.append(self._web_file_item(course_id, "Course files", "media", url))
files = list(direct_files)
seen_modules: set[str] = set()
for module_url, activity in module_links:
module_key = urllib.parse.urlsplit(module_url)._replace(query=urllib.parse.urlencode(dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(module_url).query))), fragment="").geturl()
if module_key in seen_modules:
continue
seen_modules.add(module_key)
metadata = activity_by_url.get(module_key)
if metadata:
activity = metadata[1]["name"] or activity
separator = "&" if urllib.parse.urlparse(module_url).query else "?"
inspect_url = module_url + separator + "redirect=0"
try:
module_page, module_final_url, headers = self._read_text(inspect_url)
except MoodleError as exc:
print(f"warning: skipped {activity}: {exc}", file=sys.stderr)
continue
content_type = headers.get_content_type() if hasattr(headers, "get_content_type") else ""
if not (content_type.startswith("text/") or content_type in {"application/xhtml+xml", "application/xml"}):
files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata))
continue
module_parser = _LinkParser(module_final_url)
module_parser.feed(module_page)
candidates = list(module_parser.media)
candidates.extend(url for url, _ in module_parser.links)
for candidate in candidates:
candidate_path = urllib.parse.urlparse(candidate).path
if "/pluginfile.php/" in candidate_path or "/webservice/pluginfile.php/" in candidate_path:
files.append(self._web_file_item(course_id, "Course files", activity, candidate, metadata))
return _unique(files)
def _web_file_item(
self,
course_id: int,
section: str,
activity: str,
url: str,
metadata: tuple[dict[str, Any], dict[str, Any]] | None = None,
) -> FileItem:
path_name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name
section_metadata, activity_metadata = metadata or ({}, {})
return FileItem(
course_id=course_id,
section=section,
activity=activity or path_name,
filename=path_name or _clean_name(activity),
url=url,
chapter=str(section_metadata.get("name") or section),
section_id=section_metadata.get("id"),
section_number=section_metadata.get("number"),
activity_id=activity_metadata.get("id"),
activity_type=str(activity_metadata.get("type") or ""),
activity_position=activity_metadata.get("position"),
description=str(activity_metadata.get("description") or ""),
)
def course_structure(self, course_id: int) -> list[dict[str, Any]]:
cached = self._course_structure_cache.get(course_id)
if cached is not None:
return cached
page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}")
parser = _CourseStructureParser(final_url)
parser.feed(page)
structure = parser.result()
self._course_structure_cache[course_id] = structure
return structure
def download(
self,
item: FileItem,
library: Path,
overwrite: bool = False,
retries: int = 5,
retry_delay: float = 1.0,
) -> Path:
activity = _clean_name(item.activity, "activity")
activity_directory = _activity_root(library, item)
directory = activity_directory / "files"
directory.mkdir(parents=True, exist_ok=True)
url = item.url
if self.token:
parts = urllib.parse.urlsplit(url)
query = dict(urllib.parse.parse_qsl(parts.query, keep_blank_values=True))
query.setdefault("token", self.token)
url = parts._replace(query=urllib.parse.urlencode(query)).geturl()
suggested_filename = _clean_name(item.filename, activity)
destination = directory / suggested_filename
if destination.exists() and not overwrite:
_write_item_metadata(item, activity_directory, destination)
return destination
temporary = destination.with_name(destination.name + ".part")
if overwrite:
temporary.unlink(missing_ok=True)
expected_total = item.filesize
started = time.monotonic()
retry_number = 0
while True:
resume_at = temporary.stat().st_size if temporary.exists() else 0
headers: dict[str, str] = {}
if resume_at:
headers["Range"] = f"bytes={resume_at}-"
try:
with self._request(url, headers=headers, timeout=120) as response:
status_code = getattr(response, "status", response.getcode())
response_filename = _filename_from_headers(response.headers, response.geturl(), activity)
if not temporary.exists() and response_filename != suggested_filename:
destination = directory / response_filename
if destination.exists() and not overwrite:
_write_item_metadata(item, activity_directory, destination)
return destination
temporary = destination.with_name(destination.name + ".part")
resume_at = temporary.stat().st_size if temporary.exists() else 0
content_range = response.headers.get("Content-Range", "")
range_match = re.fullmatch(r"bytes\s+(\d+)-(\d+)/(\d+|\*)", content_range.strip(), flags=re.I)
if resume_at and status_code == 206:
if not range_match or int(range_match.group(1)) != resume_at:
raise MoodleError("server returned an unexpected byte range")
if range_match.group(3) != "*":
expected_total = int(range_match.group(3))
file_mode = "ab"
downloaded = resume_at
elif resume_at and status_code == 200:
print(
f"warning: server did not honor resume for {destination.name}; restarting this file",
file=sys.stderr,
)
file_mode = "wb"
downloaded = 0
resume_at = 0
else:
file_mode = "wb"
downloaded = 0
content_length = response.headers.get("Content-Length", "")
if expected_total is None and content_length.isdigit():
expected_total = downloaded + int(content_length)
with temporary.open(file_mode) as output:
while True:
try:
chunk = response.read(1024 * 1024)
except http.client.IncompleteRead as exc:
if exc.partial:
output.write(exc.partial)
downloaded += len(exc.partial)
output.flush()
raise
if not chunk:
break
output.write(chunk)
downloaded += len(chunk)
if sys.stderr.isatty():
if expected_total:
progress = f"{downloaded / expected_total:6.1%}"
else:
progress = f"{downloaded / 1024 / 1024:7.1f} MiB"
print(
f"\r {progress} {destination.name[:60]}",
end="",
file=sys.stderr,
flush=True,
)
if expected_total is not None and downloaded != expected_total:
raise MoodleError(
f"connection closed early at {downloaded} of {expected_total} bytes"
)
temporary.replace(destination)
_write_item_metadata(item, activity_directory, destination)
if sys.stderr.isatty():
elapsed = max(time.monotonic() - started, 0.01)
rate = downloaded / 1024 / 1024 / elapsed
print(
f"\r done {downloaded / 1024 / 1024:7.1f} MiB ({rate:.1f} MiB/s) {destination.name}",
file=sys.stderr,
)
return destination
except (
MoodleError,
http.client.IncompleteRead,
http.client.RemoteDisconnected,
ConnectionError,
TimeoutError,
OSError,
) as exc:
retry_number += 1
if retry_number > retries:
saved = temporary.stat().st_size if temporary.exists() else 0
raise MoodleError(
f"download failed after {retries + 1} attempts; "
f"kept {saved / 1024 / 1024:.1f} MiB in {temporary} ({exc})"
) from exc
saved = temporary.stat().st_size if temporary.exists() else 0
delay = min(retry_delay * (2 ** (retry_number - 1)), 15.0)
print(
f"\n connection interrupted; retry {retry_number}/{retries} "
f"from {saved / 1024 / 1024:.1f} MiB in {delay:g}s",
file=sys.stderr,
)
if delay:
time.sleep(delay)
+20
View File
@@ -0,0 +1,20 @@
"""Project-wide defaults and version information."""
from pathlib import Path
DEFAULT_SITE = "https://training.ravinacademy.com"
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
__version__ = "0.5.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
DEFAULT_ENV_FILE = Path.cwd() / ".env"
ENV_KEYS = {
"username": "RAVIN_USERNAME",
"password": "RAVIN_PASSWORD",
"login_url": "RAVIN_LOGIN_URL",
"user_agent": "RAVIN_USER_AGENT",
"cookie": "RAVIN_COOKIE",
}
LIBRARY_ASSETS = ("index.html", "course.html", "styles.css", "app.js")
CONTENT_SCHEMA_VERSION = 1
+19
View File
@@ -0,0 +1,19 @@
"""Compatibility facade for the static library subsystems."""
from .catalog import (
_build_library_catalog,
_format_size,
_reuse_library_catalog,
_write_library_site,
)
from .migration import _migrate_legacy_downloads
from .server import _serve_library
__all__ = [
"_build_library_catalog",
"_format_size",
"_migrate_legacy_downloads",
"_reuse_library_catalog",
"_serve_library",
"_write_library_site",
]
+218
View File
@@ -0,0 +1,218 @@
"""Migrate legacy course files into ordered activity bundles."""
import json
import mimetypes
import re
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
from .constants import CONTENT_SCHEMA_VERSION
from .models import FileItem, MoodleError
from .paths import _activity_root, _course_content_root, _read_json_object, _write_item_metadata
def _move_migration_file(source: Path, destination: Path, moved: list[dict[str, str]], source_root: Path, library: Path) -> None:
if not source.is_file():
if destination.is_file():
return
raise MoodleError(f"migration source is missing: {source}")
if destination.exists():
raise MoodleError(f"migration target already exists: {destination}")
destination.parent.mkdir(parents=True, exist_ok=True)
source.replace(destination)
moved.append(
{
"from": source.relative_to(source_root).as_posix(),
"to": destination.relative_to(library).as_posix(),
}
)
def _normalize_transcript_metadata(path: Path, source_filename: str) -> None:
metadata = _read_json_object(path)
if not metadata:
return
metadata["schema_version"] = CONTENT_SCHEMA_VERSION
metadata["source"] = f"../files/{source_filename}"
metadata["transcript"] = "transcript.fa.txt"
if "transcribed_at" in metadata and "generated_at" not in metadata:
metadata["generated_at"] = metadata.pop("transcribed_at")
path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def _normalize_summary_source(path: Path) -> None:
try:
content = path.read_text(encoding="utf-8")
except OSError:
return
updated = re.sub(r"(?m)^\*\*منبع:\*\*.*$", "**منبع:** transcript.fa.txt", content)
if updated != content:
path.write_text(updated, encoding="utf-8")
def _finalize_item_metadata(activity_directory: Path) -> None:
path = activity_directory / "item.json"
metadata = _read_json_object(path)
artifact_names = {
"transcript": "transcript.fa.txt",
"transcript_metadata": "transcript.meta.json",
"summary": "summary.fa.md",
"questions": "questions.fa.md",
}
artifacts = {
kind: f"artifacts/{filename}"
for kind, filename in artifact_names.items()
if (activity_directory / "artifacts" / filename).is_file()
}
metadata["artifacts"] = artifacts
path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
def _record_file_item(course_id: int, section: dict[str, Any], record: dict[str, Any], filename: str) -> FileItem:
return FileItem(
course_id=course_id,
section=str(section.get("name") or "Course"),
activity=str(record.get("title") or filename),
filename=filename,
url=str(record.get("source_url") or ""),
mimetype=str(record.get("mimetype") or mimetypes.guess_type(filename)[0] or ""),
filesize=record.get("size"),
chapter=str(section.get("name") or "Course"),
section_id=record.get("section_id", section.get("id")),
section_number=record.get("section_number", section.get("number")),
activity_id=record.get("activity_id"),
activity_type=str(record.get("activity_type") or "resource"),
activity_position=record.get("activity_position"),
description=str(record.get("description") or ""),
)
def _migrate_legacy_downloads(source_root: Path, library: Path, selected_course_ids: Iterable[int] = ()) -> dict[str, Any]:
"""Move the old flat download layout into ordered activity bundles."""
catalog_path = library / "courses.json"
if not catalog_path.is_file():
raise MoodleError(f"{catalog_path} is required to map legacy files to LMS activities")
catalog = _read_json_object(catalog_path)
selected = set(selected_course_ids)
courses = [
course
for course in catalog.get("courses", [])
if not selected or int(course.get("id") or 0) in selected
]
if selected - {int(course.get("id") or 0) for course in courses}:
missing = ", ".join(str(value) for value in sorted(selected - {int(course.get("id") or 0) for course in courses}))
raise MoodleError(f"course ID(s) are missing from {catalog_path}: {missing}")
migration: dict[str, Any] = {
"schema_version": CONTENT_SCHEMA_VERSION,
"migrated_at": datetime.now(timezone.utc).isoformat(),
"courses": [],
}
for course in courses:
course_id = int(course.get("id") or 0)
legacy_course = source_root / str(course_id)
if not legacy_course.is_dir():
continue
moved: list[dict[str, str]] = []
records: list[tuple[dict[str, Any], dict[str, Any]]] = [
(section, record)
for section in course.get("sections", [])
for record in section.get("items", [])
]
records_by_filename = {
str(record.get("filename")): (section, record)
for section, record in records
if record.get("filename")
}
files_directory = legacy_course / "Course files"
for filename, (section, record) in records_by_filename.items():
source_file = files_directory / filename
if not source_file.is_file():
continue
item = _record_file_item(course_id, section, record, filename)
activity_directory = _activity_root(library, item)
destination = activity_directory / "files" / filename
_move_migration_file(source_file, destination, moved, source_root, library)
_write_item_metadata(item, activity_directory, destination)
companions = (
(files_directory / f"{filename}.txt", activity_directory / "artifacts" / "transcript.fa.txt"),
(files_directory / f"{filename}.txt.json", activity_directory / "artifacts" / "transcript.meta.json"),
(files_directory / f"{filename}.md", activity_directory / "artifacts" / "summary.fa.md"),
)
for companion_source, companion_destination in companions:
if companion_source.is_file():
_move_migration_file(companion_source, companion_destination, moved, source_root, library)
metadata_path = activity_directory / "artifacts" / "transcript.meta.json"
if metadata_path.is_file():
_normalize_transcript_metadata(metadata_path, filename)
summary_path = activity_directory / "artifacts" / "summary.fa.md"
if summary_path.is_file():
_normalize_summary_source(summary_path)
_finalize_item_metadata(activity_directory)
quizzes = sorted(
((section, record) for section, record in records if record.get("activity_type") == "quiz"),
key=lambda value: (
int(value[1].get("section_number", value[0].get("number")) or 0),
int(value[1].get("activity_position") or 0),
),
)
exams_directory = legacy_course / "Course exams"
exam_pdfs = sorted(exams_directory.glob("*.pdf")) if exams_directory.is_dir() else []
if len(exam_pdfs) > len(quizzes):
raise MoodleError(f"course {course_id} has more local exams than LMS quiz activities")
for exam_index, exam_pdf in enumerate(exam_pdfs):
section, record = quizzes[exam_index]
item = _record_file_item(course_id, section, record, exam_pdf.name)
activity_directory = _activity_root(library, item)
destination = activity_directory / "files" / exam_pdf.name
_move_migration_file(exam_pdf, destination, moved, source_root, library)
_write_item_metadata(item, activity_directory, destination)
questions = exam_pdf.with_suffix(".md")
if questions.is_file():
_move_migration_file(
questions,
activity_directory / "artifacts" / "questions.fa.md",
moved,
source_root,
library,
)
_finalize_item_metadata(activity_directory)
course_root = library / "courses" / str(course_id)
course_root.mkdir(parents=True, exist_ok=True)
course_migration = {
"course_id": course_id,
"source_layout": "downloads/<course-id>/{Course files,Course exams}",
"target_layout": "library/courses/<course-id>/content/SECTION--POSITION--ACTIVITY",
"moved": moved,
}
(course_root / "migration.json").write_text(
json.dumps(course_migration, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
migration["courses"].append({"id": course_id, "moved_files": len(moved)})
remaining = [
path
for path in legacy_course.rglob("*")
if path.is_file() and path.name not in {".DS_Store", "files-map.txt"}
]
if remaining:
names = ", ".join(str(path.relative_to(legacy_course)) for path in remaining[:5])
raise MoodleError(f"migration left unclassified files in course {course_id}: {names}")
for disposable in legacy_course.rglob(".DS_Store"):
disposable.unlink(missing_ok=True)
(legacy_course / "files-map.txt").unlink(missing_ok=True)
for directory in sorted((path for path in legacy_course.rglob("*") if path.is_dir()), reverse=True):
try:
directory.rmdir()
except OSError:
pass
try:
legacy_course.rmdir()
except OSError:
pass
return migration
+32
View File
@@ -0,0 +1,32 @@
"""Core value objects and expected errors."""
from dataclasses import dataclass
class MoodleError(RuntimeError):
"""A friendly, expected Moodle/API error."""
@dataclass(frozen=True)
class Course:
id: int
fullname: str
shortname: str = ""
@dataclass(frozen=True)
class FileItem:
course_id: int
section: str
activity: str
filename: str
url: str
mimetype: str = ""
filesize: int | None = None
chapter: str = ""
section_id: int | None = None
section_number: int | None = None
activity_id: int | None = None
activity_type: str = ""
activity_position: int | None = None
description: str = ""
+232
View File
@@ -0,0 +1,232 @@
"""Small HTML and Moodle-page parsers."""
import html
import json
import re
import urllib.parse
from html.parser import HTMLParser
from typing import Any
class _FormParser(HTMLParser):
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.forms: list[dict[str, Any]] = []
self._form: dict[str, Any] | None = None
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
values = dict(attrs)
if tag == "form":
self._form = {
"action": values.get("action", ""),
"method": values.get("method", "get").lower(),
"inputs": {},
}
elif tag == "input" and self._form is not None:
name = values.get("name")
if name:
self._form["inputs"][name] = values.get("value", "")
def handle_endtag(self, tag: str) -> None:
if tag == "form" and self._form is not None:
self.forms.append(self._form)
self._form = None
class _LinkParser(HTMLParser):
"""Collect links and embedded media without keeping the whole DOM."""
MEDIA_ATTRIBUTES = {
"source": "src",
"video": "src",
"audio": "src",
"track": "src",
"embed": "src",
"iframe": "src",
"object": "data",
}
def __init__(self, base_url: str) -> None:
super().__init__(convert_charrefs=True)
self.base_url = base_url
self.links: list[tuple[str, str]] = []
self.media: list[str] = []
self.title = ""
self._anchor_href: str | None = None
self._anchor_text: list[str] = []
self._in_title = False
self._title_text: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
values = dict(attrs)
if tag == "a" and values.get("href"):
self._anchor_href = urllib.parse.urljoin(self.base_url, values["href"] or "")
self._anchor_text = []
if tag == "title":
self._in_title = True
media_attr = self.MEDIA_ATTRIBUTES.get(tag)
if media_attr and values.get(media_attr):
self.media.append(urllib.parse.urljoin(self.base_url, values[media_attr] or ""))
def handle_data(self, data: str) -> None:
if self._anchor_href is not None:
self._anchor_text.append(data)
if self._in_title:
self._title_text.append(data)
def handle_endtag(self, tag: str) -> None:
if tag == "a" and self._anchor_href is not None:
label = " ".join("".join(self._anchor_text).split())
self.links.append((self._anchor_href, label))
self._anchor_href = None
self._anchor_text = []
if tag == "title":
self._in_title = False
self.title = " ".join("".join(self._title_text).split())
class _CourseStructureParser(HTMLParser):
"""Collect Moodle sections and activities from a course page."""
VOID_TAGS = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"}
def __init__(self, base_url: str) -> None:
super().__init__(convert_charrefs=True)
self.base_url = base_url
self.sections: list[dict[str, Any]] = []
self._section: dict[str, Any] | None = None
self._activity: dict[str, Any] | None = None
self._markers: list[str | None] = []
self._captures: list[tuple[int, dict[str, Any], str]] = []
@staticmethod
def _integer(value: str | None) -> int | None:
try:
return int(value or "")
except ValueError:
return None
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
values = dict(attrs)
classes = set((values.get("class") or "").split())
marker: str | None = None
if (
tag == "li"
and values.get("data-for") == "section"
and (values.get("id") or "").startswith("section-")
):
self._section = {
"id": self._integer(values.get("data-id")),
"number": self._integer(values.get("data-sectionid") or values.get("data-number")),
"position": len(self.sections) + 1,
"name": " ".join((values.get("data-sectionname") or "Section").split()),
"summary": "",
"activities": [],
}
self.sections.append(self._section)
marker = "section"
elif tag == "li" and self._section is not None and values.get("data-for") == "cmitem":
module_type = next(
(value.removeprefix("modtype_") for value in classes if value.startswith("modtype_")),
"activity",
)
self._activity = {
"id": self._integer(values.get("data-id")),
"position": len(self._section["activities"]) + 1,
"name": "",
"type": module_type,
"url": "",
"description": "",
"badge": "",
"lms_completed": None,
}
self._section["activities"].append(self._activity)
marker = "activity"
if tag not in self.VOID_TAGS:
self._markers.append(marker)
depth = len(self._markers)
if self._activity is not None:
activity_name = values.get("data-activityname")
if activity_name and not self._activity["name"]:
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:
self._captures.append((depth, self._activity, "description"))
if "activitybadge" in classes:
self._captures.append((depth, self._activity, "badge"))
class_value = values.get("class") or ""
if "btn-subtle-success" in class_value:
self._activity["lms_completed"] = True
if self._section is not None and "summary" in classes:
self._captures.append((depth, self._section, "summary"))
def handle_endtag(self, _tag: str) -> None:
if _tag in self.VOID_TAGS:
return
depth = len(self._markers)
self._captures = [capture for capture in self._captures if capture[0] != depth]
if not self._markers:
return
marker = self._markers.pop()
if marker == "activity":
self._activity = None
elif marker == "section":
self._section = None
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
def handle_data(self, data: str) -> None:
if not data.strip():
return
for _, target, field in self._captures:
target[field] = f"{target.get(field, '')} {data}".strip()
def result(self) -> list[dict[str, Any]]:
for section in self.sections:
section["summary"] = " ".join(section["summary"].split())
for activity in section["activities"]:
activity["name"] = " ".join((activity["name"] or activity["type"]).split())
activity["description"] = " ".join(activity["description"].split())
activity["badge"] = " ".join(activity["badge"].split())
return self.sections
def _parse_moodle_config(page: str) -> dict[str, Any]:
match = re.search(r"\bM\.cfg\s*=\s*", page)
if not match:
return {}
start = page.find("{", match.end())
if start < 0:
return {}
depth = 0
in_string = False
escaped = False
end = -1
for index in range(start, len(page)):
character = page[index]
if in_string:
if escaped:
escaped = False
elif character == "\\":
escaped = True
elif character == '"':
in_string = False
continue
if character == '"':
in_string = True
elif character == "{":
depth += 1
elif character == "}":
depth -= 1
if depth == 0:
end = index + 1
break
if end < 0:
return {}
try:
return json.loads(page[start:end])
except json.JSONDecodeError:
return {}
+161
View File
@@ -0,0 +1,161 @@
"""Portable library paths, filenames, and artifact metadata."""
import hashlib
import html
import json
import re
import urllib.parse
from pathlib import Path
from typing import Any, Iterable
from .constants import CONTENT_SCHEMA_VERSION
from .models import FileItem, MoodleError
def _clean_name(value: str, fallback: str = "item") -> str:
value = html.unescape(value).strip()
value = re.sub(r"[\\/:*?\"<>|\x00-\x1f]", "_", value)
value = re.sub(r"\s+", " ", value).strip(" .")
return value[:180] or fallback
def _activity_directory_name(
section_number: int | None,
activity_position: int | None,
activity_id: int | None,
*,
fallback: str = "",
) -> str:
"""Return the sortable, title-independent directory for an LMS activity."""
section = max(int(section_number or 0), 0)
position = max(int(activity_position or 0), 0)
if activity_id is None:
digest = hashlib.sha1(fallback.encode("utf-8")).hexdigest()[:8]
resolved_id = int(digest, 16)
else:
resolved_id = max(int(activity_id), 0)
return f"{section:03d}--{position:03d}--{resolved_id}"
def _course_content_root(library: Path, course_id: int) -> Path:
return library / "courses" / _clean_name(str(course_id), "course") / "content"
def _activity_root(library: Path, item: FileItem) -> Path:
key = _activity_directory_name(
item.section_number,
item.activity_position,
item.activity_id,
fallback=f"{item.course_id}\0{item.url}\0{item.activity}\0{item.filename}",
)
return _course_content_root(library, item.course_id) / key
def _relative_browser_path(path: Path, library: Path) -> str:
try:
relative = path.resolve().relative_to(library.resolve())
except ValueError as exc:
raise MoodleError(f"library file is outside the configured library root: {path}") from exc
return "/".join(urllib.parse.quote(part) for part in relative.parts)
def _read_json_object(path: Path) -> dict[str, Any]:
try:
value = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError):
return {}
return value if isinstance(value, dict) else {}
def _discover_artifacts(activity_directory: Path, library: Path) -> dict[str, dict[str, Any]]:
artifacts_directory = activity_directory / "artifacts"
definitions = {
"transcript": ("transcript.fa.txt", "text", "fa"),
"transcript_metadata": ("transcript.meta.json", "json", None),
"summary": ("summary.fa.md", "markdown", "fa"),
"questions": ("questions.fa.md", "markdown", "fa"),
}
artifacts: dict[str, dict[str, Any]] = {}
for kind, (filename, artifact_format, language) in definitions.items():
path = artifacts_directory / filename
if not path.is_file():
continue
record: dict[str, Any] = {
"path": path.relative_to(activity_directory).as_posix(),
"url": _relative_browser_path(path, library),
"format": artifact_format,
"size": path.stat().st_size,
}
if language:
record["language"] = language
artifacts[kind] = record
return artifacts
def _write_item_metadata(item: FileItem, activity_directory: Path, file_path: Path) -> Path:
metadata_path = activity_directory / "item.json"
metadata = _read_json_object(metadata_path)
files = [str(value) for value in metadata.get("files", []) if value]
relative_file = file_path.relative_to(activity_directory).as_posix()
if relative_file not in files:
files.append(relative_file)
metadata.update(
{
"schema_version": CONTENT_SCHEMA_VERSION,
"course_id": item.course_id,
"activity_id": item.activity_id,
"type": item.activity_type or "resource",
"title": re.sub(r"\s*فایل\s*$", "", item.activity).strip() or item.filename,
"position": item.activity_position,
"section": {
"id": item.section_id,
"number": item.section_number,
"title": item.chapter or item.section,
},
"description": item.description,
"files": files,
}
)
metadata_path.write_text(json.dumps(metadata, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return metadata_path
def _filename_from_headers(headers: Any, url: str, fallback: str) -> str:
disposition = headers.get("Content-Disposition", "")
star = re.search(r"filename\*=UTF-8''([^;]+)", disposition, flags=re.I)
normal = re.search(r'filename="?([^";]+)', disposition, flags=re.I)
if star:
name = urllib.parse.unquote(star.group(1))
elif normal:
name = normal.group(1).strip()
else:
name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name
if not name:
content_type = headers.get_content_type() if hasattr(headers, "get_content_type") else ""
extension = mimetypes.guess_extension(content_type) or ""
name = fallback + extension
return _clean_name(name, fallback)
def _unique(items: Iterable[FileItem]) -> list[FileItem]:
result: list[FileItem] = []
seen: set[str] = set()
for item in items:
key = urllib.parse.urlsplit(item.url)._replace(query="", fragment="").geturl()
if key not in seen:
seen.add(key)
result.append(item)
return result
def _is_cloudflare_challenge(page: str) -> bool:
sample = page[:20000].casefold()
return any(
marker in sample
for marker in (
"/cdn-cgi/",
"cf-browser-verification",
"challenge-platform",
"enable javascript and cookies to continue",
)
)
+109
View File
@@ -0,0 +1,109 @@
"""Range-aware local HTTP server for the static learning library."""
import functools
import http.server
import os
import re
import shutil
import urllib.parse
from pathlib import Path
from typing import Any
from .models import MoodleError
class _RangeRequestHandler(http.server.SimpleHTTPRequestHandler):
"""Static-file handler with byte ranges for efficient local media playback."""
_byte_range: tuple[int, int] | None = None
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()
try:
source = open(path, "rb")
except OSError:
self.send_error(404, "File not found")
return None
try:
size = os.fstat(source.fileno()).st_size
range_header = self.headers.get("Range", "")
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
if match and (match.group(1) or match.group(2)):
if match.group(1):
start = int(match.group(1))
end = int(match.group(2)) if match.group(2) else size - 1
else:
suffix_length = int(match.group(2))
start = max(size - suffix_length, 0)
end = size - 1
if start >= size or start > end:
self.send_response(416)
self.send_header("Content-Range", f"bytes */{size}")
self.end_headers()
source.close()
return None
end = min(end, size - 1)
self._byte_range = (start, end)
self.send_response(206)
self.send_header("Content-Type", self.guess_type(path))
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
self.send_header("Content-Length", str(end - start + 1))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Last-Modified", self.date_time_string(os.fstat(source.fileno()).st_mtime))
self.end_headers()
return source
self.send_response(200)
self.send_header("Content-Type", self.guess_type(path))
self.send_header("Content-Length", str(size))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Last-Modified", self.date_time_string(os.fstat(source.fileno()).st_mtime))
self.end_headers()
return source
except Exception:
source.close()
raise
def copyfile(self, source: Any, outputfile: Any) -> None:
if self._byte_range is None:
shutil.copyfileobj(source, outputfile)
return
start, end = self._byte_range
source.seek(start)
remaining = end - start + 1
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk:
break
outputfile.write(chunk)
remaining -= len(chunk)
def _serve_library(site_dir: Path, host: str, port: int, open_browser: bool) -> None:
site_dir = site_dir.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 library` first")
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
url = f"http://{display_host}:{server.server_port}/"
print(f"Learning Library: {url}")
print("Press Ctrl+C to stop.")
if open_browser:
import webbrowser
webbrowser.open(url)
try:
server.serve_forever()
finally:
server.server_close()
+137 -39
View File
@@ -10,26 +10,34 @@ from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from ravin_downloader import (
Course,
FileItem,
MoodleClient,
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from ravin import Course, FileItem, MoodleClient
from ravin.auth import (
_browser_login_url,
_capture_browser_session,
_load_env_file,
_save_env_values,
)
from ravin.cli import build_parser
from ravin.library import (
_build_library_catalog,
_migrate_legacy_downloads,
_reuse_library_catalog,
_write_library_site,
)
from ravin.parsers import (
_CourseStructureParser,
_FormParser,
_LinkParser,
_parse_moodle_config,
)
from ravin.paths import (
_activity_directory_name,
_clean_name,
_browser_login_url,
_build_library_catalog,
_capture_browser_session,
_filename_from_headers,
_is_cloudflare_challenge,
_load_env_file,
_parse_moodle_config,
_reuse_library_catalog,
_save_env_values,
_write_library_site,
_unique,
build_parser,
)
@@ -249,6 +257,7 @@ class ParserTests(unittest.TestCase):
def test_sanitizes_names_and_deduplicates_files(self):
self.assertEqual(_clean_name('Week 1: Intro/Setup?'), "Week 1_ Intro_Setup_")
self.assertEqual(_activity_directory_name(17, 2, 5201), "017--002--5201")
item = FileItem(44, "Chapter 1", "Intro", "1.mp4", "https://x/pluginfile.php/1/1.mp4?token=a")
duplicate = FileItem(44, "Other", "Other", "1.mp4", "https://x/pluginfile.php/1/1.mp4?token=b")
self.assertEqual(_unique([item, duplicate]), [item])
@@ -280,7 +289,7 @@ class ParserTests(unittest.TestCase):
)
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
def test_builds_static_library_catalog_from_downloads(self):
def test_builds_static_library_catalog_from_library_content(self):
class FakeClient:
site = "https://training.example"
@@ -298,6 +307,11 @@ class ParserTests(unittest.TestCase):
"https://training.example/pluginfile.php/10/1.mp4?token=secret",
"video/mp4",
10,
section_id=940,
section_number=2,
activity_id=4940,
activity_type="resource",
activity_position=1,
),
FileItem(
44,
@@ -307,49 +321,50 @@ class ParserTests(unittest.TestCase):
"https://training.example/pluginfile.php/11/notes.pdf",
"application/pdf",
20,
section_id=941,
section_number=3,
activity_id=4941,
activity_type="resource",
activity_position=1,
),
]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
downloads = root / "downloads"
output = root / "library"
video = downloads / "44" / "Course files" / "1.mp4"
video = output / "courses" / "44" / "content" / "002--001--4940" / "files" / "1.mp4"
video.parent.mkdir(parents=True)
video.write_bytes(b"video")
catalog = _build_library_catalog(FakeClient(), downloads, output)
catalog = _build_library_catalog(FakeClient(), output)
self.assertEqual(catalog["stats"]["courses"], 1)
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
items = catalog["courses"][0]["sections"][0]["items"]
self.assertEqual(items[0]["title"], "Introduction")
self.assertEqual(items[0]["kind"], "video")
self.assertEqual(items[0]["status"], "downloaded")
self.assertEqual(items[0]["local_url"], "media/44/Course%20files/1.mp4")
self.assertEqual(items[0]["local_url"], "courses/44/content/002--001--4940/files/1.mp4")
self.assertEqual(items[1]["status"], "missing")
catalog_path = _write_library_site(output, catalog, downloads)
catalog_path = _write_library_site(output, catalog)
written = json.loads(catalog_path.read_text(encoding="utf-8"))
self.assertEqual(written["schema_version"], 2)
self.assertEqual(written["schema_version"], 3)
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())
self.assertTrue((output / "courses" / "44" / "course.json").is_file())
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):
def test_reuses_catalog_and_refreshes_library_links(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
output = root / "library"
downloads = root / "downloads"
media = downloads / "44" / "Course files" / "1.mp4"
media = output / "courses" / "44" / "content" / "002--001--4940" / "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",
(media.parent.parent / "item.json").write_text(
json.dumps({"files": ["files/1.mp4"]}),
encoding="utf-8",
)
output.mkdir()
(output / "courses.json").write_text(
json.dumps(
{
@@ -359,13 +374,15 @@ class ParserTests(unittest.TestCase):
"sections": [
{
"items": [
{"local_url": "../downloads/44/Course%20files/1.mp4"},
{
"local_url": None,
"filename": "",
"filename": "1.mp4",
"activity_type": "resource",
"title": "Introduction to Networks",
"status": "online",
"section_number": 2,
"activity_position": 1,
"activity_id": 4940,
},
]
}
@@ -376,13 +393,10 @@ class ParserTests(unittest.TestCase):
),
encoding="utf-8",
)
catalog = _reuse_library_catalog(output, downloads)
catalog = _reuse_library_catalog(output)
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.assertEqual(item["local_url"], "courses/44/content/002--001--4940/files/1.mp4")
self.assertEqual(item["status"], "downloaded")
self.assertIn("prepared_at", catalog)
def test_interrupted_download_retries_with_range(self):
@@ -394,7 +408,10 @@ class ParserTests(unittest.TestCase):
)
second = _FakeResponse([b"!!"], status=206, content_range="bytes 8-9/10")
client = _FakeDownloadClient([first, second])
item = FileItem(44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin")
item = FileItem(
44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin",
section_number=2, activity_id=4940, activity_position=1,
)
with tempfile.TemporaryDirectory() as directory:
destination = client.download(item, Path(directory), retries=1, retry_delay=0)
self.assertEqual(destination.read_bytes(), b"abcdexyz!!")
@@ -403,15 +420,96 @@ class ParserTests(unittest.TestCase):
def test_existing_partial_download_is_resumed(self):
response = _FakeResponse([b"67890"], status=206, content_range="bytes 5-9/10")
client = _FakeDownloadClient([response])
item = FileItem(44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin")
item = FileItem(
44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin",
section_number=2, activity_id=4940, activity_position=1,
)
with tempfile.TemporaryDirectory() as directory:
partial = Path(directory) / "44" / "Course files" / "file.bin.part"
partial = Path(directory) / "courses" / "44" / "content" / "002--001--4940" / "files" / "file.bin.part"
partial.parent.mkdir(parents=True)
partial.write_bytes(b"12345")
destination = client.download(item, Path(directory), retries=0, retry_delay=0)
self.assertEqual(destination.read_bytes(), b"1234567890")
self.assertEqual(client.request_headers, [{"Range": "bytes=5-"}])
def test_migrates_legacy_video_artifacts_and_exam_in_course_order(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / "downloads"
library = root / "library"
course_files = source / "44" / "Course files"
exams = source / "44" / "Course exams"
course_files.mkdir(parents=True)
exams.mkdir(parents=True)
(course_files / "15.mp4").write_bytes(b"video")
(course_files / "15.mp4.txt").write_text("transcript", encoding="utf-8")
(course_files / "15.mp4.txt.json").write_text(
json.dumps({"source": "/private/15.mp4", "transcript": "/private/15.mp4.txt"}),
encoding="utf-8",
)
(course_files / "15.mp4.md").write_text("**منبع:** private/path\n\nSummary", encoding="utf-8")
(exams / "041264.pdf").write_bytes(b"exam")
(exams / "041264.md").write_text("# Questions", encoding="utf-8")
library.mkdir()
(library / "courses.json").write_text(
json.dumps(
{
"courses": [
{
"id": 44,
"sections": [
{
"id": 847,
"number": 16,
"name": "Chapter 15",
"items": [
{
"activity_id": 4954,
"activity_position": 1,
"activity_type": "resource",
"section_id": 847,
"section_number": 16,
"title": "Lesson 15",
"filename": "15.mp4",
"mimetype": "video/mp4",
}
],
},
{
"id": 924,
"number": 17,
"name": "تمرین اول",
"items": [
{
"activity_id": 5201,
"activity_position": 2,
"activity_type": "quiz",
"section_id": 924,
"section_number": 17,
"title": "تمرین اول",
"filename": "",
}
],
},
],
}
]
}
),
encoding="utf-8",
)
result = _migrate_legacy_downloads(source, library, [44])
self.assertEqual(result["courses"][0]["moved_files"], 6)
lesson = library / "courses" / "44" / "content" / "016--001--4954"
exam = library / "courses" / "44" / "content" / "017--002--5201"
self.assertEqual((lesson / "files" / "15.mp4").read_bytes(), b"video")
metadata = json.loads((lesson / "artifacts" / "transcript.meta.json").read_text(encoding="utf-8"))
self.assertEqual(metadata["source"], "../files/15.mp4")
self.assertEqual(metadata["transcript"], "transcript.fa.txt")
self.assertTrue((exam / "files" / "041264.pdf").is_file())
self.assertTrue((exam / "artifacts" / "questions.fa.md").is_file())
self.assertFalse((source / "44").exists())
if __name__ == "__main__":
unittest.main()