feat: unify course scanning and add manifest-based public library
This commit is contained in:
20 files changed
+809
-796
No files matched your search
@@ -14,6 +14,8 @@ develop-eggs/
|
|||||||
dist/
|
dist/
|
||||||
downloads/
|
downloads/
|
||||||
library/
|
library/
|
||||||
|
public/courses/
|
||||||
|
public/nginx.local.conf
|
||||||
eggs/
|
eggs/
|
||||||
.eggs/
|
.eggs/
|
||||||
lib/
|
lib/
|
||||||
|
|||||||
@@ -2,6 +2,16 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented here.
|
All notable changes to this project will be documented here.
|
||||||
|
|
||||||
|
## 0.6.0 - 2026-08-04
|
||||||
|
|
||||||
|
- Replace the separate course, file, and library builders with one `ravin scan` command.
|
||||||
|
- Add per-course manifests and a small global catalog under the Git-ignored `public/courses/` directory.
|
||||||
|
- Reconcile download, transcript, summary, and assessment states, including stale artifact detection.
|
||||||
|
- Update manifests after every completed download and add an authentication-free offline scan.
|
||||||
|
- Move the shared static interface into the tracked `public/` web root while keeping all personal course data ignored.
|
||||||
|
- Load course details from their own manifests and show learning-artifact states in the library.
|
||||||
|
- Remove redundant per-activity `item.json` files and migrate the previous generated library layout automatically.
|
||||||
|
|
||||||
## 0.5.0 - 2026-08-04
|
## 0.5.0 - 2026-08-04
|
||||||
|
|
||||||
- Replace the `ravin-downloader` console command with the shorter `ravin` command.
|
- Replace the `ravin-downloader` console command with the shorter `ravin` command.
|
||||||
|
|||||||
+1
-1
@@ -4,5 +4,5 @@ include CONTRIBUTING.md
|
|||||||
include SECURITY.md
|
include SECURITY.md
|
||||||
include CHANGELOG.md
|
include CHANGELOG.md
|
||||||
include .env.example
|
include .env.example
|
||||||
recursive-include src/ravin/assets *.html *.css *.js
|
recursive-include public *.html *.css *.js
|
||||||
recursive-include tests *.py
|
recursive-include tests *.py
|
||||||
@@ -1,73 +1,57 @@
|
|||||||
# Ravin Moodle Downloader
|
# Ravin Moodle Downloader
|
||||||
|
|
||||||
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`.
|
A small command-line client for scanning authorized Moodle courses, downloading their files, and browsing them in a private static learning library. It defaults to Ravin Academy and can target another Moodle base URL with `--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.
|
The client tries Moodle's mobile API first, falls back to its authenticated web interface, and can establish a real browser session for sites protected by Cloudflare.
|
||||||
|
|
||||||
> [!IMPORTANT]
|
> [!IMPORTANT]
|
||||||
> Use this tool only for courses and files your account is authorized to access. Respect the LMS terms, instructor permissions, and applicable copyright rules. This project does not bypass enrollment, DRM, or access controls.
|
> Use this tool only for courses and files your account may access. Respect LMS terms, instructor permissions, and copyright. The project does not bypass enrollment, DRM, or access controls.
|
||||||
|
|
||||||
## Requirements
|
## Install
|
||||||
|
|
||||||
|
Requirements:
|
||||||
|
|
||||||
- Python 3.10 or newer
|
- Python 3.10 or newer
|
||||||
- An active enrollment on the target Moodle site
|
- An active enrollment on the target Moodle site
|
||||||
|
- Zen, Firefox, Chrome, Chromium, or Brave for automatic browser login
|
||||||
|
|
||||||
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.
|
From the repository root:
|
||||||
|
|
||||||
## Installation
|
|
||||||
|
|
||||||
After cloning or downloading the repository, install the command from its root directory:
|
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 -m pip install .
|
python3 -m pip install .
|
||||||
```
|
```
|
||||||
|
|
||||||
You can then use `ravin` from any shell. The equivalent module entry point is `python3 -m ravin`.
|
This installs the `ravin` command and its browser automation dependency. The equivalent module entry point is `python3 -m ravin`.
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ravin login
|
ravin login
|
||||||
ravin courses
|
ravin scan
|
||||||
ravin files COURSE_ID
|
|
||||||
ravin download COURSE_ID
|
ravin download COURSE_ID
|
||||||
ravin library
|
ravin serve --open
|
||||||
ravin serve-library --open
|
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
`scan` replaces the former separate course-listing, file-listing, and library-generation commands. It reads the LMS structure, reconciles everything already present on disk, and writes the JSON manifests consumed by the static site.
|
||||||
|
|
||||||
For scripting, use JSON output:
|
Scan only selected courses or print machine-readable results:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ravin --json courses
|
ravin scan 44 45
|
||||||
ravin --json files COURSE_ID
|
ravin scan 44 --json
|
||||||
```
|
```
|
||||||
|
|
||||||
## Configuration
|
Check downloads and learning artifacts without logging in or contacting the LMS:
|
||||||
|
|
||||||
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 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
|
```bash
|
||||||
ravin --web-only --username YOUR_USERNAME courses
|
ravin scan --offline
|
||||||
```
|
```
|
||||||
|
|
||||||
## Browser login and Cloudflare
|
## Authentication and `.env`
|
||||||
|
|
||||||
Ravin Academy protects its account portal and Moodle with a browser check. Set up the browser helper once:
|
`ravin login` opens a persistent, Git-ignored browser profile. For Ravin Academy it begins at `https://lms.ravinacademy.com/`, follows the Moodle launch into `training.ravinacademy.com`, and stores the resulting User-Agent and cookies in `.env`.
|
||||||
|
|
||||||
```bash
|
Missing credentials are requested interactively. You can also copy [`.env.example`](.env.example) and fill it yourself:
|
||||||
python3 -m pip install .
|
|
||||||
ravin login
|
|
||||||
```
|
|
||||||
|
|
||||||
After authentication, `.env` can contain these values:
|
|
||||||
|
|
||||||
```dotenv
|
```dotenv
|
||||||
RAVIN_USERNAME="your username"
|
RAVIN_USERNAME="your username"
|
||||||
@@ -77,99 +61,111 @@ RAVIN_USER_AGENT="the complete browser User-Agent"
|
|||||||
RAVIN_COOKIE="the complete browser Cookie header"
|
RAVIN_COOKIE="the complete browser Cookie header"
|
||||||
```
|
```
|
||||||
|
|
||||||
Later commands reuse `.env`, so you can simply run:
|
`.env` is Git-ignored and written with owner-only permissions. Never commit or share it, the browser profile, your password, or your Cookie value.
|
||||||
|
|
||||||
|
Saved sessions are checked before use. If one expires or Cloudflare rejects it, Ravin opens the authentication browser and replaces the saved values. Useful alternatives are:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ravin --refresh-session scan
|
||||||
|
ravin --manual-session --refresh-session scan
|
||||||
|
ravin --web-only --username YOUR_USERNAME scan
|
||||||
|
```
|
||||||
|
|
||||||
|
## Downloads and activity bundles
|
||||||
|
|
||||||
|
Download a course with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ravin files 44
|
|
||||||
ravin download 44
|
ravin download 44
|
||||||
```
|
```
|
||||||
|
|
||||||
## Static course library
|
Files are stored directly under `public/courses/<course-id>/content/`. Each LMS activity has one sortable, title-independent bundle named:
|
||||||
|
|
||||||
Build a clean local website from your enrolled courses and downloaded files:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
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 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 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 library 44 --output library
|
|
||||||
ravin serve-library --site-dir library --port 8765
|
|
||||||
```
|
|
||||||
|
|
||||||
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 library --reuse-catalog
|
|
||||||
```
|
|
||||||
|
|
||||||
The generated directory contains:
|
|
||||||
|
|
||||||
```text
|
```text
|
||||||
library/
|
SECTION_NUMBER--ACTIVITY_POSITION--ACTIVITY_ID
|
||||||
├── index.html
|
```
|
||||||
├── course.html
|
|
||||||
├── app.js
|
Original filenames stay unchanged in the bundle's `files/` directory. Interrupted downloads use a `.part` suffix and resume with HTTP byte ranges. Completed files are skipped unless `--overwrite` is supplied.
|
||||||
├── styles.css
|
|
||||||
├── courses.json
|
An activity can also contain generated study material:
|
||||||
├── nginx-server.conf
|
|
||||||
└── courses/
|
```text
|
||||||
|
artifacts/
|
||||||
|
├── transcript.fa.txt
|
||||||
|
├── transcript.meta.json
|
||||||
|
├── summary.fa.md
|
||||||
|
├── summary.meta.json
|
||||||
|
└── questions.fa.md
|
||||||
|
```
|
||||||
|
|
||||||
|
The scanner reports each applicable file, transcript, summary, and assessment as `missing`, `partial`, `complete`, `stale`, or `error`. Non-applicable states are recorded as `not_applicable`. Transcript freshness is checked against its source file metadata; summary freshness is checked against the transcript hash.
|
||||||
|
|
||||||
|
The downloader updates the course manifest after every completed file. A final offline scan reconciles all totals, so an interrupted run still retains useful progress.
|
||||||
|
|
||||||
|
## Static learning library
|
||||||
|
|
||||||
|
The web interface is already present in the tracked `public/` directory. Generate or refresh its private data, then serve it:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ravin scan
|
||||||
|
ravin serve --open
|
||||||
|
```
|
||||||
|
|
||||||
|
The site provides course search, chapter grouping, local availability and artifact states, video playback, document and assessment links, transcript and summary readers, Markdown question rendering, dark mode, and browser-local completion checkboxes.
|
||||||
|
|
||||||
|
The layout is:
|
||||||
|
|
||||||
|
```text
|
||||||
|
public/
|
||||||
|
├── index.html # tracked UI
|
||||||
|
├── course.html # tracked UI
|
||||||
|
├── assets/ # tracked CSS and JavaScript
|
||||||
|
└── courses/ # Git-ignored private/generated data
|
||||||
|
├── catalog.json
|
||||||
└── COURSE_ID/
|
└── COURSE_ID/
|
||||||
├── course.json
|
├── manifest.json
|
||||||
└── content/
|
└── content/
|
||||||
└── SECTION--POSITION--ACTIVITY/
|
└── SECTION--POSITION--ACTIVITY/
|
||||||
├── item.json
|
|
||||||
├── files/
|
├── files/
|
||||||
└── artifacts/
|
└── artifacts/
|
||||||
```
|
```
|
||||||
|
|
||||||
For Nginx, include the generated server block inside the `http {}` section of your main configuration:
|
Only `public/courses/` is ignored: contributors can safely commit changes to the shared HTML, CSS, and JavaScript without publishing their enrollments or downloaded material. Manifests never contain passwords, cookies, session tokens, protected file URLs, or machine-specific absolute paths.
|
||||||
|
|
||||||
|
### Nginx
|
||||||
|
|
||||||
|
Point Nginx at `public/`, not the repository root. Replace the example root with the absolute path to your clone:
|
||||||
|
|
||||||
```nginx
|
```nginx
|
||||||
include /absolute/path/to/your/clone/library/nginx-server.conf;
|
server {
|
||||||
|
listen 8765;
|
||||||
|
server_name localhost;
|
||||||
|
|
||||||
|
root /absolute/path/to/easy-learn/public;
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
try_files $uri $uri/ =404;
|
||||||
|
}
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Then check and reload Nginx:
|
After checking and reloading Nginx, open `http://localhost:8765/`. Because its document root is only `public/`, `.env`, source code, the browser profile, and Git metadata cannot be requested from the web server. Nginx handles byte-range media playback automatically.
|
||||||
|
|
||||||
```bash
|
### Previous layouts
|
||||||
nginx -t
|
|
||||||
brew services restart nginx
|
When an older generated `library/courses.json` exists and `public/` has no manifests yet, the first `ravin scan` or `ravin download` performs a one-time migration. It moves the existing activity bundles into `public/courses/`, creates manifests, removes obsolete per-activity `item.json` files, and leaves downloaded media intact.
|
||||||
|
|
||||||
|
## Command reference
|
||||||
|
|
||||||
|
```text
|
||||||
|
ravin login
|
||||||
|
ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH]
|
||||||
|
ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH]
|
||||||
|
ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH]
|
||||||
```
|
```
|
||||||
|
|
||||||
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.
|
Authentication options such as `--site`, `--username`, `--refresh-session`, and `--manual-session` go before the command. Run `ravin --help` or `ravin COMMAND --help` for the complete reference.
|
||||||
|
|
||||||
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 --refresh-session courses
|
|
||||||
```
|
|
||||||
|
|
||||||
If browser automation is unavailable, manual header entry remains available as a fallback:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
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
|
## Development
|
||||||
|
|
||||||
@@ -177,27 +173,27 @@ The project uses a standard `src/` package layout:
|
|||||||
|
|
||||||
```text
|
```text
|
||||||
src/ravin/
|
src/ravin/
|
||||||
├── cli.py # command parsing and orchestration
|
├── cli.py # commands and orchestration
|
||||||
├── auth.py # environment and browser authentication
|
├── auth.py # environment and browser authentication
|
||||||
├── client.py # Moodle API/web client and downloads
|
├── client.py # Moodle API/web client and downloads
|
||||||
├── parsers.py # Moodle HTML parsers
|
├── parsers.py # Moodle HTML parsers
|
||||||
├── paths.py # portable content paths and metadata
|
├── paths.py # portable content paths and artifacts
|
||||||
├── catalog.py # static catalog generation
|
├── catalog.py # remote course catalog construction
|
||||||
├── migration.py # legacy layout migration
|
├── scan.py # manifests and local state reconciliation
|
||||||
|
├── migration.py # previous-layout migration
|
||||||
├── server.py # local range-aware HTTP server
|
├── server.py # local range-aware HTTP server
|
||||||
├── models.py # shared data objects and errors
|
└── models.py # shared value objects and errors
|
||||||
└── assets/ # packaged static library UI
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Run the test suite without installing additional packages:
|
Run the checks with:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
python3 -m unittest discover -s tests -v
|
python3 -m unittest discover -s tests -v
|
||||||
python3 -m compileall -q src tests
|
python3 -m compileall -q src tests
|
||||||
```
|
```
|
||||||
|
|
||||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution guidance and [SECURITY.md](SECURITY.md) for reporting security issues.
|
See [CONTRIBUTING.md](CONTRIBUTING.md) and [SECURITY.md](SECURITY.md) for project guidance.
|
||||||
|
|
||||||
## License and disclaimer
|
## License and disclaimer
|
||||||
|
|
||||||
Released under the [MIT License](LICENSE). This is an independent community project and is not affiliated with or endorsed by Ravin Academy or Moodle HQ.
|
Released under the [MIT License](LICENSE). This independent community project is not affiliated with or endorsed by Ravin Academy or Moodle HQ.
|
||||||
@@ -142,11 +142,18 @@ function setupTheme() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function loadCatalog() {
|
async function loadCatalog() {
|
||||||
const response = await fetch("courses.json", { cache: "no-store" });
|
const response = await fetch("courses/catalog.json", { cache: "no-store" });
|
||||||
if (!response.ok) throw new Error(`Could not load courses.json (${response.status})`);
|
if (!response.ok) throw new Error(`Could not load the course catalog (${response.status})`);
|
||||||
return response.json();
|
return response.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function loadCourse(courseId) {
|
||||||
|
const response = await fetch(`courses/${encodeURIComponent(courseId)}/manifest.json`, { cache: "no-store" });
|
||||||
|
if (!response.ok) throw new Error(`Could not load course ${courseId} (${response.status})`);
|
||||||
|
const manifest = await response.json();
|
||||||
|
return manifest.course;
|
||||||
|
}
|
||||||
|
|
||||||
function showLoadError(error) {
|
function showLoadError(error) {
|
||||||
const target = byId("courseGrid") || byId("sectionList");
|
const target = byId("courseGrid") || byId("sectionList");
|
||||||
if (!target) return;
|
if (!target) return;
|
||||||
@@ -156,7 +163,7 @@ function showLoadError(error) {
|
|||||||
const title = document.createElement("strong");
|
const title = document.createElement("strong");
|
||||||
title.textContent = "The course data could not be loaded";
|
title.textContent = "The course data could not be loaded";
|
||||||
const detail = document.createElement("span");
|
const detail = document.createElement("span");
|
||||||
detail.textContent = "Open this library with ‘ravin serve-library’, then refresh the page.";
|
detail.textContent = "Open this library with ‘ravin serve’, then refresh the page.";
|
||||||
box.append(title, detail);
|
box.append(title, detail);
|
||||||
target.append(box);
|
target.append(box);
|
||||||
console.error(error);
|
console.error(error);
|
||||||
@@ -183,6 +190,11 @@ function courseCard(course) {
|
|||||||
const meta = document.createElement("p");
|
const meta = document.createElement("p");
|
||||||
meta.className = "course-card-meta";
|
meta.className = "course-card-meta";
|
||||||
meta.textContent = `${course.section_count} chapters · ${course.file_count} files · ${formatBytes(course.downloaded_bytes)} offline`;
|
meta.textContent = `${course.section_count} chapters · ${course.file_count} files · ${formatBytes(course.downloaded_bytes)} offline`;
|
||||||
|
const states = document.createElement("p");
|
||||||
|
states.className = "course-state-line";
|
||||||
|
const transcripts = course.states?.transcripts || {};
|
||||||
|
const summaries = course.states?.summaries || {};
|
||||||
|
states.textContent = `${transcripts.complete || 0}/${transcripts.total || 0} transcripts · ${summaries.complete || 0}/${summaries.total || 0} summaries`;
|
||||||
|
|
||||||
const bottom = document.createElement("div");
|
const bottom = document.createElement("div");
|
||||||
bottom.className = "course-card-bottom";
|
bottom.className = "course-card-bottom";
|
||||||
@@ -199,7 +211,7 @@ function courseCard(course) {
|
|||||||
link.href = `course.html?id=${encodeURIComponent(course.id)}`;
|
link.href = `course.html?id=${encodeURIComponent(course.id)}`;
|
||||||
link.innerHTML = `Open course <span aria-hidden="true">→</span>`;
|
link.innerHTML = `Open course <span aria-hidden="true">→</span>`;
|
||||||
bottom.append(track, progress, link);
|
bottom.append(track, progress, link);
|
||||||
card.append(top, title, meta, bottom);
|
card.append(top, title, meta, states, bottom);
|
||||||
return card;
|
return card;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -285,6 +297,19 @@ function resourceRow(item, index) {
|
|||||||
});
|
});
|
||||||
main.append(artifactActions);
|
main.append(artifactActions);
|
||||||
}
|
}
|
||||||
|
const stateLabels = { download: "File", transcript: "Transcript", summary: "Summary", questions: "Questions" };
|
||||||
|
const visibleStates = Object.entries(item.state || {}).filter(([, value]) => value !== "not_applicable");
|
||||||
|
if (visibleStates.length) {
|
||||||
|
const stateChips = document.createElement("div");
|
||||||
|
stateChips.className = "state-chips";
|
||||||
|
visibleStates.forEach(([kind, value]) => {
|
||||||
|
const chip = document.createElement("span");
|
||||||
|
chip.className = `state-chip ${value}`;
|
||||||
|
chip.textContent = `${stateLabels[kind] || kind}: ${value.replace("_", " ")}`;
|
||||||
|
stateChips.append(chip);
|
||||||
|
});
|
||||||
|
main.append(stateChips);
|
||||||
|
}
|
||||||
|
|
||||||
const meta = document.createElement("div");
|
const meta = document.createElement("div");
|
||||||
meta.className = "resource-meta";
|
meta.className = "resource-meta";
|
||||||
@@ -321,7 +346,7 @@ function resourceRow(item, index) {
|
|||||||
action.textContent = "Open LMS";
|
action.textContent = "Open LMS";
|
||||||
} else {
|
} else {
|
||||||
action = document.createElement("span");
|
action = document.createElement("span");
|
||||||
action.textContent = item.status === "partial" ? "Partial" : "Missing";
|
action.textContent = item.status === "partial" ? "Partial" : item.status === "error" ? "Error" : "Missing";
|
||||||
action.setAttribute("aria-disabled", "true");
|
action.setAttribute("aria-disabled", "true");
|
||||||
}
|
}
|
||||||
action.className = "action-button";
|
action.className = "action-button";
|
||||||
@@ -430,7 +455,6 @@ function closeArtifact() {
|
|||||||
|
|
||||||
function renderCourse() {
|
function renderCourse() {
|
||||||
const id = new URLSearchParams(window.location.search).get("id");
|
const id = new URLSearchParams(window.location.search).get("id");
|
||||||
state.course = state.catalog.courses.find((course) => String(course.id) === String(id));
|
|
||||||
if (!state.course) {
|
if (!state.course) {
|
||||||
showLoadError(new Error(`Course ${id || "(missing)"} was not found`));
|
showLoadError(new Error(`Course ${id || "(missing)"} was not found`));
|
||||||
return;
|
return;
|
||||||
@@ -444,6 +468,13 @@ function renderCourse() {
|
|||||||
setText("courseSummary", `${course.activity_count ?? course.file_count} activities, ${course.file_count} downloadable files, and ${course.section_count} chapters.`);
|
setText("courseSummary", `${course.activity_count ?? course.file_count} activities, ${course.file_count} downloadable files, and ${course.section_count} chapters.`);
|
||||||
setText("coursePercent", `${percent}%`);
|
setText("coursePercent", `${percent}%`);
|
||||||
setText("courseDownloaded", `${course.downloaded_count} of ${course.file_count}`);
|
setText("courseDownloaded", `${course.downloaded_count} of ${course.file_count}`);
|
||||||
|
const countState = (name) => {
|
||||||
|
const value = course.states?.[name] || {};
|
||||||
|
return `${value.complete || 0} / ${value.total || 0}`;
|
||||||
|
};
|
||||||
|
setText("transcriptState", countState("transcripts"));
|
||||||
|
setText("summaryState", countState("summaries"));
|
||||||
|
setText("assessmentState", countState("assessments"));
|
||||||
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
|
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
|
||||||
byId("courseProgress").style.setProperty("--progress", percent);
|
byId("courseProgress").style.setProperty("--progress", percent);
|
||||||
byId("courseSource").href = course.source_url;
|
byId("courseSource").href = course.source_url;
|
||||||
@@ -473,8 +504,11 @@ async function start() {
|
|||||||
setupTheme();
|
setupTheme();
|
||||||
try {
|
try {
|
||||||
state.catalog = await loadCatalog();
|
state.catalog = await loadCatalog();
|
||||||
if (document.body.dataset.page === "course") renderCourse();
|
if (document.body.dataset.page === "course") {
|
||||||
else renderIndex();
|
const id = new URLSearchParams(window.location.search).get("id");
|
||||||
|
state.course = await loadCourse(id);
|
||||||
|
renderCourse();
|
||||||
|
} else renderIndex();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
showLoadError(error);
|
showLoadError(error);
|
||||||
}
|
}
|
||||||
@@ -265,6 +265,7 @@ main {
|
|||||||
.course-badge { padding: 5px 9px; border-radius: 999px; color: var(--blue); background: var(--blue-soft); font-size: .72rem; font-weight: 750; }
|
.course-badge { padding: 5px 9px; border-radius: 999px; color: var(--blue); background: var(--blue-soft); font-size: .72rem; font-weight: 750; }
|
||||||
.course-card h3 { margin: 36px 0 10px; font-size: 1.4rem; line-height: 1.28; letter-spacing: -.025em; }
|
.course-card h3 { margin: 36px 0 10px; font-size: 1.4rem; line-height: 1.28; letter-spacing: -.025em; }
|
||||||
.course-card-meta { margin: 0; color: var(--muted); font-size: .85rem; }
|
.course-card-meta { margin: 0; color: var(--muted); font-size: .85rem; }
|
||||||
|
.course-state-line { margin: 8px 0 0; color: var(--muted); font-size: .76rem; }
|
||||||
.course-card-bottom { margin-top: auto; }
|
.course-card-bottom { margin-top: auto; }
|
||||||
|
|
||||||
.progress-track { height: 7px; margin: 28px 0 12px; overflow: hidden; border-radius: 99px; background: var(--line); }
|
.progress-track { height: 7px; margin: 28px 0 12px; overflow: hidden; border-radius: 99px; background: var(--line); }
|
||||||
@@ -279,6 +280,9 @@ main {
|
|||||||
|
|
||||||
.course-hero { min-height: 300px; margin-top: 0; }
|
.course-hero { min-height: 300px; margin-top: 0; }
|
||||||
.course-heading { position: relative; z-index: 1; }
|
.course-heading { position: relative; z-index: 1; }
|
||||||
|
.learning-states { display: flex; flex-wrap: wrap; gap: 8px; margin: 18px 0 2px; }
|
||||||
|
.learning-states span { padding: 7px 10px; border: 1px solid rgba(255,255,255,.18); border-radius: 10px; color: rgba(255,255,255,.68); font-size: .72rem; }
|
||||||
|
.learning-states strong { color: #fff; font-variant-numeric: tabular-nums; }
|
||||||
.progress-panel { position: relative; z-index: 1; display: flex; align-items: center; gap: 18px; min-width: 250px; }
|
.progress-panel { position: relative; z-index: 1; display: flex; align-items: center; gap: 18px; min-width: 250px; }
|
||||||
.progress-panel > div:last-child { display: grid; }
|
.progress-panel > div:last-child { display: grid; }
|
||||||
.progress-panel span { color: rgba(255,255,255,.62); font-size: .78rem; }
|
.progress-panel span { color: rgba(255,255,255,.62); font-size: .78rem; }
|
||||||
@@ -339,6 +343,11 @@ main {
|
|||||||
.artifact-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 9px; }
|
.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 { 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); }
|
.artifact-button:hover { border-color: var(--blue); }
|
||||||
|
.state-chips { display: flex; flex-wrap: wrap; gap: 5px; margin-top: 9px; }
|
||||||
|
.state-chip { padding: 4px 7px; border-radius: 7px; color: var(--muted); background: var(--surface-strong); font-size: .65rem; font-weight: 700; text-transform: capitalize; }
|
||||||
|
.state-chip.complete { color: var(--accent-strong); background: color-mix(in srgb, var(--accent-soft) 78%, transparent); }
|
||||||
|
.state-chip.partial, .state-chip.stale { color: #9a6500; background: #fff2c7; }
|
||||||
|
.state-chip.error, .state-chip.missing { color: var(--danger); background: color-mix(in srgb, var(--danger) 10%, transparent); }
|
||||||
.resource-meta { display: flex; gap: 8px; align-items: center; color: var(--muted); font-size: .74rem; white-space: nowrap; }
|
.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; }
|
.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); }
|
.status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-strong); }
|
||||||
@@ -5,8 +5,8 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<meta name="description" content="Browse the resources in a downloaded course.">
|
<meta name="description" content="Browse the resources in a downloaded course.">
|
||||||
<title>Course · Learning Library</title>
|
<title>Course · Learning Library</title>
|
||||||
<link rel="stylesheet" href="styles.css">
|
<link rel="stylesheet" href="assets/styles.css">
|
||||||
<script src="app.js" defer></script>
|
<script src="assets/app.js" defer></script>
|
||||||
</head>
|
</head>
|
||||||
<body data-page="course">
|
<body data-page="course">
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
@@ -27,6 +27,11 @@
|
|||||||
<p class="eyebrow" id="courseCode">Course</p>
|
<p class="eyebrow" id="courseCode">Course</p>
|
||||||
<h1 id="courseTitle">Loading course…</h1>
|
<h1 id="courseTitle">Loading course…</h1>
|
||||||
<p class="hero-copy" id="courseSummary"></p>
|
<p class="hero-copy" id="courseSummary"></p>
|
||||||
|
<div class="learning-states" aria-label="Course material status">
|
||||||
|
<span><strong id="transcriptState">0 / 0</strong> transcripts</span>
|
||||||
|
<span><strong id="summaryState">0 / 0</strong> summaries</span>
|
||||||
|
<span><strong id="assessmentState">0 / 0</strong> assessments</span>
|
||||||
|
</div>
|
||||||
<a class="hero-source" id="courseSource" href="#" target="_blank" rel="noopener">Open in LMS ↗</a>
|
<a class="hero-source" id="courseSource" href="#" target="_blank" rel="noopener">Open in LMS ↗</a>
|
||||||
</div>
|
</div>
|
||||||
<div class="progress-panel">
|
<div class="progress-panel">
|
||||||
@@ -5,8 +5,8 @@
|
|||||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
<meta name="description" content="A private, local library for downloaded course materials.">
|
<meta name="description" content="A private, local library for downloaded course materials.">
|
||||||
<title>Learning Library</title>
|
<title>Learning Library</title>
|
||||||
<link rel="stylesheet" href="styles.css">
|
<link rel="stylesheet" href="assets/styles.css">
|
||||||
<script src="app.js" defer></script>
|
<script src="assets/app.js" defer></script>
|
||||||
</head>
|
</head>
|
||||||
<body data-page="index">
|
<body data-page="index">
|
||||||
<header class="topbar">
|
<header class="topbar">
|
||||||
+2
-5
@@ -4,8 +4,8 @@ build-backend = "setuptools.build_meta"
|
|||||||
|
|
||||||
[project]
|
[project]
|
||||||
name = "ravin-moodle-downloader"
|
name = "ravin-moodle-downloader"
|
||||||
version = "0.5.0"
|
version = "0.6.0"
|
||||||
description = "List and download authorized course files from Ravin Academy or another Moodle site"
|
description = "Scan, download, and browse authorized Moodle course materials"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.10"
|
requires-python = ">=3.10"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
@@ -34,6 +34,3 @@ package-dir = {"" = "src"}
|
|||||||
|
|
||||||
[tool.setuptools.packages.find]
|
[tool.setuptools.packages.find]
|
||||||
where = ["src"]
|
where = ["src"]
|
||||||
|
|
||||||
[tool.setuptools.package-data]
|
|
||||||
"ravin.assets" = ["*.html", "*.css", "*.js"]
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
"""Static assets for the generated local course library."""
|
|
||||||
+10
-167
@@ -1,24 +1,19 @@
|
|||||||
"""Build, write, and refresh the static course catalog."""
|
"""Build, write, and refresh the static course catalog."""
|
||||||
|
|
||||||
import hashlib
|
import hashlib
|
||||||
import html
|
|
||||||
import json
|
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from importlib import resources
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
from .client import MoodleClient
|
from .client import MoodleClient
|
||||||
from .constants import LIBRARY_ASSETS
|
|
||||||
from .models import FileItem, MoodleError
|
from .models import FileItem, MoodleError
|
||||||
from .paths import (
|
from .paths import (
|
||||||
_activity_directory_name, _activity_root, _clean_name, _course_content_root,
|
_activity_directory_name, _activity_root, _clean_name, _course_content_root,
|
||||||
_discover_artifacts, _read_json_object, _relative_browser_path,
|
_discover_artifacts, _relative_browser_path,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -81,10 +76,15 @@ def _local_activity_record(
|
|||||||
fallback=f"{course_id}\0{activity.get('url', '')}\0{activity.get('name', '')}",
|
fallback=f"{course_id}\0{activity.get('url', '')}\0{activity.get('name', '')}",
|
||||||
)
|
)
|
||||||
directory = _course_content_root(library, course_id) / key
|
directory = _course_content_root(library, course_id) / key
|
||||||
metadata = _read_json_object(directory / "item.json")
|
files_directory = directory / "files"
|
||||||
if not metadata:
|
files = [
|
||||||
|
path.relative_to(directory).as_posix()
|
||||||
|
for path in sorted(files_directory.iterdir())
|
||||||
|
if path.is_file() and not path.name.endswith(".part")
|
||||||
|
] if files_directory.is_dir() else []
|
||||||
|
if not files and not (directory / "artifacts").is_dir():
|
||||||
return None
|
return None
|
||||||
return metadata, directory
|
return {"files": files}, directory
|
||||||
|
|
||||||
|
|
||||||
def _build_library_catalog(
|
def _build_library_catalog(
|
||||||
@@ -154,6 +154,7 @@ def _build_library_catalog(
|
|||||||
"extension": Path(item.filename).suffix.removeprefix(".").casefold(),
|
"extension": Path(item.filename).suffix.removeprefix(".").casefold(),
|
||||||
"kind": _resource_kind(item),
|
"kind": _resource_kind(item),
|
||||||
"mimetype": item.mimetype,
|
"mimetype": item.mimetype,
|
||||||
|
"remote_size": item.filesize,
|
||||||
"status": status,
|
"status": status,
|
||||||
"size": local_bytes if status == "downloaded" else item.filesize,
|
"size": local_bytes if status == "downloaded" else item.filesize,
|
||||||
"local_bytes": local_bytes,
|
"local_bytes": local_bytes,
|
||||||
@@ -315,161 +316,3 @@ def _build_library_catalog(
|
|||||||
},
|
},
|
||||||
"courses": catalog_courses,
|
"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
|
|
||||||
+81
-137
@@ -1,10 +1,10 @@
|
|||||||
"""Command-line parser and application entry point."""
|
"""Command-line parser and application orchestration."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import argparse
|
import argparse
|
||||||
import json
|
import json
|
||||||
import re
|
|
||||||
import sys
|
import sys
|
||||||
from dataclasses import asdict
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from .auth import (
|
from .auth import (
|
||||||
@@ -16,50 +16,31 @@ from .auth import (
|
|||||||
)
|
)
|
||||||
from .client import MoodleClient
|
from .client import MoodleClient
|
||||||
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
|
from .constants import DEFAULT_ENV_FILE, DEFAULT_RAVIN_LOGIN_URL, DEFAULT_SITE, ENV_KEYS, __version__
|
||||||
from .library import (
|
from .migration import migrate_library_to_public
|
||||||
_build_library_catalog,
|
|
||||||
_format_size,
|
|
||||||
_migrate_legacy_downloads,
|
|
||||||
_reuse_library_catalog,
|
|
||||||
_serve_library,
|
|
||||||
_write_library_site,
|
|
||||||
)
|
|
||||||
from .models import MoodleError
|
from .models import MoodleError
|
||||||
|
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
|
||||||
|
from .server import _serve_library
|
||||||
|
|
||||||
|
|
||||||
def build_parser() -> argparse.ArgumentParser:
|
def build_parser() -> argparse.ArgumentParser:
|
||||||
parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.")
|
parser = argparse.ArgumentParser(description="Scan and download your Ravin Academy Moodle courses.")
|
||||||
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
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("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})")
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--login-url",
|
"--login-url",
|
||||||
help=(
|
help=f"account portal used for browser login; defaults to {DEFAULT_RAVIN_LOGIN_URL} for Ravin Academy",
|
||||||
"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("--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("--web-only", action="store_true", help="skip the Moodle mobile API and use a web session")
|
||||||
parser.add_argument(
|
parser.add_argument("--browser-session", action="store_true", help="force browser-session authentication")
|
||||||
"--browser-session",
|
parser.add_argument("--browser-user-agent", help="User-Agent copied from the logged-in browser")
|
||||||
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(
|
parser.add_argument(
|
||||||
"--env-file",
|
"--env-file",
|
||||||
type=Path,
|
type=Path,
|
||||||
default=DEFAULT_ENV_FILE,
|
default=DEFAULT_ENV_FILE,
|
||||||
help=f"credentials and browser-session file (default: {DEFAULT_ENV_FILE})",
|
help=f"credentials and browser-session file (default: {DEFAULT_ENV_FILE})",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument("--refresh-session", action="store_true", help="refresh the saved browser session")
|
||||||
"--refresh-session",
|
|
||||||
action="store_true",
|
|
||||||
help="ignore the saved browser session and open the authentication browser",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
parser.add_argument(
|
||||||
"--manual-session",
|
"--manual-session",
|
||||||
action="store_true",
|
action="store_true",
|
||||||
@@ -71,152 +52,115 @@ def build_parser() -> argparse.ArgumentParser:
|
|||||||
default=Path.cwd() / ".ravin-browser-profile",
|
default=Path.cwd() / ".ravin-browser-profile",
|
||||||
help="persistent profile for automatic browser login",
|
help="persistent profile for automatic browser login",
|
||||||
)
|
)
|
||||||
parser.add_argument(
|
parser.add_argument("--browser-executable", type=Path, help="installed browser executable")
|
||||||
"--browser-executable",
|
parser.add_argument("--login-timeout", type=int, default=600, help="interactive login timeout")
|
||||||
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 = parser.add_subparsers(dest="command", required=True)
|
||||||
|
|
||||||
subparsers.add_parser("login", help="open a browser and refresh the saved LMS session")
|
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")
|
scan_parser = subparsers.add_parser("scan", help="scan LMS courses and reconcile local learning state")
|
||||||
|
scan_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all courses")
|
||||||
|
scan_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||||
|
scan_parser.add_argument("--offline", action="store_true", help="verify existing manifests without contacting LMS")
|
||||||
|
scan_parser.add_argument("--json", action="store_true", help="print machine-readable scan results")
|
||||||
|
|
||||||
|
download_parser = subparsers.add_parser("download", help="scan and download files from one course")
|
||||||
download_parser.add_argument("course_id", type=int)
|
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("--public", type=Path, default=Path("public"), help="public web root")
|
||||||
download_parser.add_argument("--overwrite", action="store_true")
|
download_parser.add_argument("--overwrite", action="store_true")
|
||||||
download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)")
|
download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)")
|
||||||
library_parser = subparsers.add_parser(
|
download_parser.add_argument("--json", action="store_true", help="print downloaded paths as JSON")
|
||||||
"library",
|
|
||||||
help="generate a private static course library and courses.json",
|
serve_parser = subparsers.add_parser("serve", help="serve the public learning library locally")
|
||||||
)
|
serve_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
|
||||||
library_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all courses")
|
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address")
|
||||||
library_parser.add_argument("--output", type=Path, default=Path("library"), help="generated site directory")
|
serve_parser.add_argument("--port", type=int, default=8765, help="local port")
|
||||||
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")
|
serve_parser.add_argument("--open", action="store_true", help="open the library in your default browser")
|
||||||
return parser
|
return parser
|
||||||
|
|
||||||
|
|
||||||
|
def _maybe_migrate(public: Path) -> None:
|
||||||
|
if any((public / "courses").glob("*/manifest.json")):
|
||||||
|
return
|
||||||
|
legacy = Path("library").resolve()
|
||||||
|
if (legacy / "courses.json").is_file():
|
||||||
|
print("Migrating the previous library layout...", file=sys.stderr)
|
||||||
|
migrate_library_to_public(legacy, public)
|
||||||
|
|
||||||
|
|
||||||
|
def _authenticate(args: argparse.Namespace) -> tuple[MoodleClient, str]:
|
||||||
|
args.env_values = _load_env_file(args.env_file)
|
||||||
|
saved_session = _browser_session_values(args, fresh=args.refresh_session)
|
||||||
|
if args.browser_session or args.refresh_session or saved_session is not None:
|
||||||
|
return _authenticate_browser_session(args, saved_session)
|
||||||
|
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)
|
||||||
|
return _authenticate_browser_session(args)
|
||||||
|
return client, mode
|
||||||
|
|
||||||
|
|
||||||
def main(argv: list[str] | None = None) -> int:
|
def main(argv: list[str] | None = None) -> int:
|
||||||
args = build_parser().parse_args(argv)
|
args = build_parser().parse_args(argv)
|
||||||
try:
|
try:
|
||||||
if args.command == "serve-library":
|
if args.command == "serve":
|
||||||
_serve_library(args.site_dir, args.host, args.port, args.open)
|
_serve_library(args.public, args.host, args.port, args.open)
|
||||||
return 0
|
return 0
|
||||||
if args.command == "migrate-library":
|
|
||||||
source = args.source.expanduser().resolve()
|
public = getattr(args, "public", Path("public")).expanduser().resolve()
|
||||||
library = args.library.expanduser().resolve()
|
if args.command in {"scan", "download"}:
|
||||||
result = _migrate_legacy_downloads(source, library, args.course_ids)
|
_maybe_migrate(public)
|
||||||
catalog = _reuse_library_catalog(library)
|
|
||||||
catalog_path = _write_library_site(library, catalog)
|
if args.command == "scan" and args.offline:
|
||||||
moved = sum(int(course.get("moved_files") or 0) for course in result.get("courses", []))
|
catalog = scan_offline(public, args.course_ids)
|
||||||
print(f"Migrated {moved} files and refreshed {catalog_path}.")
|
print(json.dumps(scan_output(catalog), ensure_ascii=False, indent=2) if args.json else format_scan(catalog))
|
||||||
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
|
return 0
|
||||||
|
|
||||||
args.env_values = _load_env_file(args.env_file)
|
args.env_values = _load_env_file(args.env_file)
|
||||||
if args.command == "login":
|
if args.command == "login":
|
||||||
client, mode = _authenticate_browser_session(args)
|
_client, mode = _authenticate_browser_session(args)
|
||||||
print(f"Authenticated using {mode}; updated {args.env_file}.")
|
print(f"Authenticated using {mode}; updated {args.env_file}.")
|
||||||
return 0
|
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(args)
|
||||||
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)
|
print(f"Authenticated using {mode}.", file=sys.stderr)
|
||||||
|
|
||||||
if args.command == "courses":
|
if args.command == "scan":
|
||||||
courses = client.list_courses()
|
catalog = scan_remote(client, public, args.course_ids)
|
||||||
if args.json:
|
print(json.dumps(scan_output(catalog), ensure_ascii=False, indent=2) if args.json else format_scan(catalog))
|
||||||
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
|
return 0
|
||||||
|
|
||||||
|
scan_remote(client, public, [args.course_id])
|
||||||
files = client.list_files(args.course_id)
|
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:
|
if not files:
|
||||||
print("No downloadable files were found.")
|
print("No downloadable files were found.")
|
||||||
return 0
|
return 0
|
||||||
downloaded: list[str] = []
|
downloaded: list[str] = []
|
||||||
for number, item in enumerate(files, 1):
|
for number, item in enumerate(files, 1):
|
||||||
print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr)
|
print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr)
|
||||||
library = args.output.expanduser().resolve()
|
|
||||||
path = client.download(
|
path = client.download(
|
||||||
item,
|
item,
|
||||||
library,
|
public,
|
||||||
overwrite=args.overwrite,
|
overwrite=args.overwrite,
|
||||||
retries=max(args.retries, 0),
|
retries=max(args.retries, 0),
|
||||||
)
|
)
|
||||||
|
update_download_state(public, item, path)
|
||||||
downloaded.append(str(path))
|
downloaded.append(str(path))
|
||||||
|
scan_offline(public, [args.course_id])
|
||||||
if args.json:
|
if args.json:
|
||||||
print(json.dumps(downloaded, ensure_ascii=False, indent=2))
|
print(json.dumps(downloaded, ensure_ascii=False, indent=2))
|
||||||
else:
|
else:
|
||||||
print(f"Downloaded {len(downloaded)} file(s) to {args.output.resolve()}")
|
print(f"Downloaded {len(downloaded)} file(s) into {public / 'courses' / str(args.course_id)}")
|
||||||
return 0
|
return 0
|
||||||
except (MoodleError, KeyboardInterrupt) as exc:
|
except (MoodleError, KeyboardInterrupt) as exc:
|
||||||
if isinstance(exc, KeyboardInterrupt):
|
if isinstance(exc, KeyboardInterrupt):
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ from .paths import (
|
|||||||
_filename_from_headers,
|
_filename_from_headers,
|
||||||
_is_cloudflare_challenge,
|
_is_cloudflare_challenge,
|
||||||
_unique,
|
_unique,
|
||||||
_write_item_metadata,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -461,7 +460,6 @@ class MoodleClient:
|
|||||||
suggested_filename = _clean_name(item.filename, activity)
|
suggested_filename = _clean_name(item.filename, activity)
|
||||||
destination = directory / suggested_filename
|
destination = directory / suggested_filename
|
||||||
if destination.exists() and not overwrite:
|
if destination.exists() and not overwrite:
|
||||||
_write_item_metadata(item, activity_directory, destination)
|
|
||||||
return destination
|
return destination
|
||||||
temporary = destination.with_name(destination.name + ".part")
|
temporary = destination.with_name(destination.name + ".part")
|
||||||
if overwrite:
|
if overwrite:
|
||||||
@@ -482,7 +480,6 @@ class MoodleClient:
|
|||||||
if not temporary.exists() and response_filename != suggested_filename:
|
if not temporary.exists() and response_filename != suggested_filename:
|
||||||
destination = directory / response_filename
|
destination = directory / response_filename
|
||||||
if destination.exists() and not overwrite:
|
if destination.exists() and not overwrite:
|
||||||
_write_item_metadata(item, activity_directory, destination)
|
|
||||||
return destination
|
return destination
|
||||||
temporary = destination.with_name(destination.name + ".part")
|
temporary = destination.with_name(destination.name + ".part")
|
||||||
resume_at = temporary.stat().st_size if temporary.exists() else 0
|
resume_at = temporary.stat().st_size if temporary.exists() else 0
|
||||||
@@ -542,7 +539,6 @@ class MoodleClient:
|
|||||||
f"connection closed early at {downloaded} of {expected_total} bytes"
|
f"connection closed early at {downloaded} of {expected_total} bytes"
|
||||||
)
|
)
|
||||||
temporary.replace(destination)
|
temporary.replace(destination)
|
||||||
_write_item_metadata(item, activity_directory, destination)
|
|
||||||
if sys.stderr.isatty():
|
if sys.stderr.isatty():
|
||||||
elapsed = max(time.monotonic() - started, 0.01)
|
elapsed = max(time.monotonic() - started, 0.01)
|
||||||
rate = downloaded / 1024 / 1024 / elapsed
|
rate = downloaded / 1024 / 1024 / elapsed
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
|||||||
|
|
||||||
DEFAULT_SITE = "https://training.ravinacademy.com"
|
DEFAULT_SITE = "https://training.ravinacademy.com"
|
||||||
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
||||||
__version__ = "0.5.0"
|
__version__ = "0.6.0"
|
||||||
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
||||||
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
||||||
DEFAULT_ENV_FILE = Path.cwd() / ".env"
|
DEFAULT_ENV_FILE = Path.cwd() / ".env"
|
||||||
@@ -16,5 +16,3 @@ ENV_KEYS = {
|
|||||||
"user_agent": "RAVIN_USER_AGENT",
|
"user_agent": "RAVIN_USER_AGENT",
|
||||||
"cookie": "RAVIN_COOKIE",
|
"cookie": "RAVIN_COOKIE",
|
||||||
}
|
}
|
||||||
LIBRARY_ASSETS = ("index.html", "course.html", "styles.css", "app.js")
|
|
||||||
CONTENT_SCHEMA_VERSION = 1
|
|
||||||
+10
-11
@@ -1,19 +1,18 @@
|
|||||||
"""Compatibility facade for the static library subsystems."""
|
"""Public facade for scanning and serving the learning library."""
|
||||||
|
|
||||||
from .catalog import (
|
from .catalog import _build_library_catalog, _format_size
|
||||||
_build_library_catalog,
|
from .migration import migrate_library_to_public
|
||||||
_format_size,
|
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
|
||||||
_reuse_library_catalog,
|
|
||||||
_write_library_site,
|
|
||||||
)
|
|
||||||
from .migration import _migrate_legacy_downloads
|
|
||||||
from .server import _serve_library
|
from .server import _serve_library
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"_build_library_catalog",
|
"_build_library_catalog",
|
||||||
"_format_size",
|
"_format_size",
|
||||||
"_migrate_legacy_downloads",
|
|
||||||
"_reuse_library_catalog",
|
|
||||||
"_serve_library",
|
"_serve_library",
|
||||||
"_write_library_site",
|
"format_scan",
|
||||||
|
"migrate_library_to_public",
|
||||||
|
"scan_offline",
|
||||||
|
"scan_output",
|
||||||
|
"scan_remote",
|
||||||
|
"update_download_state",
|
||||||
]
|
]
|
||||||
+48
-204
@@ -1,218 +1,62 @@
|
|||||||
"""Migrate legacy course files into ordered activity bundles."""
|
"""One-time migration from the generated ``library/`` layout to ``public/``."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
|
||||||
import mimetypes
|
|
||||||
import re
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterable
|
from typing import Any
|
||||||
|
|
||||||
from .constants import CONTENT_SCHEMA_VERSION
|
from .models import MoodleError
|
||||||
from .models import FileItem, MoodleError
|
from .paths import _read_json_object
|
||||||
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:
|
def migrate_library_to_public(legacy: Path, public: Path) -> dict[str, Any]:
|
||||||
if not source.is_file():
|
"""Move private course bundles and create manifests before removing legacy metadata."""
|
||||||
if destination.is_file():
|
catalog_path = legacy / "courses.json"
|
||||||
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)
|
catalog = _read_json_object(catalog_path)
|
||||||
selected = set(selected_course_ids)
|
courses = catalog.get("courses")
|
||||||
courses = [
|
if not isinstance(courses, list) or not courses:
|
||||||
course
|
raise MoodleError(f"legacy course catalog not found: {catalog_path}")
|
||||||
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] = {
|
moved: list[dict[str, Any]] = []
|
||||||
"schema_version": CONTENT_SCHEMA_VERSION,
|
|
||||||
"migrated_at": datetime.now(timezone.utc).isoformat(),
|
|
||||||
"courses": [],
|
|
||||||
}
|
|
||||||
for course in courses:
|
for course in courses:
|
||||||
course_id = int(course.get("id") or 0)
|
course_id = int(course.get("id") or 0)
|
||||||
legacy_course = source_root / str(course_id)
|
source_course = legacy / "courses" / str(course_id)
|
||||||
if not legacy_course.is_dir():
|
target_course = public / "courses" / str(course_id)
|
||||||
continue
|
source_content = source_course / "content"
|
||||||
moved: list[dict[str, str]] = []
|
target_content = target_course / "content"
|
||||||
records: list[tuple[dict[str, Any], dict[str, Any]]] = [
|
if target_content.exists():
|
||||||
(section, record)
|
raise MoodleError(f"migration target already exists: {target_content}")
|
||||||
for section in course.get("sections", [])
|
if not source_content.is_dir():
|
||||||
for record in section.get("items", [])
|
raise MoodleError(f"legacy course content not found: {source_content}")
|
||||||
]
|
target_course.mkdir(parents=True, exist_ok=True)
|
||||||
records_by_filename = {
|
source_content.replace(target_content)
|
||||||
str(record.get("filename")): (section, record)
|
migration_journal = source_course / "migration.json"
|
||||||
for section, record in records
|
if migration_journal.is_file():
|
||||||
if record.get("filename")
|
migration_journal.replace(target_course / "migration.json")
|
||||||
}
|
moved.append({"id": course_id, "content": target_content.as_posix()})
|
||||||
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 = (
|
from .scan import _write_manifests
|
||||||
(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(
|
result = _write_manifests(public, courses, remote=False)
|
||||||
((section, record) for section, record in records if record.get("activity_type") == "quiz"),
|
for course in courses:
|
||||||
key=lambda value: (
|
course_id = int(course.get("id") or 0)
|
||||||
int(value[1].get("section_number", value[0].get("number")) or 0),
|
manifest = public / "courses" / str(course_id) / "manifest.json"
|
||||||
int(value[1].get("activity_position") or 0),
|
if not manifest.is_file():
|
||||||
),
|
raise MoodleError(f"migration did not create {manifest}")
|
||||||
)
|
for item_metadata in (public / "courses" / str(course_id) / "content").rglob("item.json"):
|
||||||
exams_directory = legacy_course / "Course exams"
|
item_metadata.unlink()
|
||||||
exam_pdfs = sorted(exams_directory.glob("*.pdf")) if exams_directory.is_dir() else []
|
source_course = legacy / "courses" / str(course_id)
|
||||||
if len(exam_pdfs) > len(quizzes):
|
(source_course / "course.json").unlink(missing_ok=True)
|
||||||
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:
|
try:
|
||||||
legacy_course.rmdir()
|
source_course.rmdir()
|
||||||
except OSError:
|
except OSError:
|
||||||
pass
|
pass
|
||||||
return migration
|
|
||||||
|
for generated in ("app.js", "course.html", "index.html", "nginx-server.conf", "styles.css", "courses.json"):
|
||||||
|
(legacy / generated).unlink(missing_ok=True)
|
||||||
|
try:
|
||||||
|
(legacy / "courses").rmdir()
|
||||||
|
legacy.rmdir()
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
return {"catalog": result, "moved": moved}
|
||||||
+1
-29
@@ -8,7 +8,6 @@ import urllib.parse
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any, Iterable
|
from typing import Any, Iterable
|
||||||
|
|
||||||
from .constants import CONTENT_SCHEMA_VERSION
|
|
||||||
from .models import FileItem, MoodleError
|
from .models import FileItem, MoodleError
|
||||||
|
|
||||||
|
|
||||||
@@ -73,6 +72,7 @@ def _discover_artifacts(activity_directory: Path, library: Path) -> dict[str, di
|
|||||||
"transcript": ("transcript.fa.txt", "text", "fa"),
|
"transcript": ("transcript.fa.txt", "text", "fa"),
|
||||||
"transcript_metadata": ("transcript.meta.json", "json", None),
|
"transcript_metadata": ("transcript.meta.json", "json", None),
|
||||||
"summary": ("summary.fa.md", "markdown", "fa"),
|
"summary": ("summary.fa.md", "markdown", "fa"),
|
||||||
|
"summary_metadata": ("summary.meta.json", "json", None),
|
||||||
"questions": ("questions.fa.md", "markdown", "fa"),
|
"questions": ("questions.fa.md", "markdown", "fa"),
|
||||||
}
|
}
|
||||||
artifacts: dict[str, dict[str, Any]] = {}
|
artifacts: dict[str, dict[str, Any]] = {}
|
||||||
@@ -92,34 +92,6 @@ def _discover_artifacts(activity_directory: Path, library: Path) -> dict[str, di
|
|||||||
return artifacts
|
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:
|
def _filename_from_headers(headers: Any, url: str, fallback: str) -> str:
|
||||||
disposition = headers.get("Content-Disposition", "")
|
disposition = headers.get("Content-Disposition", "")
|
||||||
star = re.search(r"filename\*=UTF-8''([^;]+)", disposition, flags=re.I)
|
star = re.search(r"filename\*=UTF-8''([^;]+)", disposition, flags=re.I)
|
||||||
|
|||||||
@@ -0,0 +1,397 @@
|
|||||||
|
"""Remote course scanning, local state reconciliation, and manifest storage."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from datetime import datetime, timezone
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any, Iterable, Iterator
|
||||||
|
|
||||||
|
from .catalog import _build_library_catalog
|
||||||
|
from .client import MoodleClient
|
||||||
|
from .models import FileItem, MoodleError
|
||||||
|
from .paths import (
|
||||||
|
_activity_directory_name,
|
||||||
|
_course_content_root,
|
||||||
|
_discover_artifacts,
|
||||||
|
_read_json_object,
|
||||||
|
_relative_browser_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
MANIFEST_SCHEMA_VERSION = 1
|
||||||
|
STATE_VALUES = {"missing", "partial", "complete", "stale", "error", "not_applicable"}
|
||||||
|
|
||||||
|
|
||||||
|
def _utc_now() -> str:
|
||||||
|
return datetime.now(timezone.utc).isoformat()
|
||||||
|
|
||||||
|
|
||||||
|
def _atomic_json(path: Path, value: dict[str, Any]) -> None:
|
||||||
|
path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
temporary = path.with_name(path.name + ".tmp")
|
||||||
|
temporary.write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||||
|
temporary.replace(path)
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def _manifest_lock(courses_root: Path) -> Iterator[None]:
|
||||||
|
courses_root.mkdir(parents=True, exist_ok=True)
|
||||||
|
lock_path = courses_root / ".manifest.lock"
|
||||||
|
with lock_path.open("a+", encoding="utf-8") as lock:
|
||||||
|
try:
|
||||||
|
import fcntl
|
||||||
|
|
||||||
|
fcntl.flock(lock.fileno(), fcntl.LOCK_EX)
|
||||||
|
except (ImportError, OSError):
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
try:
|
||||||
|
import fcntl
|
||||||
|
|
||||||
|
fcntl.flock(lock.fileno(), fcntl.LOCK_UN)
|
||||||
|
except (ImportError, OSError):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def _activity_directory(public: Path, course_id: int, section: dict[str, Any], item: dict[str, Any]) -> Path:
|
||||||
|
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', '')}",
|
||||||
|
)
|
||||||
|
item["key"] = key
|
||||||
|
item["bundle_path"] = f"content/{key}"
|
||||||
|
return _course_content_root(public, course_id) / key
|
||||||
|
|
||||||
|
|
||||||
|
def _sha256(path: Path) -> str:
|
||||||
|
digest = hashlib.sha256()
|
||||||
|
with path.open("rb") as source:
|
||||||
|
for chunk in iter(lambda: source.read(1024 * 1024), b""):
|
||||||
|
digest.update(chunk)
|
||||||
|
return digest.hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def _summary_metadata(summary: Path, transcript: Path) -> dict[str, Any]:
|
||||||
|
transcript_stat = transcript.stat()
|
||||||
|
return {
|
||||||
|
"schema_version": MANIFEST_SCHEMA_VERSION,
|
||||||
|
"source": "transcript.fa.txt",
|
||||||
|
"source_sha256": _sha256(transcript),
|
||||||
|
"source_size": transcript_stat.st_size,
|
||||||
|
"source_mtime_ns": transcript_stat.st_mtime_ns,
|
||||||
|
"generated_at": datetime.fromtimestamp(summary.stat().st_mtime, timezone.utc).isoformat(),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _artifact_state(activity_directory: Path, kind: str, applicable: bool) -> str:
|
||||||
|
artifacts = activity_directory / "artifacts"
|
||||||
|
if kind == "transcript":
|
||||||
|
transcript = artifacts / "transcript.fa.txt"
|
||||||
|
if not transcript.is_file():
|
||||||
|
return "missing" if applicable else "not_applicable"
|
||||||
|
metadata = _read_json_object(artifacts / "transcript.meta.json")
|
||||||
|
source_files: list[Path] = []
|
||||||
|
source_name = metadata.get("source") if metadata else None
|
||||||
|
if isinstance(source_name, str):
|
||||||
|
candidate = (artifacts / source_name).resolve()
|
||||||
|
try:
|
||||||
|
candidate.relative_to(activity_directory.resolve())
|
||||||
|
except ValueError:
|
||||||
|
candidate = Path()
|
||||||
|
if candidate.is_file():
|
||||||
|
source_files.append(candidate)
|
||||||
|
if not source_files:
|
||||||
|
source_files = sorted(
|
||||||
|
path
|
||||||
|
for path in (activity_directory / "files").glob("*")
|
||||||
|
if path.is_file() and not path.name.endswith(".part")
|
||||||
|
)
|
||||||
|
if not metadata or not source_files:
|
||||||
|
return "stale"
|
||||||
|
source_stat = source_files[0].stat()
|
||||||
|
expected_size = metadata.get("source_size")
|
||||||
|
expected_mtime = metadata.get("source_mtime_ns")
|
||||||
|
if expected_size is not None and int(expected_size) != source_stat.st_size:
|
||||||
|
return "stale"
|
||||||
|
if expected_mtime is not None and int(expected_mtime) != source_stat.st_mtime_ns:
|
||||||
|
return "stale"
|
||||||
|
return "complete"
|
||||||
|
|
||||||
|
if kind == "summary":
|
||||||
|
summary = artifacts / "summary.fa.md"
|
||||||
|
if not summary.is_file():
|
||||||
|
return "missing" if applicable else "not_applicable"
|
||||||
|
transcript = artifacts / "transcript.fa.txt"
|
||||||
|
if not transcript.is_file():
|
||||||
|
return "stale"
|
||||||
|
metadata_path = artifacts / "summary.meta.json"
|
||||||
|
metadata = _read_json_object(metadata_path)
|
||||||
|
current = _summary_metadata(summary, transcript)
|
||||||
|
if not metadata:
|
||||||
|
_atomic_json(metadata_path, current)
|
||||||
|
return "complete"
|
||||||
|
if (
|
||||||
|
metadata.get("source_sha256") != current["source_sha256"]
|
||||||
|
or int(metadata.get("source_size") or -1) != current["source_size"]
|
||||||
|
or int(metadata.get("source_mtime_ns") or -1) != current["source_mtime_ns"]
|
||||||
|
):
|
||||||
|
return "stale"
|
||||||
|
return "complete"
|
||||||
|
|
||||||
|
questions = artifacts / "questions.fa.md"
|
||||||
|
if questions.is_file():
|
||||||
|
return "complete"
|
||||||
|
return "missing" if applicable else "not_applicable"
|
||||||
|
|
||||||
|
|
||||||
|
def _download_state(activity_directory: Path, item: dict[str, Any]) -> tuple[str, Path | None]:
|
||||||
|
filename = str(item.get("filename") or "")
|
||||||
|
files_directory = activity_directory / "files"
|
||||||
|
final = files_directory / filename if filename else None
|
||||||
|
if final and final.is_file():
|
||||||
|
expected_size = item.get("remote_size")
|
||||||
|
if expected_size is not None and int(expected_size) != final.stat().st_size:
|
||||||
|
return "error", final
|
||||||
|
return "complete", final
|
||||||
|
partial = final.with_name(final.name + ".part") if final else None
|
||||||
|
if partial and partial.is_file():
|
||||||
|
return "partial", partial
|
||||||
|
if filename or item.get("activity_type") in {"resource", "folder", "page", "book"}:
|
||||||
|
return "missing", None
|
||||||
|
return "not_applicable", None
|
||||||
|
|
||||||
|
|
||||||
|
def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
course_id = int(course.get("id") or 0)
|
||||||
|
downloaded_bytes = 0
|
||||||
|
type_counts: dict[str, int] = {}
|
||||||
|
state_counts = {
|
||||||
|
"downloads": {"complete": 0, "total": 0},
|
||||||
|
"transcripts": {"complete": 0, "total": 0},
|
||||||
|
"summaries": {"complete": 0, "total": 0},
|
||||||
|
"assessments": {"complete": 0, "total": 0},
|
||||||
|
"partial": 0,
|
||||||
|
"stale": 0,
|
||||||
|
"errors": 0,
|
||||||
|
}
|
||||||
|
records = 0
|
||||||
|
for section in course.get("sections", []):
|
||||||
|
for item in section.get("items", []):
|
||||||
|
records += 1
|
||||||
|
activity_directory = _activity_directory(public, course_id, section, item)
|
||||||
|
download_state, local_path = _download_state(activity_directory, item)
|
||||||
|
media_applicable = item.get("kind") in {"video", "audio"}
|
||||||
|
assessment_applicable = item.get("kind") == "assessment" or item.get("activity_type") == "quiz"
|
||||||
|
transcript_state = _artifact_state(activity_directory, "transcript", media_applicable)
|
||||||
|
summary_state = _artifact_state(activity_directory, "summary", media_applicable)
|
||||||
|
questions_state = _artifact_state(activity_directory, "questions", assessment_applicable)
|
||||||
|
for value in (download_state, transcript_state, summary_state, questions_state):
|
||||||
|
if value not in STATE_VALUES:
|
||||||
|
raise MoodleError(f"invalid manifest state {value!r}")
|
||||||
|
item["state"] = {
|
||||||
|
"download": download_state,
|
||||||
|
"transcript": transcript_state,
|
||||||
|
"summary": summary_state,
|
||||||
|
"questions": questions_state,
|
||||||
|
}
|
||||||
|
item["downloaded"] = download_state == "complete"
|
||||||
|
item["transcribed"] = transcript_state == "complete"
|
||||||
|
item["summarized"] = summary_state == "complete"
|
||||||
|
item["status"] = (
|
||||||
|
"downloaded" if download_state == "complete"
|
||||||
|
else "online" if download_state == "not_applicable"
|
||||||
|
else download_state
|
||||||
|
)
|
||||||
|
item["artifacts"] = _discover_artifacts(activity_directory, public)
|
||||||
|
if local_path:
|
||||||
|
item["local_bytes"] = local_path.stat().st_size
|
||||||
|
item["local_url"] = _relative_browser_path(local_path, public)
|
||||||
|
if download_state == "complete":
|
||||||
|
item["size"] = local_path.stat().st_size
|
||||||
|
downloaded_bytes += local_path.stat().st_size
|
||||||
|
else:
|
||||||
|
item["local_bytes"] = 0
|
||||||
|
item["local_url"] = None
|
||||||
|
if download_state != "not_applicable":
|
||||||
|
state_counts["downloads"]["total"] += 1
|
||||||
|
state_counts["downloads"]["complete"] += int(download_state == "complete")
|
||||||
|
if media_applicable:
|
||||||
|
state_counts["transcripts"]["total"] += 1
|
||||||
|
state_counts["transcripts"]["complete"] += int(transcript_state == "complete")
|
||||||
|
state_counts["summaries"]["total"] += 1
|
||||||
|
state_counts["summaries"]["complete"] += int(summary_state == "complete")
|
||||||
|
if assessment_applicable:
|
||||||
|
state_counts["assessments"]["total"] += 1
|
||||||
|
state_counts["assessments"]["complete"] += int(questions_state == "complete")
|
||||||
|
state_counts["partial"] += int(download_state == "partial")
|
||||||
|
state_counts["stale"] += sum(value == "stale" for value in (transcript_state, summary_state))
|
||||||
|
state_counts["errors"] += int(download_state == "error")
|
||||||
|
kind = str(item.get("kind") or "activity")
|
||||||
|
type_counts[kind] = type_counts.get(kind, 0) + 1
|
||||||
|
|
||||||
|
course.update(
|
||||||
|
{
|
||||||
|
"record_count": records,
|
||||||
|
"file_count": state_counts["downloads"]["total"],
|
||||||
|
"downloaded_count": state_counts["downloads"]["complete"],
|
||||||
|
"downloaded_bytes": downloaded_bytes,
|
||||||
|
"type_counts": type_counts,
|
||||||
|
"states": state_counts,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return course
|
||||||
|
|
||||||
|
|
||||||
|
def _course_summary(course: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
key: course.get(key)
|
||||||
|
for key in (
|
||||||
|
"id", "fullname", "shortname", "source_url", "section_count", "activity_count",
|
||||||
|
"record_count", "file_count", "downloaded_count", "downloaded_bytes", "type_counts", "states",
|
||||||
|
)
|
||||||
|
} | {"manifest_url": f"courses/{course.get('id')}/manifest.json"}
|
||||||
|
|
||||||
|
|
||||||
|
def _catalog_from_manifests(courses_root: Path, now: str) -> dict[str, Any]:
|
||||||
|
courses: list[dict[str, Any]] = []
|
||||||
|
for path in sorted(courses_root.glob("*/manifest.json")):
|
||||||
|
course = _read_json_object(path).get("course")
|
||||||
|
if isinstance(course, dict):
|
||||||
|
courses.append(course)
|
||||||
|
courses.sort(key=lambda course: str(course.get("fullname") or "").casefold())
|
||||||
|
return {
|
||||||
|
"schema_version": MANIFEST_SCHEMA_VERSION,
|
||||||
|
"generated_at": now,
|
||||||
|
"stats": {
|
||||||
|
"courses": len(courses),
|
||||||
|
"activities": sum(int(course.get("activity_count") or 0) for course in courses),
|
||||||
|
"records": sum(int(course.get("record_count") or 0) for course in courses),
|
||||||
|
"files": sum(int(course.get("file_count") or 0) for course in courses),
|
||||||
|
"downloaded_files": sum(int(course.get("downloaded_count") or 0) for course in courses),
|
||||||
|
"downloaded_bytes": sum(int(course.get("downloaded_bytes") or 0) for course in courses),
|
||||||
|
},
|
||||||
|
"courses": [_course_summary(course) for course in courses],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _write_manifests(public: Path, courses: Iterable[dict[str, Any]], *, remote: bool) -> dict[str, Any]:
|
||||||
|
courses_root = public / "courses"
|
||||||
|
now = _utc_now()
|
||||||
|
with _manifest_lock(courses_root):
|
||||||
|
for course in courses:
|
||||||
|
reconciled = _reconcile_course(public, course)
|
||||||
|
manifest_path = courses_root / str(course["id"]) / "manifest.json"
|
||||||
|
previous = _read_json_object(manifest_path)
|
||||||
|
scan = dict(previous.get("scan") or {})
|
||||||
|
scan["local_at"] = now
|
||||||
|
if remote:
|
||||||
|
scan["remote_at"] = now
|
||||||
|
manifest = {
|
||||||
|
"schema_version": MANIFEST_SCHEMA_VERSION,
|
||||||
|
"generated_at": now,
|
||||||
|
"scan": scan,
|
||||||
|
"course": reconciled,
|
||||||
|
}
|
||||||
|
_atomic_json(manifest_path, manifest)
|
||||||
|
catalog = _catalog_from_manifests(courses_root, now)
|
||||||
|
_atomic_json(courses_root / "catalog.json", catalog)
|
||||||
|
return catalog
|
||||||
|
|
||||||
|
|
||||||
|
def scan_remote(client: MoodleClient, public: Path, course_ids: Iterable[int] = ()) -> dict[str, Any]:
|
||||||
|
full_catalog = _build_library_catalog(client, public, course_ids)
|
||||||
|
return _write_manifests(public, full_catalog.get("courses", []), remote=True)
|
||||||
|
|
||||||
|
|
||||||
|
def scan_offline(public: Path, course_ids: Iterable[int] = ()) -> dict[str, Any]:
|
||||||
|
courses_root = public / "courses"
|
||||||
|
selected = set(course_ids)
|
||||||
|
manifests = sorted(courses_root.glob("*/manifest.json"))
|
||||||
|
courses = []
|
||||||
|
for path in manifests:
|
||||||
|
manifest = _read_json_object(path)
|
||||||
|
course = manifest.get("course")
|
||||||
|
if not isinstance(course, dict):
|
||||||
|
continue
|
||||||
|
course_id = int(course.get("id") or 0)
|
||||||
|
if selected and course_id not in selected:
|
||||||
|
continue
|
||||||
|
courses.append(course)
|
||||||
|
missing = selected - {int(course.get("id") or 0) for course in courses}
|
||||||
|
if missing:
|
||||||
|
raise MoodleError(f"course manifest(s) not found: {', '.join(str(value) for value in sorted(missing))}")
|
||||||
|
if not courses:
|
||||||
|
raise MoodleError(f"no course manifests found in {courses_root}; run `ravin scan` online first")
|
||||||
|
return _write_manifests(public, courses, remote=False)
|
||||||
|
|
||||||
|
|
||||||
|
def update_download_state(public: Path, item: FileItem, path: Path) -> None:
|
||||||
|
if not path.is_file():
|
||||||
|
return
|
||||||
|
manifest_path = public / "courses" / str(item.course_id) / "manifest.json"
|
||||||
|
courses_root = public / "courses"
|
||||||
|
with _manifest_lock(courses_root):
|
||||||
|
manifest = _read_json_object(manifest_path)
|
||||||
|
course = manifest.get("course")
|
||||||
|
if not isinstance(course, dict):
|
||||||
|
return
|
||||||
|
now = _utc_now()
|
||||||
|
manifest["course"] = _reconcile_course(public, course)
|
||||||
|
manifest["generated_at"] = now
|
||||||
|
scan = dict(manifest.get("scan") or {})
|
||||||
|
scan["local_at"] = now
|
||||||
|
manifest["scan"] = scan
|
||||||
|
_atomic_json(manifest_path, manifest)
|
||||||
|
_atomic_json(courses_root / "catalog.json", _catalog_from_manifests(courses_root, now))
|
||||||
|
|
||||||
|
|
||||||
|
def scan_output(catalog: dict[str, Any]) -> list[dict[str, Any]]:
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": course.get("id"),
|
||||||
|
"title": course.get("fullname"),
|
||||||
|
"sections": course.get("section_count"),
|
||||||
|
"activities": course.get("activity_count"),
|
||||||
|
"downloads": course.get("states", {}).get("downloads", {}),
|
||||||
|
"transcripts": course.get("states", {}).get("transcripts", {}),
|
||||||
|
"summaries": course.get("states", {}).get("summaries", {}),
|
||||||
|
"assessments": course.get("states", {}).get("assessments", {}),
|
||||||
|
"partial": course.get("states", {}).get("partial", 0),
|
||||||
|
"stale": course.get("states", {}).get("stale", 0),
|
||||||
|
"errors": course.get("states", {}).get("errors", 0),
|
||||||
|
}
|
||||||
|
for course in catalog.get("courses", [])
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def format_scan(catalog: dict[str, Any]) -> str:
|
||||||
|
blocks = []
|
||||||
|
for course in scan_output(catalog):
|
||||||
|
def count(name: str) -> str:
|
||||||
|
state = course[name]
|
||||||
|
return f"{int(state.get('complete') or 0):>3} / {int(state.get('total') or 0):<3} complete"
|
||||||
|
|
||||||
|
blocks.append(
|
||||||
|
"\n".join(
|
||||||
|
(
|
||||||
|
f"Course {course['id']} — {course['title']}",
|
||||||
|
f"{course['activities']} activities across {course['sections']} sections",
|
||||||
|
"",
|
||||||
|
f"Downloads {count('downloads')}",
|
||||||
|
f"Transcripts {count('transcripts')}",
|
||||||
|
f"Summaries {count('summaries')}",
|
||||||
|
f"Assessments {count('assessments')}",
|
||||||
|
f"Partial {course['partial']}",
|
||||||
|
f"Stale {course['stale']}",
|
||||||
|
f"Errors {course['errors']}",
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return "\n\n".join(blocks)
|
||||||
+5
-5
@@ -86,11 +86,11 @@ class _RangeRequestHandler(http.server.SimpleHTTPRequestHandler):
|
|||||||
remaining -= len(chunk)
|
remaining -= len(chunk)
|
||||||
|
|
||||||
|
|
||||||
def _serve_library(site_dir: Path, host: str, port: int, open_browser: bool) -> None:
|
def _serve_library(public: Path, host: str, port: int, open_browser: bool) -> None:
|
||||||
site_dir = site_dir.expanduser().resolve()
|
public = public.expanduser().resolve()
|
||||||
if not (site_dir / "index.html").is_file() or not (site_dir / "courses.json").is_file():
|
if not (public / "index.html").is_file() or not (public / "courses" / "catalog.json").is_file():
|
||||||
raise MoodleError(f"{site_dir} is not built yet; run `ravin library` first")
|
raise MoodleError(f"{public} is not ready; run `ravin scan` first")
|
||||||
handler = functools.partial(_RangeRequestHandler, directory=str(site_dir))
|
handler = functools.partial(_RangeRequestHandler, directory=str(public))
|
||||||
try:
|
try:
|
||||||
server = http.server.ThreadingHTTPServer((host, port), handler)
|
server = http.server.ThreadingHTTPServer((host, port), handler)
|
||||||
except OSError as exc:
|
except OSError as exc:
|
||||||
|
|||||||
+68
-100
@@ -20,12 +20,7 @@ from ravin.auth import (
|
|||||||
_save_env_values,
|
_save_env_values,
|
||||||
)
|
)
|
||||||
from ravin.cli import build_parser
|
from ravin.cli import build_parser
|
||||||
from ravin.library import (
|
from ravin.migration import migrate_library_to_public
|
||||||
_build_library_catalog,
|
|
||||||
_migrate_legacy_downloads,
|
|
||||||
_reuse_library_catalog,
|
|
||||||
_write_library_site,
|
|
||||||
)
|
|
||||||
from ravin.parsers import (
|
from ravin.parsers import (
|
||||||
_CourseStructureParser,
|
_CourseStructureParser,
|
||||||
_FormParser,
|
_FormParser,
|
||||||
@@ -39,6 +34,7 @@ from ravin.paths import (
|
|||||||
_is_cloudflare_challenge,
|
_is_cloudflare_challenge,
|
||||||
_unique,
|
_unique,
|
||||||
)
|
)
|
||||||
|
from ravin.scan import scan_offline, scan_remote
|
||||||
|
|
||||||
|
|
||||||
class _FakeResponse:
|
class _FakeResponse:
|
||||||
@@ -88,12 +84,16 @@ class ParserTests(unittest.TestCase):
|
|||||||
self.assertEqual(args.command, "login")
|
self.assertEqual(args.command, "login")
|
||||||
self.assertFalse(args.manual_session)
|
self.assertFalse(args.manual_session)
|
||||||
|
|
||||||
def test_library_commands_parse(self):
|
def test_scan_download_and_serve_commands_parse(self):
|
||||||
build = build_parser().parse_args(["library", "44", "--output", "my-library", "--reuse-catalog"])
|
scan = build_parser().parse_args(["scan", "44", "--public", "site", "--offline", "--json"])
|
||||||
self.assertEqual(build.course_ids, [44])
|
self.assertEqual(scan.course_ids, [44])
|
||||||
self.assertEqual(build.output, Path("my-library"))
|
self.assertEqual(scan.public, Path("site"))
|
||||||
self.assertTrue(build.reuse_catalog)
|
self.assertTrue(scan.offline)
|
||||||
serve = build_parser().parse_args(["serve-library", "--port", "9000"])
|
self.assertTrue(scan.json)
|
||||||
|
download = build_parser().parse_args(["download", "44", "--retries", "2"])
|
||||||
|
self.assertEqual(download.course_id, 44)
|
||||||
|
self.assertEqual(download.retries, 2)
|
||||||
|
serve = build_parser().parse_args(["serve", "--port", "9000"])
|
||||||
self.assertEqual(serve.port, 9000)
|
self.assertEqual(serve.port, 9000)
|
||||||
|
|
||||||
def test_browser_login_captures_user_agent_and_cookies(self):
|
def test_browser_login_captures_user_agent_and_cookies(self):
|
||||||
@@ -289,7 +289,7 @@ class ParserTests(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
|
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
|
||||||
|
|
||||||
def test_builds_static_library_catalog_from_library_content(self):
|
def test_scan_writes_public_catalog_and_course_manifest(self):
|
||||||
class FakeClient:
|
class FakeClient:
|
||||||
site = "https://training.example"
|
site = "https://training.example"
|
||||||
|
|
||||||
@@ -306,7 +306,7 @@ class ParserTests(unittest.TestCase):
|
|||||||
"1.mp4",
|
"1.mp4",
|
||||||
"https://training.example/pluginfile.php/10/1.mp4?token=secret",
|
"https://training.example/pluginfile.php/10/1.mp4?token=secret",
|
||||||
"video/mp4",
|
"video/mp4",
|
||||||
10,
|
5,
|
||||||
section_id=940,
|
section_id=940,
|
||||||
section_number=2,
|
section_number=2,
|
||||||
activity_id=4940,
|
activity_id=4940,
|
||||||
@@ -331,73 +331,71 @@ class ParserTests(unittest.TestCase):
|
|||||||
|
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
root = Path(directory)
|
root = Path(directory)
|
||||||
output = root / "library"
|
output = root / "public"
|
||||||
video = output / "courses" / "44" / "content" / "002--001--4940" / "files" / "1.mp4"
|
video = output / "courses" / "44" / "content" / "002--001--4940" / "files" / "1.mp4"
|
||||||
video.parent.mkdir(parents=True)
|
video.parent.mkdir(parents=True)
|
||||||
video.write_bytes(b"video")
|
video.write_bytes(b"video")
|
||||||
catalog = _build_library_catalog(FakeClient(), output)
|
catalog = scan_remote(FakeClient(), output)
|
||||||
self.assertEqual(catalog["stats"]["courses"], 1)
|
self.assertEqual(catalog["stats"]["courses"], 1)
|
||||||
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
|
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
|
||||||
items = catalog["courses"][0]["sections"][0]["items"]
|
manifest_path = output / "courses" / "44" / "manifest.json"
|
||||||
|
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||||
|
items = [
|
||||||
|
item
|
||||||
|
for section in manifest["course"]["sections"]
|
||||||
|
for item in section["items"]
|
||||||
|
]
|
||||||
self.assertEqual(items[0]["title"], "Introduction")
|
self.assertEqual(items[0]["title"], "Introduction")
|
||||||
self.assertEqual(items[0]["kind"], "video")
|
self.assertEqual(items[0]["kind"], "video")
|
||||||
self.assertEqual(items[0]["status"], "downloaded")
|
self.assertEqual(items[0]["status"], "downloaded")
|
||||||
self.assertEqual(items[0]["local_url"], "courses/44/content/002--001--4940/files/1.mp4")
|
self.assertEqual(items[0]["local_url"], "courses/44/content/002--001--4940/files/1.mp4")
|
||||||
|
self.assertEqual(items[0]["state"]["download"], "complete")
|
||||||
|
self.assertEqual(items[0]["state"]["transcript"], "missing")
|
||||||
self.assertEqual(items[1]["status"], "missing")
|
self.assertEqual(items[1]["status"], "missing")
|
||||||
catalog_path = _write_library_site(output, catalog)
|
written = json.loads((output / "courses" / "catalog.json").read_text(encoding="utf-8"))
|
||||||
written = json.loads(catalog_path.read_text(encoding="utf-8"))
|
self.assertEqual(written["schema_version"], 1)
|
||||||
self.assertEqual(written["schema_version"], 3)
|
self.assertEqual(written["courses"][0]["manifest_url"], "courses/44/manifest.json")
|
||||||
self.assertTrue((output / "index.html").is_file())
|
self.assertFalse((output / "index.html").exists())
|
||||||
self.assertTrue((output / "course.html").is_file())
|
|
||||||
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_refreshes_library_links(self):
|
def test_offline_scan_refreshes_local_artifact_state(self):
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
root = Path(directory)
|
root = Path(directory)
|
||||||
output = root / "library"
|
output = root / "public"
|
||||||
media = output / "courses" / "44" / "content" / "002--001--4940" / "files" / "1.mp4"
|
media = output / "courses" / "44" / "content" / "002--001--4940" / "files" / "1.mp4"
|
||||||
media.parent.mkdir(parents=True)
|
media.parent.mkdir(parents=True)
|
||||||
media.write_bytes(b"video")
|
media.write_bytes(b"video")
|
||||||
(media.parent.parent / "item.json").write_text(
|
manifest_path = output / "courses" / "44" / "manifest.json"
|
||||||
json.dumps({"files": ["files/1.mp4"]}),
|
manifest_path.write_text(
|
||||||
encoding="utf-8",
|
|
||||||
)
|
|
||||||
(output / "courses.json").write_text(
|
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
"courses": [
|
"schema_version": 1,
|
||||||
{
|
"course": {
|
||||||
"id": 44,
|
"id": 44,
|
||||||
"sections": [
|
"fullname": "Network +",
|
||||||
{
|
"sections": [{
|
||||||
"items": [
|
"number": 2,
|
||||||
{
|
"items": [{
|
||||||
"local_url": None,
|
"filename": "1.mp4",
|
||||||
"filename": "1.mp4",
|
"activity_type": "resource",
|
||||||
"activity_type": "resource",
|
"kind": "video",
|
||||||
"title": "Introduction to Networks",
|
"title": "Introduction to Networks",
|
||||||
"status": "online",
|
"section_number": 2,
|
||||||
"section_number": 2,
|
"activity_position": 1,
|
||||||
"activity_position": 1,
|
"activity_id": 4940,
|
||||||
"activity_id": 4940,
|
}],
|
||||||
},
|
}],
|
||||||
]
|
},
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
),
|
),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
catalog = _reuse_library_catalog(output)
|
catalog = scan_offline(output, [44])
|
||||||
item = catalog["courses"][0]["sections"][0]["items"][0]
|
refreshed = json.loads(manifest_path.read_text(encoding="utf-8"))
|
||||||
|
item = refreshed["course"]["sections"][0]["items"][0]
|
||||||
self.assertEqual(item["local_url"], "courses/44/content/002--001--4940/files/1.mp4")
|
self.assertEqual(item["local_url"], "courses/44/content/002--001--4940/files/1.mp4")
|
||||||
self.assertEqual(item["status"], "downloaded")
|
self.assertEqual(item["status"], "downloaded")
|
||||||
self.assertIn("prepared_at", catalog)
|
self.assertEqual(item["state"]["download"], "complete")
|
||||||
|
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
|
||||||
|
|
||||||
def test_interrupted_download_retries_with_range(self):
|
def test_interrupted_download_retries_with_range(self):
|
||||||
first = _FakeResponse(
|
first = _FakeResponse(
|
||||||
@@ -432,25 +430,15 @@ class ParserTests(unittest.TestCase):
|
|||||||
self.assertEqual(destination.read_bytes(), b"1234567890")
|
self.assertEqual(destination.read_bytes(), b"1234567890")
|
||||||
self.assertEqual(client.request_headers, [{"Range": "bytes=5-"}])
|
self.assertEqual(client.request_headers, [{"Range": "bytes=5-"}])
|
||||||
|
|
||||||
def test_migrates_legacy_video_artifacts_and_exam_in_course_order(self):
|
def test_migrates_existing_library_bundles_into_public(self):
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
root = Path(directory)
|
root = Path(directory)
|
||||||
source = root / "downloads"
|
|
||||||
library = root / "library"
|
library = root / "library"
|
||||||
course_files = source / "44" / "Course files"
|
public = root / "public"
|
||||||
exams = source / "44" / "Course exams"
|
lesson = library / "courses" / "44" / "content" / "016--001--4954"
|
||||||
course_files.mkdir(parents=True)
|
(lesson / "files").mkdir(parents=True)
|
||||||
exams.mkdir(parents=True)
|
(lesson / "files" / "15.mp4").write_bytes(b"video")
|
||||||
(course_files / "15.mp4").write_bytes(b"video")
|
(lesson / "item.json").write_text("{}", encoding="utf-8")
|
||||||
(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(
|
(library / "courses.json").write_text(
|
||||||
json.dumps(
|
json.dumps(
|
||||||
{
|
{
|
||||||
@@ -475,22 +463,6 @@ class ParserTests(unittest.TestCase):
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
|
||||||
"id": 924,
|
|
||||||
"number": 17,
|
|
||||||
"name": "تمرین اول",
|
|
||||||
"items": [
|
|
||||||
{
|
|
||||||
"activity_id": 5201,
|
|
||||||
"activity_position": 2,
|
|
||||||
"activity_type": "quiz",
|
|
||||||
"section_id": 924,
|
|
||||||
"section_number": 17,
|
|
||||||
"title": "تمرین اول",
|
|
||||||
"filename": "",
|
|
||||||
}
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -498,17 +470,13 @@ class ParserTests(unittest.TestCase):
|
|||||||
),
|
),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
result = _migrate_legacy_downloads(source, library, [44])
|
result = migrate_library_to_public(library, public)
|
||||||
self.assertEqual(result["courses"][0]["moved_files"], 6)
|
migrated = public / "courses" / "44" / "content" / "016--001--4954"
|
||||||
lesson = library / "courses" / "44" / "content" / "016--001--4954"
|
self.assertEqual((migrated / "files" / "15.mp4").read_bytes(), b"video")
|
||||||
exam = library / "courses" / "44" / "content" / "017--002--5201"
|
self.assertFalse((migrated / "item.json").exists())
|
||||||
self.assertEqual((lesson / "files" / "15.mp4").read_bytes(), b"video")
|
self.assertTrue((public / "courses" / "44" / "manifest.json").is_file())
|
||||||
metadata = json.loads((lesson / "artifacts" / "transcript.meta.json").read_text(encoding="utf-8"))
|
self.assertEqual(result["catalog"]["stats"]["downloaded_files"], 1)
|
||||||
self.assertEqual(metadata["source"], "../files/15.mp4")
|
self.assertFalse(library.exists())
|
||||||
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__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in new issue
Block a user