Compare commits

...
10 Commits
Author SHA1 Message Date
Meghdad 08335a4bb0 update AGENTS.md
CI / test (3.10) (push) Canceled after 0s
CI / test (3.12) (push) Canceled after 0s
CI / test (3.14) (push) Canceled after 0s
2026-11-22 18:25:10 +03:30
Meghdad 789f2e2b3a update AGENTS.md 2026-11-22 18:20:25 +03:30
Meghdad 31e8af6cf4 add AGENTS.md 2026-11-22 18:07:26 +03:30
Meghdad 45392c14b9 skip file bodies during Moodle activity scans 2026-11-22 17:57:04 +03:30
Meghdad 9d277383ac fix: show quizzes without local artifacts in library exam filters
Classify quizzes as assessments during online and offline scans,
support legacy quiz entries in the Exams filter, and add regression tests.
2026-10-29 17:00:53 +03:30
Meghdad 3e37df980c fix: restore Ravin login and scanning compatibility
- Fall back to Chromium when Firefox/Zen SSO fails
- Restore saved browser sessions and follow login tabs
- Validate LMS responses before saving scan results
- Preserve local exams when linked quizzes are hidden
- Add regression tests and bump version to 0.16.3
2026-10-08 02:19:26 +03:30
Meghdad ff467ab2ea fix: install dependencies and Zsh before running CI tests 2026-10-01 04:36:32 +03:30
Meghdad f1217f8864 feat: add Bash and Zsh completion with persistent shell setup 2026-10-01 04:32:53 +03:30
Meghdad 0f000a8912 feat: generate Vazirmatn course summary PDFs and add Library study-guide cards 2026-10-01 04:04:13 +03:30
Meghdad 7223b25241 feat(cli): add final-exam and sync-public commands 2026-09-27 06:41:41 +03:30
31 changed files with 1721 additions and 85 deletions

No files matched your search

+8 -1
View File
@@ -25,6 +25,14 @@ jobs:
with: with:
python-version: ${{ matrix.python-version }} python-version: ${{ matrix.python-version }}
- name: Install package and dependencies
run: python -m pip install .
- name: Install shells for completion tests
run: |
sudo apt-get update
sudo apt-get install -y zsh
- name: Run tests - name: Run tests
run: python -m unittest discover -s tests -v run: python -m unittest discover -s tests -v
@@ -40,7 +48,6 @@ jobs:
- name: Verify package installation - name: Verify package installation
run: | run: |
python -m pip install .
ravin --version ravin --version
ravin transcribe --help ravin transcribe --help
ravin summarize --help ravin summarize --help
+57
View File
@@ -0,0 +1,57 @@
# Repository Guidelines
## Project Structure
Ravin is a Python CLI for organizing authorized Moodle course materials. The package lives in `src/ravin/` and tests live in `tests/`.
- `cli.py` owns argument parsing, shell completion wiring, and command dispatch. `auth.py` manages credentials and browser sessions, `client.py` owns Moodle requests and file transfer, and `parsers.py` interprets Moodle HTML.
- `catalog.py` builds course records from Moodle discovery. `scan.py` reconciles them with local state, `layout.py` repairs activity bundle locations, and `paths.py` handles portable paths and artifact discovery.
- `questions.py`, `assessments.py`, and `recordings.py` manage local additions. `transcribe.py`, `summarize.py`, and `course_pdf.py` produce study artifacts. `exporter.py` and `importer.py` handle portable course ZIPs.
- The static library lives in `public/` and the local byte-range server lives in `server.py`. PDF fonts and their license are packaged in `src/ravin/fonts/`.
## Build, Test, and Development
- `python3 -m pip install -e .` installs the package for local development in a Python 3.10+ virtual environment.
- `python3 -m pip wheel --no-deps . -w dist` builds a wheel with setuptools.
- `ravin --help` checks the CLI entry point. `ravin serve --open` starts the local library and opens it in a browser.
- `python3 -m unittest discover -s tests -v` runs the test suite.
- `python3 -m compileall -q src tests` checks Python syntax, as CI does.
- Use the project virtual environment for these checks. Base CI installs the package with its declared dependencies. Real transcription requires the `transcribe` extra and FFmpeg, real summarization requires an authenticated Codex CLI, and PDF rendering requires the `pdf` extra and Playwright Chromium.
## Coding Style
Use four spaces for Python indentation, `snake_case` for modules and functions, and `PascalCase` for classes. Match nearby type annotations and keep changes compatible with Python 3.10. Keep dependencies to a minimum. CI runs tests and syntax checks without a separate formatter or linter.
## Testing Guidelines
Add or update `unittest` coverage for behavioral changes. Use `tests/test_<feature>.py` files and descriptive `test_*` methods. Use synthetic fixtures and temporary directories for course files. Bash and Zsh are needed to exercise both shell completion paths. CI tests Python 3.10, 3.12, and 3.14 without a numeric coverage threshold.
- Exercise CLI behavior through `ravin.cli.main([...])` when argument handling, output, or exit status changes. Keep progress and diagnostics on stderr when a command emits JSON on stdout.
- Pass a temporary `--public` root and isolate the working directory and environment when testing commands that can migrate a legacy `library/`, save sessions, or write `.ravin/` state. Stub external services and subprocesses. Report live LMS or tool verification separately from local test results.
## Moodle Scans and Downloads
- Keep online discovery separate from file transfer. Identify file responses by their headers and leave their bodies unread during activity inspection. Course downloads go through `ravin download`, which resumes `.part` files, checks byte ranges and available size metadata, and updates the manifests after successful transfers.
- Treat exhausted network retries as scan failures. Preserve the last successful manifests and distinguish connectivity failures from expired sessions before triggering browser authentication. Exercise the scan entry point with synthetic HTTP responses, including the failure path.
- Keep offline scan, artifact generation, and local question and recording imports independent of LMS authentication. An offline scan refreshes local state from existing manifests and preserves the last remote scan timestamp.
## Manifests and Portable Course Data
- Treat `courses/catalog.json` and `courses/<id>/manifest.json` under the public root as a shared contract for the CLI, library UI, and course ZIPs. Keep changes compatible with older manifests. Generate local URLs with the existing path helpers so they remain relative to the public root and work with spaces and Persian filenames.
- Use the existing atomic writers and manifest lock for manifest and layout mutations. Reconcile Moodle bundles by stable activity ID when section or position changes their directory key. Preserve files, partials, artifacts, and archived versions when repairing bundles or migrating the legacy layout.
- Preserve local assessment declarations and questions when Moodle hides or removes a linked quiz. Moodle quizzes should remain visible in the Exams filter even before local attachments or questions exist. Refresh derived manifest state through the existing reconciliation path after local changes.
- Preserve portable artifact metadata and freshness checks across import and sync, including filesystem timestamp rounding. Keep batch dry runs read-only and preserve completed work on interruption. Pass transcript content to Codex as untrusted input through stdin in an isolated workspace.
- Keep ZIP validation and staging before the merge, followed by offline reconciliation. Exports omit videos by default and skip partial files. For changes to SSH sync behavior, check both `ravin sync-public` and `sync-public.sh`, which exclude video files and video partials and enable remote deletion only with `--delete`.
## Release Checks
- For fixes or features shipped to users, follow the [release checklist](CONTRIBUTING.md#release-checklist). Keep the versions in `pyproject.toml` and `src/ravin/constants.py` in sync, add a dated entry to `CHANGELOG.md`, and verify `ravin --version` from the project virtual environment after installation. Documentation-only changes to contributor guidance do not require a release bump.
- Update the README when command usage or user-visible behavior changes. When changing a shared JavaScript or CSS file, update that asset's cache key in both `public/index.html` and `public/course.html`.
## Commits and Pull Requests
Prefer the common history patterns `feat: ...`, `fix: ...`, and scoped forms such as `fix(scan): ...`. Use a short, imperative summary. Describe the problem, approach, and test coverage in the PR. Link related issues and include screenshots for visible library changes when helpful.
## Private Data
Keep `.env`, browser profiles, cookies, credentials, private LMS responses, and downloaded course files out of version control and issue reports. Treat `.ravin/`, `public/courses/`, and `public/exports/` as private generated data. Keep credentials, session tokens, protected download URLs, and machine-specific absolute paths out of generated manifests. Point the static server at the public root and treat its course data and export ZIPs as private when serving or syncing it.
+28
View File
@@ -2,6 +2,34 @@
All notable changes to this project will be documented here. All notable changes to this project will be documented here.
## 0.16.4 - 2026-11-22
- Discover Moodle resources that redirect to a download by reading their response headers. Use the advertised filename, media type, and size when available.
- Retry interrupted page reads and report persistent network failures before publishing an incomplete scan or attempting a browser-session refresh.
- Show Moodle quizzes in the library's Exams filter before local questions or attachments are added, including quizzes in older manifests.
## 0.16.3 - 2026-10-08
- Recover from Ravin single-sign-on rejecting Firefox/Zen keys by transferring the authorized portal session to a persistent Chromium browser.
- Reuse the successful Chromium profile on subsequent logins, without repeating the failed Firefox transfer.
- Include Playwright with the base installation so Chromium does not depend on a downloadable ChromeDriver.
- Preserve linked local exams and their artifacts when Moodle hides or removes the linked quiz; reconnect when it reappears.
- Verify the installed login command against the live LMS and scan all enrolled courses.
## 0.16.2 - 2026-10-08
- Reuse an authenticated persistent Moodle browser profile before launching portal single sign-on.
- Activate the portal's actual course link once, preserving normal browser navigation and event handlers.
- Follow newly opened login tabs and report invalid sign-in keys without replaying the transfer.
- Keep credential submission limited to the configured login and Moodle origins.
## 0.16.1 - 2026-10-08
- Recognize authenticated Moodle sessions in the updated Ravin theme without a static logout link.
- Follow Moodle launch links inside closed portal dropdowns and wait for manual CAPTCHA login.
- Reject guest sessions, malformed course-list responses, expired course/activity pages, and unrecognized course layouts before writing scan results.
- Fix error reporting for rejected web logins.
## 0.16.0 - 2026-08-30 ## 0.16.0 - 2026-08-30
- Treat Moodle activity IDs as stable local bundle identities while retaining sortable `SECTION--POSITION--ID` paths. - Treat Moodle activity IDs as stable local bundle identities while retaining sortable `SECTION--POSITION--ID` paths.
+6
View File
@@ -17,3 +17,9 @@ Contributions are welcome. Keep changes focused, dependency-free where practical
5. Open a pull request describing the problem, approach, and test coverage. 5. Open a pull request describing the problem, approach, and test coverage.
Tests must use synthetic data. Do not include real course content, account identifiers, session values, or credentials in fixtures or issue reports. Tests must use synthetic data. Do not include real course content, account identifiers, session values, or credentials in fixtures or issue reports.
## Release checklist
1. Update the version in `pyproject.toml` and `src/ravin/constants.py`.
2. Add a dated release entry to `CHANGELOG.md`.
3. Install the package and check that `ravin --version` reports the new version.
+93 -4
View File
@@ -23,7 +23,37 @@ From the repository root:
python3 -m pip install . python3 -m pip install .
``` ```
This installs the `ravin` command and its browser automation dependency. The equivalent module entry point is `python3 -m ravin`. This installs the `ravin` command, browser automation, and shell completion support. The equivalent module entry point is `python3 -m ravin`.
After updating the checkout, run the same install command in your active virtual environment to update an existing installation. Check the installed version with `ravin --version`.
### Shell tab completion
Install completion once for your shell:
```bash
ravin completion bash --install
```
For Zsh (the default shell on current macOS):
```zsh
ravin completion zsh --install
```
Open a new terminal afterward. The command saves a managed setup block in
`~/.bashrc` (`~/.bash_profile` on macOS) or `~/.zshrc` (honoring `ZDOTDIR`).
Running it again updates the block without duplicating it or replacing other
settings. It uses the Python environment where you ran the setup, so completion
also loads before you activate that environment. Rerun setup if you move or
replace the environment. Package installation itself does not edit shell settings.
To enable completion only in the current session, use
`eval "$(ravin completion bash)"`, or `eval "$(ravin completion zsh)"` in Zsh
with `compinit` initialized.
Press Tab to complete commands, options, choice values such as
`ravin transcribe --device`, and file paths. Completion uses the current command
definitions and does not log in or contact the LMS.
Whisper and PyTorch are large, platform-specific dependencies, so install them only on the machine that will transcribe media: Whisper and PyTorch are large, platform-specific dependencies, so install them only on the machine that will transcribe media:
@@ -53,23 +83,27 @@ Sync `public/` to an SSH host without transferring video files. Provide
your destination at runtime and preview the changes first: your destination at runtime and preview the changes first:
```bash ```bash
./sync-public.sh --dry-run \ ravin sync-public --dry-run \
--destination 'user@example-host:/path/to/project/public/' --destination 'user@example-host:/path/to/project/public/'
``` ```
Then perform the sync: Then perform the sync:
```bash ```bash
./sync-public.sh \ ravin sync-public \
--destination 'user@example-host:/path/to/project/public/' --destination 'user@example-host:/path/to/project/public/'
``` ```
You can alternatively set `SYNC_PUBLIC_DESTINATION` in your local shell. The You can alternatively set `SYNC_PUBLIC_DESTINATION` in your local shell. The
script does not remove remote files by default; pass `--delete` when an exact command does not remove remote files by default; pass `--delete` when an exact
mirror of non-video files is required. mirror of non-video files is required.
The original `./sync-public.sh` entry point remains available for compatibility.
`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. `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.
When an LMS activity redirects to a file, online scanning uses the file's response headers. Use `ravin download COURSE_ID` to transfer the file contents.
Scan only selected courses or print machine-readable results: Scan only selected courses or print machine-readable results:
```bash ```bash
@@ -87,6 +121,25 @@ ravin scan --offline
`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`. `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`.
If the account portal shows a CAPTCHA, complete the login in that browser window.
The command waits for you and does not submit the CAPTCHA form automatically.
It first checks the persistent browser's existing Moodle session. If login is
needed, it clicks the dashboard's course or **Offline class** link once (including
links in closed dropdowns), follows a newly opened login tab, and recognizes the
new Moodle theme without requiring a logout link. If the portal rejects a sign-in
key, the command does not replay that key or repeatedly launch single sign-on.
If Ravin rejects a Firefox/Zen transfer, the command switches to Chromium with the
existing authorized portal session. Later logins reuse that separate persistent
Chromium profile. Install the Chromium browser once if it is not already available:
```bash
python -m playwright install chromium
```
Logging in through Codex's internal browser does not refresh the separate session
used by this command. After a site update or rejected session, run `ravin login`
and then `ravin scan` to scan all enrolled courses.
Missing credentials are requested interactively. You can also copy [`.env.example`](.env.example) and fill it yourself: Missing credentials are requested interactively. You can also copy [`.env.example`](.env.example) and fill it yourself:
```dotenv ```dotenv
@@ -224,6 +277,12 @@ Start the interactive import wizard:
ravin questions ravin questions
``` ```
For a declared course-level final exam, use the dedicated shortcut:
```bash
ravin final-exam
```
The wizard: The wizard:
1. Lists local courses that contain exams. 1. Lists local courses that contain exams.
@@ -374,6 +433,33 @@ ravin summarize 44 --no-keep-awake
Set `CODEX_SUMMARY_MODEL` in `.env` to make a model override persistent. Leave it empty to use the model configured by Codex CLI. Set `CODEX_SUMMARY_MODEL` in `.env` to make a model override persistent. Leave it empty to use the model configured by Codex CLI.
## Course summaries PDF
Install PDF support once, then create a PDF for a course without an LMS login:
```bash
pip install 'ravin-moodle-downloader[pdf]'
python -m playwright install chromium
ravin pdf COURSE_ID
```
The command combines all non-empty local lesson summaries in chapter and lesson order,
preserving Markdown headings, lists, code, and tables. It embeds Vazirmatn Regular and
Bold and uses Chromium's Unicode shaping and bidirectional layout for Persian/Arabic
letters, Latin text, and Persian, Arabic, and Western digits. Digit characters are
preserved as written. Raw HTML and external images are disabled.
The PDF is saved to `public/courses/COURSE_ID/artifacts/summaries.fa.pdf` and linked
on the Library course card and course page immediately. Use `--public PATH` for
another library root or `--json` for machine-readable results. Re-running replaces
the PDF atomically. Scans mark its link outdated when summaries or their titles
change; re-run `ravin pdf COURSE_ID` to refresh it. Courses without summaries report
an error instead of producing an empty PDF. Only available summaries are included;
generate missing summaries with `ravin summarize COURSE_ID` first.
Bundled Vazirmatn fonts are distributed under the SIL Open Font License in
`src/ravin/fonts/OFL.txt`.
## Static learning library ## Static learning library
The web interface is already present in the tracked `public/` directory. Generate or refresh its private data, then serve it: The web interface is already present in the tracked `public/` directory. Generate or refresh its private data, then serve it:
@@ -433,13 +519,16 @@ When an older generated `library/courses.json` exists and `public/` has no manif
```text ```text
ravin login ravin login
ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH] ravin scan [COURSE_ID ...] [--offline] [--json] [--public PATH]
ravin completion [bash|zsh] [--install]
ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH] ravin download COURSE_ID [--overwrite] [--retries N] [--json] [--public PATH]
ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE] ravin transcribe [COURSE_ID ...] [--model MODEL] [--device DEVICE] [--language LANGUAGE]
ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS] ravin summarize [COURSE_ID ...] [--model MODEL] [--retries N] [--timeout SECONDS]
ravin questions [COURSE_ID] [ACTIVITY_OR_ASSESSMENT_ID] [QUESTIONS.md] [--file ATTACHMENT ...] ravin questions [COURSE_ID] [ACTIVITY_OR_ASSESSMENT_ID] [QUESTIONS.md] [--file ATTACHMENT ...]
ravin final-exam [COURSE_ID] [QUESTIONS.md] [--file ATTACHMENT ...]
ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO] ravin recording [COURSE_ID] [ACTIVITY_ID] [VIDEO]
ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH] ravin export [--output ARCHIVE.zip] [--include-videos] [--public PATH]
ravin import URL [--timeout SECONDS] [--json] [--public PATH] ravin import URL [--timeout SECONDS] [--json] [--public PATH]
ravin sync-public [--destination USER@HOST:PATH] [--dry-run] [--delete] [--public PATH]
ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH] ravin serve [--host ADDRESS] [--port PORT] [--open] [--public PATH]
``` ```
+17
View File
@@ -211,6 +211,16 @@ 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);
if (course.summary_pdf?.url) {
const pdf = document.createElement("a");
pdf.className = "guide-card-link";
pdf.href = course.summary_pdf.url;
pdf.target = "_blank";
pdf.rel = "noopener";
pdf.innerHTML = '<span class="guide-mini-icon" aria-hidden="true">▤</span><span><strong>Study guide</strong><small></small></span><span aria-hidden="true">↗</span>';
pdf.querySelector("small").textContent = `${course.summary_pdf.summary_count || 0} lesson summaries · PDF${course.summary_pdf.state === "stale" ? " · Outdated" : ""}`;
bottom.append(pdf);
}
card.append(top, title, meta, states, bottom); card.append(top, title, meta, states, bottom);
return card; return card;
} }
@@ -251,6 +261,7 @@ function resourceMatches(item) {
if (state.query && !haystack.includes(state.query)) return false; if (state.query && !haystack.includes(state.query)) return false;
if (state.filter === "all") return true; if (state.filter === "all") return true;
if (state.filter === "downloaded" || state.filter === "missing") return item.status === state.filter; if (state.filter === "downloaded" || state.filter === "missing") return item.status === state.filter;
if (state.filter === "assessment") return item.kind === "assessment" || item.activity_type === "quiz";
return item.kind === state.filter; return item.kind === state.filter;
} }
@@ -536,6 +547,12 @@ function renderCourse() {
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;
const pdf = byId("coursePdf");
pdf.hidden = !course.summary_pdf?.url;
if (course.summary_pdf?.url) {
pdf.href = course.summary_pdf.url;
setText("guideMeta", `${course.summary_pdf.summary_count || 0} lesson summaries · Persian · PDF${course.summary_pdf.state === "stale" ? " · Update available: regenerate your guide" : ""}`);
}
byId("resourceSearch").addEventListener("input", (event) => { byId("resourceSearch").addEventListener("input", (event) => {
state.query = normalized(event.target.value); state.query = normalized(event.target.value);
renderResources(); renderResources();
+25
View File
@@ -168,6 +168,31 @@ main {
font-size: clamp(1rem, 2vw, 1.18rem); font-size: clamp(1rem, 2vw, 1.18rem);
} }
#coursePdf[hidden] { display: none; }
.study-guide { display:flex; align-items:center; gap:28px; position:relative; overflow:hidden; margin-top:24px; padding:26px 32px; border:1px solid var(--line); border-radius:24px; background:linear-gradient(115deg, var(--surface), color-mix(in srgb, var(--accent) 13%, var(--surface))); text-decoration:none; transition:box-shadow .2s, border-color .2s; }
.study-guide:hover { border-color:var(--accent-strong); box-shadow:var(--shadow); }
.study-guide:focus-visible, .guide-card-link:focus-visible { outline:3px solid var(--blue); outline-offset:4px; }
.guide-cover { flex-shrink:0; display:flex; flex-direction:column; justify-content:space-between; width:88px; height:116px; padding:14px 12px 10px 17px; border-radius:3px 9px 9px 3px; background:#1c5166; color:#f5f3ec; box-shadow:-4px 0 0 #123a4b, 3px 3px 0 #dedfd4, 7px 10px 18px #17212620; transform:rotate(-6deg); transition:transform .2s; border-left:2px solid #ffffff25; }
.study-guide:hover .guide-cover { transform:rotate(-2deg) translateY(-2px); }
.guide-cover-label { font-size:11px; line-height:1.3; font-weight:850; letter-spacing:.08em; }
.guide-cover-lines { width:42px; height:16px; background:repeating-linear-gradient(to bottom, #d8f26a 0 2px, transparent 2px 7px); }
.guide-cover-format { align-self:flex-end; font-size:9px; font-weight:800; letter-spacing:.12em; color:#d8f26a; }
.guide-copy { display:grid; gap:6px; flex:1; min-width:0; }
.guide-eyebrow { color:var(--blue); font-size:.65rem; font-weight:850; letter-spacing:.14em; }
.guide-copy strong { font-size:clamp(1.3rem, 3vw, 1.8rem); line-height:1.25; letter-spacing:-.04em; }
.guide-description { color:var(--muted); font-size:.88rem; }
.guide-meta { color:var(--muted); font-size:.73rem; margin-top:5px; }
.guide-action { display:flex; gap:20px; align-items:center; padding:12px 18px; border-radius:12px; background:var(--ink); color:var(--paper); font-size:.8rem; font-weight:750; white-space:nowrap; }
.guide-card-link { display:flex; align-items:center; gap:12px; margin-top:18px; padding:12px; border:1px solid var(--line); border-radius:12px; text-decoration:none; background:color-mix(in srgb, var(--accent) 10%, var(--surface)); }
.guide-card-link > span:nth-child(2) { flex:1; display:grid; gap:2px; }
.guide-card-link strong { font-size:.8rem; }
.guide-card-link small { font-size:.68rem; color:var(--muted); }
.guide-mini-icon { display:grid; place-items:center; width:32px; height:38px; border-radius:5px; background:var(--blue-soft); color:var(--blue); font-size:22px; }
@media(max-width:700px) { .study-guide { gap:20px; padding:22px; flex-wrap:wrap; } .guide-action { margin-left:108px; } }
@media(max-width:420px) { .guide-cover { width:64px; height:94px; padding:10px; } .guide-cover-label { font-size:9px; } .guide-description { font-size:.78rem; } .guide-action { margin-left:84px; padding:10px 12px; } }
@media(prefers-reduced-motion:reduce) { .guide-cover, .study-guide { transition:none; } }
.hero-source { .hero-source {
display: inline-flex; display: inline-flex;
margin-top: 22px; margin-top: 22px;
+8 -2
View File
@@ -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="assets/styles.css"> <link rel="stylesheet" href="assets/styles.css?v=course-pdf-3">
<script src="assets/app.js" defer></script> <script src="assets/app.js?v=0.16.4" defer></script>
</head> </head>
<body data-page="course"> <body data-page="course">
<header class="topbar"> <header class="topbar">
@@ -42,6 +42,12 @@
</div> </div>
</section> </section>
<a class="study-guide" id="coursePdf" hidden target="_blank" rel="noopener" aria-labelledby="guideTitle">
<span class="guide-cover" aria-hidden="true"><span class="guide-cover-label">COURSE<br>NOTES</span><span class="guide-cover-lines"></span><span class="guide-cover-format">PDF</span></span>
<span class="guide-copy"><span class="guide-eyebrow">YOUR STUDY COMPANION</span><strong id="guideTitle">The course, collected.</strong><span class="guide-description">Your lesson summaries in one beautifully readable guide.</span><span class="guide-meta" id="guideMeta"></span></span>
<span class="guide-action">Open study guide <span aria-hidden="true">↗</span></span>
</a>
<section class="course-toolbar" aria-label="Resource controls"> <section class="course-toolbar" aria-label="Resource controls">
<label class="search-box resource-search"> <label class="search-box resource-search">
<span aria-hidden="true">⌕</span> <span aria-hidden="true">⌕</span>
+2 -2
View File
@@ -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="assets/styles.css"> <link rel="stylesheet" href="assets/styles.css?v=course-pdf-3">
<script src="assets/app.js" defer></script> <script src="assets/app.js?v=0.16.4" defer></script>
</head> </head>
<body data-page="index"> <body data-page="index">
<header class="topbar"> <header class="topbar">
+6 -2
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "ravin-moodle-downloader" name = "ravin-moodle-downloader"
version = "0.16.0" version = "0.16.4"
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials" description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
@@ -24,9 +24,10 @@ classifiers = [
"Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.14",
"Topic :: Education", "Topic :: Education",
] ]
dependencies = ["selenium>=4.46,<5"] dependencies = ["selenium>=4.46,<5", "argcomplete>=3.6,<4", "playwright>=1.50,<2"]
[project.optional-dependencies] [project.optional-dependencies]
pdf = ["playwright>=1.50,<2", "markdown-it-py>=3,<5"]
transcribe = [ transcribe = [
"openai-whisper==20250625", "openai-whisper==20250625",
"torch==2.13.0", "torch==2.13.0",
@@ -40,3 +41,6 @@ package-dir = {"" = "src"}
[tool.setuptools.packages.find] [tool.setuptools.packages.find]
where = ["src"] where = ["src"]
[tool.setuptools.package-data]
ravin = ["fonts/*.ttf", "fonts/OFL.txt"]
+10 -8
View File
@@ -2,6 +2,7 @@
from __future__ import annotations from __future__ import annotations
import mimetypes
import re import re
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -99,6 +100,8 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]:
raise MoodleError( raise MoodleError(
f"invalid activity ID for assessment {assessment['id']}: {activity_id!r}" f"invalid activity ID for assessment {assessment['id']}: {activity_id!r}"
) from exc ) from exc
if resolved_activity_id <= 0:
raise MoodleError(f"invalid activity ID for assessment {assessment['id']}: {activity_id!r}")
for section in sections: for section in sections:
for item in section.get("items", []): for item in section.get("items", []):
if int(item.get("activity_id") or 0) == resolved_activity_id: if int(item.get("activity_id") or 0) == resolved_activity_id:
@@ -106,11 +109,9 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]:
break break
if linked is not None: if linked is not None:
break break
if linked is None: # A linked quiz can disappear from the visible LMS tree. Its local
raise MoodleError( # assessment and stable artifact bundle must survive that scan;
f"assessment {assessment['id']} links to missing activity {resolved_activity_id} " # retain the desired link so it reconnects if the quiz reappears.
f"in course {course_id}"
)
common = { common = {
"assessment_id": assessment["id"], "assessment_id": assessment["id"],
@@ -134,13 +135,14 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]:
"section_id": None, "section_id": None,
"section_number": None, "section_number": None,
"activity_id": None, "activity_id": None,
"linked_activity_id": int(activity_id) if activity_id is not None else None,
"activity_position": position, "activity_position": position,
"activity_type": "assessment", "activity_type": "assessment",
"title": assessment["title"], "title": assessment["title"],
"description": str(assessment.get("description") or ""), "description": str(assessment.get("description") or ""),
"filename": "", "filename": str(assessment.get("filename") or ""),
"extension": "", "extension": Path(str(assessment.get("filename") or "")).suffix.lstrip(".").casefold(),
"mimetype": "", "mimetype": mimetypes.guess_type(str(assessment.get("filename") or ""))[0] or "",
"source_url": course.get("source_url"), "source_url": course.get("source_url"),
"lms_completed": None, "lms_completed": None,
**common, **common,
+231 -32
View File
@@ -14,7 +14,11 @@ from pathlib import Path
from .client import MoodleClient from .client import MoodleClient
from .constants import DEFAULT_RAVIN_LOGIN_URL, ENV_KEYS from .constants import DEFAULT_RAVIN_LOGIN_URL, ENV_KEYS
from .models import MoodleError from .models import MoodleConnectionError, MoodleError
class _InvalidSSOKey(MoodleError):
"""The portal transfer failed before establishing a Moodle session."""
def _env_value(args: argparse.Namespace, key: str) -> str: def _env_value(args: argparse.Namespace, key: str) -> str:
@@ -163,6 +167,169 @@ def _browser_login_url(args: argparse.Namespace) -> str:
return urllib.parse.urljoin(args.site.rstrip("/") + "/", "my/courses.php") return urllib.parse.urljoin(args.site.rstrip("/") + "/", "my/courses.php")
def _authenticated_browser_session(driver, site: str) -> tuple[str, str] | None:
"""Capture only a signed-in Moodle page on the configured site."""
location = urllib.parse.urlsplit(driver.current_url)
target = urllib.parse.urlsplit(site)
if (location.scheme, location.netloc.casefold()) != (target.scheme, target.netloc.casefold()):
return None
if "/login/" in location.path or location.path.endswith("/auth/userkey/login.php"):
return None
logged_in = driver.execute_script(
"""return Boolean(
window.M && M.cfg && Number(M.cfg.userId) > 0 && M.cfg.sesskey
);"""
)
if not logged_in:
return None
cookie_header = "; ".join(
f"{cookie['name']}={cookie['value']}"
for cookie in driver.get_cookies()
if cookie.get("name") and cookie.get("value")
)
if not cookie_header:
raise MoodleError("browser login succeeded, but no site cookies were available")
return str(driver.execute_script("return navigator.userAgent;")), cookie_header
def _select_login_tab(driver, known_handles: set[str]) -> set[str]:
"""Follow a newly opened login tab, or recover when the active tab closes."""
from selenium.common.exceptions import NoSuchWindowException
handles = driver.window_handles
if not handles:
raise MoodleError("the authentication browser was closed before login finished")
new_handles = [handle for handle in handles if handle not in known_handles]
if new_handles:
driver.switch_to.window(new_handles[-1])
else:
try:
current = driver.current_window_handle
except NoSuchWindowException:
current = None
if current not in handles:
driver.switch_to.window(handles[-1])
return set(handles)
def _launch_moodle_from_portal(driver, login_url: str, by) -> bool:
"""Activate the actual portal link so browser navigation preserves its context."""
links = driver.find_elements(by.CSS_SELECTOR, 'a[href*="/moodle/login_student_user/"]')
candidates = [
link for link in links
if urllib.parse.urlsplit(link.get_attribute("href") or "").hostname
== urllib.parse.urlsplit(login_url).hostname
]
if not candidates:
return False
visible = next((link for link in candidates if link.is_displayed()), None)
if visible is not None:
visible.click()
else:
# Closed dropdowns still contain the real link and its event handlers.
driver.execute_script("arguments[0].click();", candidates[0])
return True
def _capture_chromium_session(args: argparse.Namespace, portal_cookies=()) -> tuple[str, str]:
"""Use a persistent Chromium context when Firefox's portal transfer fails."""
try:
from playwright.sync_api import sync_playwright, Error as PlaywrightError
except ImportError as exc:
raise MoodleError("Chromium login requires Playwright; reinstall the updated package") from exc
profile = args.browser_profile.expanduser().resolve() / "chromium"
profile.mkdir(parents=True, exist_ok=True, mode=0o700)
deadline = time.monotonic() + max(args.login_timeout, 30)
login_url = _browser_login_url(args)
target = urllib.parse.urlsplit(args.site)
saved = _browser_session_values(args)
# A browser restart may discard session-only cookies. Rehydrate only a
# previous Chromium session, using its matching User-Agent.
chromium_saved = saved if saved and "Chrome/" in saved[0] and not portal_cookies else None
with sync_playwright() as playwright:
if not Path(playwright.chromium.executable_path).is_file():
raise MoodleError("Chromium is not installed. Run `python -m playwright install chromium` and retry login")
try:
context = playwright.chromium.launch_persistent_context(
str(profile), headless=False,
**({"user_agent": chromium_saved[0]} if chromium_saved else {}),
)
try:
if chromium_saved:
context.add_cookies([
{"name": name.strip(), "value": value, "url": args.site.rstrip("/") + "/", "secure": target.scheme == "https"}
for pair in chromium_saved[1].split(";")
for name, separator, value in [pair.strip().partition("=")]
if separator and name.strip()
])
if portal_cookies:
# Keep the authorized portal session when changing engines.
# Analytics cookies are unnecessary and can have invalid flags.
cookies = []
for cookie in portal_cookies:
if cookie["name"].startswith(("_ga", "_gid", "_gat")):
continue
copied = {key: cookie[key] for key in ("name", "value", "domain", "path")}
copied.update(secure=cookie.get("secure", False), httpOnly=cookie.get("httpOnly", False))
if cookie.get("expiry"):
copied["expires"] = cookie["expiry"]
cookies.append(copied)
context.add_cookies(cookies)
page = context.pages[0] if context.pages else context.new_page()
page.goto(args.site.rstrip("/") + "/my/courses.php")
launched = False
opened_portal = False
known_pages = set(context.pages)
while time.monotonic() < deadline:
pages = [item for item in context.pages if not item.is_closed()]
if not pages:
raise MoodleError("the authentication browser was closed before login finished")
new_pages = [item for item in pages if item not in known_pages]
if new_pages or page.is_closed():
page = (new_pages or pages)[-1]
known_pages = set(pages)
location = urllib.parse.urlsplit(page.url)
if (location.scheme, location.netloc.casefold()) == (target.scheme, target.netloc.casefold()):
if page.locator('a[href*="/error/moodle/invalidkey"]').count():
raise _InvalidSSOKey("Moodle rejected the portal sign-in key in Chromium too; no new session was saved")
if "/login/" not in location.path and page.evaluate(
"Boolean(window.M && M.cfg && Number(M.cfg.userId) > 0 && M.cfg.sesskey)"
):
cookie_header = "; ".join(
f"{cookie['name']}={cookie['value']}" for cookie in context.cookies(page.url)
if cookie.get("name") and cookie.get("value")
)
if not cookie_header:
raise MoodleError("Chromium login succeeded, but no cookies were available")
return page.evaluate("navigator.userAgent"), cookie_header
if not opened_portal:
page.goto(login_url)
opened_portal = True
continue
if not launched and location.hostname == urllib.parse.urlsplit(login_url).hostname:
links = page.locator('a[href*="/moodle/login_student_user/"]').all()
links = [link for link in links if urllib.parse.urlsplit(
urllib.parse.urljoin(page.url, link.get_attribute("href") or "")
).hostname == location.hostname]
if links:
visible = next((link for link in links if link.is_visible()), None)
if visible is not None:
visible.click()
else:
links[0].evaluate("element => element.click()")
launched = True
print("Opening the Moodle course portal in Chromium...", file=sys.stderr)
continue
time.sleep(1)
raise MoodleError(f"Chromium login did not finish within {max(args.login_timeout, 30)} seconds")
finally:
context.close()
except PlaywrightError as exc:
# Browser exceptions can embed the one-time login URL.
raise MoodleError("Chromium authentication could not complete; check the browser or retry login") from None
def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]: def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]:
"""Open an installed browser through Selenium and capture its authenticated session.""" """Open an installed browser through Selenium and capture its authenticated session."""
try: try:
@@ -189,6 +356,10 @@ def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]:
except OSError: except OSError:
pass pass
if not args.browser_executable and (profile / "chromium" / "Local State").is_file():
print("Opening the previously verified Chromium login profile...", file=sys.stderr)
return _capture_chromium_session(args)
browser_name = executable.name.casefold() browser_name = executable.name.casefold()
try: try:
if "firefox" in browser_name or "zen" in browser_name: if "firefox" in browser_name or "zen" in browser_name:
@@ -223,55 +394,76 @@ def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]:
print(f"Opening {executable.name} for LMS authentication...", file=sys.stderr) print(f"Opening {executable.name} for LMS authentication...", file=sys.stderr)
print("Complete Cloudflare or LMS login in that window if requested.", file=sys.stderr) print("Complete Cloudflare or LMS login in that window if requested.", file=sys.stderr)
try: try:
# A persistent profile may already hold a valid Moodle session. Reuse it
# before issuing another single-sign-on launch from the account portal.
driver.get(args.site.rstrip("/") + "/my/courses.php")
session = _authenticated_browser_session(driver, args.site)
if session is not None:
return session
driver.get(login_url) driver.get(login_url)
known_handles = set(driver.window_handles)
launched_moodle = False
submitted_credentials = False submitted_credentials = False
credential_attempts = 0 credential_attempts = 0
captcha_notice_shown = False
last_location = "" last_location = ""
while time.monotonic() < deadline: while time.monotonic() < deadline:
known_handles = _select_login_tab(driver, known_handles)
current_location = urllib.parse.urlsplit(driver.current_url)._replace(query="", fragment="").geturl() current_location = urllib.parse.urlsplit(driver.current_url)._replace(query="", fragment="").geturl()
if current_location != last_location: if current_location != last_location:
print(f"Browser is at {current_location}", file=sys.stderr) print(f"Browser is at {current_location}", file=sys.stderr)
last_location = current_location last_location = current_location
try: try:
logged_in = bool( session = _authenticated_browser_session(driver, args.site)
driver.execute_script(
"""return Boolean(
window.M && M.cfg && Number(M.cfg.userId) > 0 &&
document.querySelector('a[href*="/login/logout.php"]')
);"""
)
)
except WebDriverException: except WebDriverException:
logged_in = False session = None
if logged_in: if session is not None:
cookies = driver.get_cookies() return session
user_agent = str(driver.execute_script("return navigator.userAgent;"))
cookie_header = "; ".join( if driver.find_elements(By.CSS_SELECTOR, 'a[href*="/error/moodle/invalidkey"]'):
f"{cookie['name']}={cookie['value']}" raise _InvalidSSOKey(
for cookie in cookies "Moodle rejected the portal's sign-in key (invalidkey). "
if cookie.get("name") and cookie.get("value") "The browser did not establish a session; no new session was saved. "
"The account portal's single-sign-on may need attention."
) )
if not cookie_header:
raise MoodleError("browser login succeeded, but no site cookies were available") if launched_moodle:
return user_agent, cookie_header # A click may open its destination asynchronously. Do not issue
# another launch or submit the portal form during that transfer.
time.sleep(1)
continue
location = urllib.parse.urlsplit(driver.current_url)
allowed_origins = {
(parsed.scheme, parsed.netloc.casefold())
for parsed in (urllib.parse.urlsplit(args.site), urllib.parse.urlsplit(login_url))
}
if (location.scheme, location.netloc.casefold()) not in allowed_origins:
time.sleep(1)
continue
# Ravin's account portal owns the login. Its Moodle launch link creates # Ravin's account portal owns the login. Its Moodle launch link creates
# the session on training.ravinacademy.com and redirects there. # the session on training.ravinacademy.com and redirects there.
launch_links = driver.find_elements( if not launched_moodle and _launch_moodle_from_portal(driver, login_url, By):
By.CSS_SELECTOR,
'a[href*="/moodle/login_student_user/"]',
)
launch_urls = [
element.get_attribute("href")
for element in launch_links
if element.is_displayed() and element.get_attribute("href")
]
if launch_urls:
print("LMS login accepted; opening the Moodle course portal.", file=sys.stderr) print("LMS login accepted; opening the Moodle course portal.", file=sys.stderr)
driver.get(launch_urls[0]) launched_moodle = True
submitted_credentials = False submitted_credentials = False
continue continue
# The portal now requires a human-entered CAPTCHA. Leave the form
# untouched rather than submitting incomplete credentials repeatedly.
captcha_controls = driver.find_elements(
By.CSS_SELECTOR,
'input[name="captcha_1"], input[name="g-recaptcha-response"], '
'.g-recaptcha, .h-captcha, iframe[src*="recaptcha"], iframe[src*="hcaptcha"]',
)
if any(element.is_displayed() for element in captcha_controls):
if not captcha_notice_shown:
print("CAPTCHA detected; complete login in the browser window.", file=sys.stderr)
captcha_notice_shown = True
time.sleep(1)
continue
if submitted_credentials: if submitted_credentials:
error_elements = driver.find_elements( error_elements = driver.find_elements(
By.CSS_SELECTOR, By.CSS_SELECTOR,
@@ -364,6 +556,13 @@ def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]:
print("Submitted the stored LMS credentials.", file=sys.stderr) print("Submitted the stored LMS credentials.", file=sys.stderr)
time.sleep(1) time.sleep(1)
raise MoodleError(f"browser login did not finish within {max(args.login_timeout, 30)} seconds") raise MoodleError(f"browser login did not finish within {max(args.login_timeout, 30)} seconds")
except _InvalidSSOKey:
if not ("firefox" in browser_name or "zen" in browser_name):
raise
print("Firefox/Zen rejected the portal transfer; switching to Chromium.", file=sys.stderr)
driver.get(login_url)
portal_cookies = driver.get_cookies()
return _capture_chromium_session(args, portal_cookies)
except WebDriverException as exc: except WebDriverException as exc:
raise MoodleError(f"browser authentication failed: {exc}") from exc raise MoodleError(f"browser authentication failed: {exc}") from exc
finally: finally:
@@ -389,7 +588,7 @@ def _authenticate_browser_session(
try: try:
mode = client.authenticate() mode = client.authenticate()
except MoodleError as exc: except MoodleError as exc:
if not from_saved: if not from_saved or isinstance(exc, MoodleConnectionError):
raise raise
print(f"Saved browser session is no longer valid ({exc}).", file=sys.stderr) print(f"Saved browser session is no longer valid ({exc}).", file=sys.stderr)
if args.manual_session: if args.manual_session:
+1 -1
View File
@@ -257,7 +257,7 @@ def _build_library_catalog(
current_path = local_directory / str(current_relative) if local_directory and current_relative else None current_path = local_directory / str(current_relative) if local_directory and current_relative else None
local_path = current_path if current_path and current_path.is_file() else (local_files[0] if local_files else None) local_path = current_path if current_path and current_path.is_file() else (local_files[0] if local_files else None)
local_bytes = local_path.stat().st_size if local_path else 0 local_bytes = local_path.stat().st_size if local_path else 0
if activity_type == "quiz" and local_activity: if activity_type == "quiz":
local_kind = "assessment" local_kind = "assessment"
elif activity_type in LIVE_CLASS_MODULES and local_path: elif activity_type in LIVE_CLASS_MODULES and local_path:
local_kind = _media_kind(local_path.name, mimetypes.guess_type(local_path.name)[0] or "") local_kind = _media_kind(local_path.name, mimetypes.guess_type(local_path.name)[0] or "")
+93 -7
View File
@@ -8,6 +8,8 @@ import os
import sys import sys
from pathlib import Path from pathlib import Path
import argcomplete
from .auth import ( from .auth import (
_authenticate_browser_session, _authenticate_browser_session,
_browser_session_values, _browser_session_values,
@@ -26,6 +28,7 @@ from .recordings import format_recording_result, import_recording, recording_wiz
from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state from .scan import format_scan, scan_offline, scan_output, scan_remote, update_download_state
from .server import _serve_library from .server import _serve_library
from .summarize import SummaryOptions, format_summary_result, summarize_courses from .summarize import SummaryOptions, format_summary_result, summarize_courses
from .sync_public import sync_public
from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_courses from .transcribe import TranscriptionOptions, format_transcription_result, transcribe_courses
@@ -67,8 +70,17 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--login-timeout", type=int, default=600, help="interactive login timeout") parser.add_argument("--login-timeout", type=int, default=600, help="interactive login timeout")
subparsers = parser.add_subparsers(dest="command", required=True) subparsers = parser.add_subparsers(dest="command", required=True)
completion_parser = subparsers.add_parser("completion", help="print shell tab-completion setup")
completion_parser.add_argument("shell", choices=("bash", "zsh"), nargs="?", default="bash")
completion_parser.add_argument("--install", action="store_true", help="save setup in your shell startup file")
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")
pdf_parser = subparsers.add_parser("pdf", help="create a course PDF from its local summaries")
pdf_parser.add_argument("course_id", type=int)
pdf_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
pdf_parser.add_argument("--json", action="store_true", help="print PDF details as JSON")
scan_parser = subparsers.add_parser("scan", help="scan LMS courses and reconcile local learning state") 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("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("--public", type=Path, default=Path("public"), help="public web root")
@@ -167,6 +179,32 @@ def build_parser() -> argparse.ArgumentParser:
questions_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root") questions_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
questions_parser.add_argument("--json", action="store_true", help="print imported paths as JSON") questions_parser.add_argument("--json", action="store_true", help="print imported paths as JSON")
final_exam_parser = subparsers.add_parser(
"final-exam",
help="import questions and attachments for a declared final exam",
description=(
"Import questions and optional attachments for the course assessment named final-exam; "
"all positional values are optional."
),
)
final_exam_parser.add_argument("course_id", nargs="?", type=int, help="course containing the final exam")
final_exam_parser.add_argument(
"questions",
nargs="?",
type=Path,
help="UTF-8 Markdown final-exam questions and answers",
)
final_exam_parser.add_argument(
"--file",
dest="files",
type=Path,
action="append",
default=[],
help="optional original exam attachment; repeat for multiple files",
)
final_exam_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
final_exam_parser.add_argument("--json", action="store_true", help="print imported paths as JSON")
recording_parser = subparsers.add_parser( recording_parser = subparsers.add_parser(
"recording", "recording",
aliases=["recordings"], aliases=["recordings"],
@@ -212,6 +250,24 @@ def build_parser() -> argparse.ArgumentParser:
) )
import_parser.add_argument("--json", action="store_true", help="print import and scan details as JSON") import_parser.add_argument("--json", action="store_true", help="print import and scan details as JSON")
sync_parser = subparsers.add_parser(
"sync-public",
help="sync the public library to an SSH destination without videos",
description="Sync public course data with rsync while excluding current and partial video files.",
)
sync_parser.add_argument(
"-d",
"--destination",
help="rsync SSH destination (USER@HOST:PATH); defaults to SYNC_PUBLIC_DESTINATION",
)
sync_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
sync_parser.add_argument("-n", "--dry-run", action="store_true", help="show changes without transferring files")
sync_parser.add_argument(
"--delete",
action="store_true",
help="delete remote non-video files that are missing locally",
)
serve_parser = subparsers.add_parser("serve", help="serve the public learning library locally") 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") serve_parser.add_argument("--public", type=Path, default=Path("public"), help="public web root")
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address") serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address")
@@ -252,16 +308,45 @@ def _authenticate(args: argparse.Namespace) -> tuple[MoodleClient, str]:
def main(argv: list[str] | None = None) -> int: def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv) parser = build_parser()
argcomplete.autocomplete(parser)
args = parser.parse_args(argv)
if args.command == "completion":
if args.install:
from .completion import install_completion
try: try:
startup = install_completion(args.shell)
except (OSError, ValueError) as exc:
print(f"Could not install completion: {exc}", file=sys.stderr)
return 1
print(f"Installed {args.shell} completion in {startup}. Open a new shell to enable it.")
return 0
print(argcomplete.shellcode(["ravin"], shell=args.shell))
return 0
try:
if args.command == "pdf":
from .course_pdf import create_course_pdf
result = create_course_pdf(args.public, args.course_id)
print(json.dumps(result, ensure_ascii=False, indent=2) if args.json else
f"Created PDF from {result['summary_count']} summaries: {result['path']}")
return 0
if args.command == "serve": if args.command == "serve":
_serve_library(args.public, args.host, args.port, args.open) _serve_library(args.public, args.host, args.port, args.open)
return 0 return 0
if args.command == "sync-public":
return sync_public(
args.public,
args.destination,
dry_run=args.dry_run,
delete=args.delete,
)
public = getattr(args, "public", Path("public")).expanduser().resolve() public = getattr(args, "public", Path("public")).expanduser().resolve()
if args.command in { if args.command in {
"scan", "download", "transcribe", "summarize", "questions", "recording", "recordings", "export", "scan", "download", "transcribe", "summarize", "questions", "final-exam", "recording",
"import", "recordings", "export", "import",
}: }:
_maybe_migrate(public) _maybe_migrate(public)
@@ -353,18 +438,19 @@ def main(argv: list[str] | None = None) -> int:
) )
return result.exit_code return result.exit_code
if args.command == "questions": if args.command in {"questions", "final-exam"}:
interactive = args.course_id is None or args.activity_id is None or args.questions is None activity_id = "final-exam" if args.command == "final-exam" else args.activity_id
interactive = args.course_id is None or activity_id is None or args.questions is None
course_id, activity_id, questions_path, attachment_paths = questions_wizard( course_id, activity_id, questions_path, attachment_paths = questions_wizard(
public, public,
args.course_id, args.course_id,
args.activity_id, activity_id,
args.questions, args.questions,
tuple(args.files), tuple(args.files),
prompt_for_attachment=interactive, prompt_for_attachment=interactive,
) if interactive else ( ) if interactive else (
args.course_id, args.course_id,
args.activity_id, activity_id,
args.questions, args.questions,
tuple(args.files), tuple(args.files),
) )
+88 -18
View File
@@ -2,8 +2,8 @@
import http.client import http.client
import http.cookiejar import http.cookiejar
import html
import json import json
import mimetypes
import re import re
import sys import sys
import time import time
@@ -15,7 +15,7 @@ from typing import Any
from .constants import DOWNLOADABLE_MODULES, USER_AGENT from .constants import DOWNLOADABLE_MODULES, USER_AGENT
from .local_files import archive_existing_file from .local_files import archive_existing_file
from .models import Course, FileItem, MoodleError from .models import Course, FileItem, MoodleConnectionError, MoodleError
from .parsers import _CourseStructureParser, _FormParser, _LinkParser, _parse_moodle_config from .parsers import _CourseStructureParser, _FormParser, _LinkParser, _parse_moodle_config
from .paths import ( from .paths import (
_activity_root, _activity_root,
@@ -111,15 +111,55 @@ class MoodleClient:
detail = exc.read(500).decode("utf-8", "replace").strip() detail = exc.read(500).decode("utf-8", "replace").strip()
raise MoodleError(f"HTTP {exc.code} from {url}: {detail or exc.reason}") from exc raise MoodleError(f"HTTP {exc.code} from {url}: {detail or exc.reason}") from exc
except urllib.error.URLError as exc: except urllib.error.URLError as exc:
raise MoodleError(f"Could not connect to {url}: {exc.reason}") from exc raise MoodleConnectionError(f"Could not connect to {url}: {exc.reason}") from exc
except (TimeoutError, http.client.HTTPException) as exc: except (ConnectionError, TimeoutError, http.client.HTTPException) as exc:
raise MoodleError(f"connection to {url} failed: {exc}") from exc raise MoodleConnectionError(f"connection to {url} failed: {exc}") from exc
def _read_text(self, path_or_url: str, **kwargs: Any) -> tuple[str, str, Any]: def _read_text(
self,
path_or_url: str,
*,
inspect_module: bool = False,
**kwargs: Any,
) -> tuple[str, str, Any]:
attempts = 1 if kwargs.get("data") is not None else 4
for attempt in range(attempts):
if attempt:
time.sleep(2 ** (attempt - 1))
try:
with self._request(path_or_url, **kwargs) as response: with self._request(path_or_url, **kwargs) as response:
headers = response.headers
final_url = response.geturl()
if inspect_module and self._is_module_file(headers):
return "", final_url, headers
if inspect_module:
limit = 8 * 1024 * 1024
raw = response.read(limit + 1)
if len(raw) > limit:
raise MoodleError("activity page exceeds the 8 MiB inspection limit")
if response.length:
raise http.client.IncompleteRead(raw, response.length)
else:
raw = response.read() raw = response.read()
charset = response.headers.get_content_charset() or "utf-8" charset = headers.get_content_charset() or "utf-8"
return raw.decode(charset, "replace"), response.geturl(), response.headers return raw.decode(charset, "replace"), final_url, headers
except MoodleConnectionError:
if attempt + 1 == attempts:
raise
except (ConnectionError, TimeoutError, http.client.HTTPException) as exc:
if attempt + 1 == attempts:
raise MoodleConnectionError(
f"connection interrupted while reading {path_or_url}: {exc}"
) from exc
raise AssertionError("response read must return or raise")
@staticmethod
def _is_module_file(headers: Any) -> bool:
content_type = headers.get_content_type()
return headers.get_content_disposition() == "attachment" or not (
content_type.startswith("text/")
or content_type in {"application/xhtml+xml", "application/xml"}
)
def authenticate(self) -> str: def authenticate(self) -> str:
if self.has_browser_session: if self.has_browser_session:
@@ -233,6 +273,8 @@ class MoodleClient:
self.user_id = int(config["userId"]) self.user_id = int(config["userId"])
if not self.sesskey: if not self.sesskey:
raise MoodleError("the page opened, but Moodle's session key was not found") raise MoodleError("the page opened, but Moodle's session key was not found")
if not self.user_id or self.user_id <= 0:
raise MoodleError("the browser session is not logged in as a Moodle user")
def api_call(self, function: str, **params: Any) -> Any: def api_call(self, function: str, **params: Any) -> Any:
if not self.token: if not self.token:
@@ -295,7 +337,9 @@ class MoodleClient:
"requiredfields": ["id", "fullname", "shortname", "visible", "enddate"], "requiredfields": ["id", "fullname", "shortname", "visible", "enddate"],
}, },
) )
raw_courses = data.get("courses", []) if isinstance(data, dict) else [] if not isinstance(data, dict) or not isinstance(data.get("courses"), list):
raise MoodleError("Moodle returned an unexpected enrolled-course response")
raw_courses = data["courses"]
courses = [ courses = [
Course(int(item["id"]), str(item.get("fullname") or item.get("displayname") or item["id"]), str(item.get("shortname") or "")) Course(int(item["id"]), str(item.get("fullname") or item.get("displayname") or item["id"]), str(item.get("shortname") or ""))
for item in raw_courses for item in raw_courses
@@ -346,9 +390,7 @@ class MoodleClient:
def _list_files_web(self, course_id: int) -> list[FileItem]: def _list_files_web(self, course_id: int) -> list[FileItem]:
page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}") page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}")
structure_parser = _CourseStructureParser(final_url) structure = self._parse_course_structure(page, final_url, course_id)
structure_parser.feed(page)
structure = structure_parser.result()
self._course_structure_cache[course_id] = structure self._course_structure_cache[course_id] = structure
activity_by_url: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {} activity_by_url: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {}
for section in structure: for section in structure:
@@ -384,14 +426,16 @@ class MoodleClient:
separator = "&" if urllib.parse.urlparse(module_url).query else "?" separator = "&" if urllib.parse.urlparse(module_url).query else "?"
inspect_url = module_url + separator + "redirect=0" inspect_url = module_url + separator + "redirect=0"
try: try:
module_page, module_final_url, headers = self._read_text(inspect_url) module_page, module_final_url, headers = self._read_text(inspect_url, inspect_module=True)
except MoodleError as exc: except MoodleError as exc:
if not isinstance(exc.__cause__, urllib.error.HTTPError):
raise
print(f"warning: skipped {activity}: {exc}", file=sys.stderr) print(f"warning: skipped {activity}: {exc}", file=sys.stderr)
continue continue
content_type = headers.get_content_type() if hasattr(headers, "get_content_type") else "" if self._is_module_file(headers):
if not (content_type.startswith("text/") or content_type in {"application/xhtml+xml", "application/xml"}): files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata, headers))
files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata))
continue continue
self._validate_web_page(module_page, module_final_url)
module_parser = _LinkParser(module_final_url) module_parser = _LinkParser(module_final_url)
module_parser.feed(module_page) module_parser.feed(module_page)
candidates = list(module_parser.media) candidates = list(module_parser.media)
@@ -409,15 +453,21 @@ class MoodleClient:
activity: str, activity: str,
url: str, url: str,
metadata: tuple[dict[str, Any], dict[str, Any]] | None = None, metadata: tuple[dict[str, Any], dict[str, Any]] | None = None,
headers: Any = None,
) -> FileItem: ) -> FileItem:
path_name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name path_name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name
content_length = headers.get("Content-Length", "") if headers is not None else ""
section_metadata, activity_metadata = metadata or ({}, {}) section_metadata, activity_metadata = metadata or ({}, {})
return FileItem( return FileItem(
course_id=course_id, course_id=course_id,
section=section, section=section,
activity=activity or path_name, activity=activity or path_name,
filename=path_name or _clean_name(activity), filename=_filename_from_headers(headers, url, activity) if headers is not None else (
path_name or _clean_name(activity)
),
url=url, url=url,
mimetype=headers.get_content_type() if headers is not None else "",
filesize=int(content_length) if content_length.isascii() and content_length.isdecimal() else None,
chapter=str(section_metadata.get("name") or section), chapter=str(section_metadata.get("name") or section),
section_id=section_metadata.get("id"), section_id=section_metadata.get("id"),
section_number=section_metadata.get("number"), section_number=section_metadata.get("number"),
@@ -432,12 +482,32 @@ class MoodleClient:
if cached is not None: if cached is not None:
return cached return cached
page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}") page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}")
structure = self._parse_course_structure(page, final_url, course_id)
self._course_structure_cache[course_id] = structure
return structure
def _parse_course_structure(self, page: str, final_url: str, course_id: int) -> list[dict[str, Any]]:
self._validate_web_page(page, final_url)
parser = _CourseStructureParser(final_url) parser = _CourseStructureParser(final_url)
parser.feed(page) parser.feed(page)
structure = parser.result() structure = parser.result()
self._course_structure_cache[course_id] = structure if not structure:
raise MoodleError(
f"course {course_id} exposed no readable sections; check access and the site's course format"
)
return structure return structure
@staticmethod
def _validate_web_page(page: str, final_url: str) -> None:
if _is_cloudflare_challenge(page):
raise MoodleError("Cloudflare rejected the LMS page; run `ravin login` again")
forms = _FormParser()
forms.feed(page)
if "/login/" in urllib.parse.urlsplit(final_url).path or any(
"password" in form["inputs"] for form in forms.forms
):
raise MoodleError("the session expired while reading the LMS; run `ravin login` again")
def download( def download(
self, self,
item: FileItem, item: FileItem,
+47
View File
@@ -0,0 +1,47 @@
"""Persistent, repeatable shell completion setup."""
from pathlib import Path
import os
import shlex
import sys
def install_completion(shell: str) -> Path:
if shell == "zsh":
startup = Path(os.environ.get("ZDOTDIR") or Path.home()) / ".zshrc"
else:
startup = Path.home() / (".bash_profile" if sys.platform == "darwin" else ".bashrc")
start = "# >>> ravin completion >>>"
end = "# <<< ravin completion <<<"
original = startup.read_text() if startup.exists() else ""
if start in original or end in original:
if original.count(start) != 1 or original.count(end) != 1:
raise ValueError(f"Invalid Ravin completion markers in {startup}")
first = original.index(start)
last = original.index(end)
if last < first:
raise ValueError(f"Invalid Ravin completion markers in {startup}")
before = original[:first]
after = original[last + len(end):].lstrip("\n")
else:
before = original + ("\n" if original and not original.endswith("\n") else "")
after = ""
python = shlex.quote(sys.executable)
initialize = (
" if ! (( $+functions[compdef] )); then\n"
" autoload -Uz compinit\n"
" compinit\n"
" fi\n"
) if shell == "zsh" else ""
block = (
f"{start}\n"
f"if [ -x {python} ]; then\n"
f"{initialize}"
f' eval "$({python} -m ravin completion {shell})"\n'
f"fi\n{end}\n"
)
updated = before + block + after
if updated != original:
startup.parent.mkdir(parents=True, exist_ok=True)
startup.write_text(updated)
return startup
+1 -1
View File
@@ -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.16.0" __version__ = "0.16.4"
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"}
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"} LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
+125
View File
@@ -0,0 +1,125 @@
"""Offline course summary PDFs, rendered with Unicode shaping in Chromium."""
from __future__ import annotations
import base64
import hashlib
from html import escape
from pathlib import Path
import tempfile
from urllib.parse import unquote
from .models import MoodleError
from .paths import _read_json_object, _relative_browser_path
from .scan import scan_offline
def summary_sources(public: Path, course: dict) -> list[tuple[str, str, Path]]:
"""Read summaries in manifest order, once per activity bundle."""
sources = []
seen = set()
root = (public / "courses" / str(course["id"])).resolve()
for section in course.get("sections", []):
for item in section.get("items", []):
url = item.get("artifacts", {}).get("summary", {}).get("url")
if not url:
continue
path = (public / unquote(url)).resolve()
if not path.is_relative_to(root):
raise MoodleError(f"summary is outside its course directory: {url}")
if path in seen or not path.is_file():
continue
seen.add(path)
if path.read_text(encoding="utf-8").strip():
sources.append((section.get("title") or section.get("name") or "", item.get("title") or "", path))
return sources
def source_digest(course: dict, sources: list[tuple[str, str, Path]]) -> str:
digest = hashlib.sha256(str(course.get("fullname", "")).encode())
for chapter, title, path in sources:
digest.update((chapter + "\0" + title + "\0").encode())
digest.update(path.read_bytes())
return digest.hexdigest()
def summary_pdf_artifact(public: Path, course: dict) -> dict | None:
path = public / "courses" / str(course["id"]) / "artifacts" / "summaries.fa.pdf"
if not path.is_file():
return None
metadata = _read_json_object(path.with_suffix(".meta.json"))
sources = summary_sources(public, course)
return {"url": _relative_browser_path(path, public), "format": "pdf", "language": "fa",
"summary_count": metadata.get("summary_count", 0),
"state": "complete" if metadata.get("source_sha256") == source_digest(course, sources) else "stale"}
def render_html(course: dict, sources: list[tuple[str, str, Path]]) -> str:
from markdown_it import MarkdownIt
markdown = MarkdownIt("commonmark", {"html": False}).enable("table")
# No external resources or raw HTML from summaries are loaded by the renderer.
markdown.disable("image")
faces = []
for weight, name in ((400, "Regular"), (700, "Bold")):
data = base64.b64encode((Path(__file__).parent / "fonts" / f"Vazirmatn-{name}.ttf").read_bytes()).decode()
faces.append(f"@font-face{{font-family:Vazirmatn;font-weight:{weight};src:url(data:font/ttf;base64,{data})}}")
body = [f'<h1 dir="auto">{escape(course.get("fullname") or str(course["id"]))}</h1>']
previous = None
for chapter, title, path in sources:
if chapter != previous:
body.append(f'<h2 dir="auto">{escape(chapter)}</h2>')
previous = chapter
content = markdown.render(path.read_text(encoding="utf-8"))
body.append(f'<section><h3 dir="auto">{escape(title)}</h3>{content}</section>')
return '<!doctype html><html lang="fa" dir="rtl"><meta charset="utf-8"><style>' + ''.join(faces) + '''
@page { size:A4; margin:18mm 16mm 20mm; }
body {font-family:Vazirmatn; font-size:11pt; line-height:1.9; color:#182334;}
h1 {font-size:24pt;} h2 {font-size:18pt; border-bottom:1px solid #ccd5df;}
h3 {font-size:14pt;} h1,h2,h3 {break-after:avoid;}
p,li,td,th {unicode-bidi:plaintext; overflow-wrap:anywhere;}
pre {direction:ltr; text-align:left; white-space:pre-wrap; unicode-bidi:isolate;}
code {font-family:Vazirmatn; unicode-bidi:isolate; direction:ltr;}
table {width:100%; border-collapse:collapse; font-size:10pt;}
th,td {border:1px solid #ccd5df; padding:5px;}
tr,blockquote {break-inside:avoid;} a {color:#245b8c;}
</style><body>''' + ''.join(body) + '</body></html>'
def create_course_pdf(public: Path, course_id: int) -> dict:
"""Atomically replace the course PDF and refresh Library manifests."""
from .scan import _atomic_json
public = public.expanduser().resolve()
scan_offline(public, [course_id])
course = _read_json_object(public / "courses" / str(course_id) / "manifest.json")["course"]
sources = summary_sources(public, course)
if not sources:
raise MoodleError(f"course {course_id} has no non-empty summaries; run `ravin summarize {course_id}` first")
try:
from playwright.sync_api import sync_playwright, Error
html = render_html(course, sources)
except ImportError as exc:
raise MoodleError('PDF support requires `pip install "ravin-moodle-downloader[pdf]"` and `python -m playwright install chromium`') from exc
target = public / "courses" / str(course_id) / "artifacts" / "summaries.fa.pdf"
target.parent.mkdir(parents=True, exist_ok=True)
digest = source_digest(course, sources)
try:
with tempfile.TemporaryDirectory(prefix=".pdf-", dir=target.parent) as temporary:
output = Path(temporary) / "course.pdf"
with sync_playwright() as playwright:
browser = playwright.chromium.launch()
try:
page = browser.new_page()
page.route("**/*", lambda route: route.abort())
page.set_content(html, wait_until="load")
page.evaluate("document.fonts.ready")
page.pdf(path=str(output), format="A4", print_background=True,
prefer_css_page_size=True, display_header_footer=True,
header_template="<span></span>",
footer_template='<div style="width:100%;text-align:center;font-size:9px"><span class="pageNumber"></span> / <span class="totalPages"></span></div>')
finally:
browser.close()
output.replace(target)
except Error as exc:
raise MoodleError(f"PDF rendering failed; install Chromium with `python -m playwright install chromium`: {exc}") from exc
_atomic_json(target.with_suffix(".meta.json"), {"source_sha256": digest, "summary_count": len(sources)})
scan_offline(public, [course_id])
return {"course_id": course_id, "path": str(target), "summary_count": len(sources)}
+93
View File
@@ -0,0 +1,93 @@
Copyright 2015 The Vazirmatn Project Authors (https://github.com/rastikerdar/vazirmatn)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
+4
View File
@@ -7,6 +7,10 @@ class MoodleError(RuntimeError):
"""A friendly, expected Moodle/API error.""" """A friendly, expected Moodle/API error."""
class MoodleConnectionError(MoodleError):
"""A failure to connect to Moodle or finish reading its response."""
@dataclass(frozen=True) @dataclass(frozen=True)
class Course: class Course:
id: int id: int
+5 -1
View File
@@ -254,6 +254,8 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
for section in course.get("sections", []): for section in course.get("sections", []):
for item in section.get("items", []): for item in section.get("items", []):
records += 1 records += 1
if item.get("activity_type") == "quiz":
item["kind"] = "assessment"
activity_directory = _activity_directory(public, course_id, section, item) activity_directory = _activity_directory(public, course_id, section, item)
download_state, local_path = _download_state(activity_directory, item) download_state, local_path = _download_state(activity_directory, item)
media_applicable = item.get("kind") in {"video", "audio"} media_applicable = item.get("kind") in {"video", "audio"}
@@ -361,6 +363,8 @@ def _reconcile_course(public: Path, course: dict[str, Any]) -> dict[str, Any]:
}, },
} }
) )
from .course_pdf import summary_pdf_artifact
course["summary_pdf"] = summary_pdf_artifact(public, course)
return course return course
@@ -369,7 +373,7 @@ def _course_summary(course: dict[str, Any]) -> dict[str, Any]:
key: course.get(key) key: course.get(key)
for key in ( for key in (
"id", "fullname", "shortname", "source_url", "section_count", "activity_count", "id", "fullname", "shortname", "source_url", "section_count", "activity_count",
"record_count", "file_count", "downloaded_count", "downloaded_bytes", "type_counts", "states", "record_count", "file_count", "downloaded_count", "downloaded_bytes", "type_counts", "states", "summary_pdf",
) )
} | {"manifest_url": f"courses/{course.get('id')}/manifest.json"} } | {"manifest_url": f"courses/{course.get('id')}/manifest.json"}
+71
View File
@@ -0,0 +1,71 @@
"""Synchronize the public learning library to an SSH destination."""
from __future__ import annotations
import os
import shutil
import subprocess
from pathlib import Path
from .models import MoodleError
VIDEO_PATTERNS = (
"*.[mM][pP]4", "*.[mM][pP]4.part",
"*.[mM]4[vV]", "*.[mM]4[vV].part",
"*.[mM][kK][vV]", "*.[mM][kK][vV].part",
"*.[mM][oO][vV]", "*.[mM][oO][vV].part",
"*.[aA][vV][iI]", "*.[aA][vV][iI].part",
"*.[wW][eE][bB][mM]", "*.[wW][eE][bB][mM].part",
"*.[fF][lL][vV]", "*.[fF][lL][vV].part",
"*.[wW][mM][vV]", "*.[wW][mM][vV].part",
"*.[mM][pP][eE][gG]", "*.[mM][pP][eE][gG].part",
"*.[mM][pP][gG]", "*.[mM][pP][gG].part",
"*.[3][gG][pP]", "*.[3][gG][pP].part",
"*.[oO][gG][vV]", "*.[oO][gG][vV].part",
)
def sync_public(
public: Path,
destination: str | None,
*,
dry_run: bool = False,
delete: bool = False,
) -> int:
"""Run rsync for non-video public files and return its exit code."""
resolved_destination = destination or os.getenv("SYNC_PUBLIC_DESTINATION")
if not resolved_destination:
raise MoodleError(
"no sync destination provided; use --destination USER@HOST:PATH "
"or set SYNC_PUBLIC_DESTINATION"
)
source = public.expanduser().resolve()
if not source.is_dir():
raise MoodleError(f"public web root does not exist: {source}")
rsync = shutil.which("rsync")
if rsync is None:
raise MoodleError("rsync is not installed locally")
command = [
rsync,
"--archive",
"--compress",
"--human-readable",
"--partial",
"--progress",
"--itemize-changes",
]
command.extend(f"--exclude={pattern}" for pattern in VIDEO_PATTERNS)
if dry_run:
command.append("--dry-run")
if delete:
command.append("--delete")
command.extend(("--", f"{source}/", resolved_destination))
print(f"Syncing {source}/ to {resolved_destination}")
if dry_run:
print("Dry run: no files will be changed.")
if delete:
print("Mirror mode: stale remote non-video files will be deleted.")
return subprocess.run(command, check=False).returncode
+46
View File
@@ -109,6 +109,23 @@ class CourseAssessmentTests(unittest.TestCase):
self.assertEqual(item["kind"], "assessment") self.assertEqual(item["kind"], "assessment")
self.assertEqual(item["bundle_path"], "assessments/final-exam") self.assertEqual(item["bundle_path"], "assessments/final-exam")
def test_local_exam_pdf_remains_available_after_repeated_scans(self) -> None:
course = self.write_course(56)
self.write_overlay(course, filename="final-exam.pdf")
attachment = course / "assessments" / "final-exam" / "files" / "final-exam.pdf"
attachment.parent.mkdir(parents=True)
attachment.write_bytes(b"exam PDF attachment")
scan_offline(self.public, [56])
scan_offline(self.public, [56])
manifest = json.loads((course / "manifest.json").read_text(encoding="utf-8"))
item = manifest["course"]["sections"][-1]["items"][0]
self.assertEqual(item["state"]["download"], "complete")
self.assertEqual(item["extension"], "pdf")
self.assertEqual(item["mimetype"], "application/pdf")
self.assertEqual(item["local_url"], "courses/56/assessments/final-exam/files/final-exam.pdf")
def test_question_import_uses_the_local_assessment_bundle(self) -> None: def test_question_import_uses_the_local_assessment_bundle(self) -> None:
course = self.write_course(51) course = self.write_course(51)
self.write_overlay(course) self.write_overlay(course)
@@ -130,6 +147,35 @@ class CourseAssessmentTests(unittest.TestCase):
self.assertEqual(item["bundle_path"], "assessments/final-exam") self.assertEqual(item["bundle_path"], "assessments/final-exam")
self.assertEqual(item["state"]["questions"], "complete") self.assertEqual(item["state"]["questions"], "complete")
def test_hidden_linked_quiz_keeps_local_exam_and_reconnects_when_visible(self) -> None:
course = self.write_course(53)
self.write_overlay(course, activity_id=6126)
questions = course / "assessments" / "final-exam" / "artifacts" / "questions.fa.md"
questions.parent.mkdir(parents=True)
questions.write_text("# Preserved exam", encoding="utf-8")
scan_offline(self.public, [53])
scan_offline(self.public, [53])
manifest_path = course / "manifest.json"
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
exam = manifest["course"]["sections"][-1]["items"][0]
self.assertEqual(exam["linked_activity_id"], 6126)
self.assertIsNone(exam["activity_id"])
self.assertEqual(exam["state"]["questions"], "complete")
self.assertEqual(exam["bundle_path"], "assessments/final-exam")
manifest["course"]["sections"][0]["items"].append({
"activity_id": 6126, "activity_position": 1, "activity_type": "quiz",
"title": "Visible quiz", "kind": "quiz", "filename": "",
})
manifest_path.write_text(json.dumps(manifest), encoding="utf-8")
scan_offline(self.public, [53])
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
exams = [item for section in manifest["course"]["sections"] for item in section["items"]
if item.get("assessment_id") == "final-exam"]
self.assertEqual(len(exams), 1)
self.assertEqual(exams[0]["activity_id"], 6126)
self.assertEqual(exams[0]["state"]["questions"], "complete")
self.assertEqual(questions.read_text(encoding="utf-8"), "# Preserved exam")
def test_active_exam_is_visible_but_cannot_publish_answers(self) -> None: def test_active_exam_is_visible_but_cannot_publish_answers(self) -> None:
course = self.write_course(56) course = self.write_course(56)
self.write_overlay(course, status="active") self.write_overlay(course, status="active")
+299
View File
@@ -0,0 +1,299 @@
"""Regressions for the Ravin portal and its October 2026 Moodle theme."""
import email.message
import io
import json
import sys
import tempfile
import unittest
from contextlib import redirect_stderr
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from ravin.auth import (
_authenticate_browser_session,
_authenticated_browser_session,
_capture_browser_session,
_select_login_tab,
)
from ravin.client import MoodleClient
from ravin.models import MoodleConnectionError, MoodleError
class BrowserUpdateTests(unittest.TestCase):
def test_network_failure_does_not_refresh_saved_browser_session(self):
args = SimpleNamespace(site="https://training.example", refresh_session=False)
with patch.object(
MoodleClient, "authenticate", side_effect=MoodleConnectionError("DNS failed")
), patch("ravin.auth._capture_browser_session") as capture:
with self.assertRaisesRegex(MoodleConnectionError, "DNS failed"):
_authenticate_browser_session(args, ("Synthetic Browser", "MoodleSession=synthetic"))
capture.assert_not_called()
def capture(self, *, captcha=False, existing_session=False, new_tab=False, invalid_key=False, use_zen=False):
test = self
class Element:
def __init__(self, visible):
self.visible = visible
def is_displayed(self):
return self.visible
def get_attribute(self, name):
return 'https://lms.example/moodle/login_student_user/162/' if name == 'href' else None
def click(self):
driver.launch()
class Driver:
current_url = 'about:blank'
awaiting_captcha = captcha
quit_called = False
launches = 0
def __init__(self):
self.window_handles = ['portal']
self.current_window_handle = 'portal'
self.switch_to = SimpleNamespace(window=self.switch_window)
def switch_window(self, handle):
self.current_window_handle = handle
self.current_url = 'https://training.example/my/'
def launch(self):
self.launches += 1
test.assertEqual(self.launches, 1, 'SSO link must only be activated once')
if new_tab:
self.window_handles.append('moodle')
elif invalid_key:
self.current_url = 'https://training.example/auth/userkey/login.php?key=synthetic'
else:
self.current_url = 'https://training.example/my/'
def get(self, url):
test.assertNotIn('login_student_user', url, 'Use the portal link instead of direct navigation')
self.current_url = url
def execute_script(self, script, *args):
if script == 'arguments[0].click();':
args[0].click()
return None
test.assertFalse(args, 'CAPTCHA form must not be auto-submitted')
if 'navigator.userAgent' in script:
return 'Synthetic Browser/1'
test.assertNotIn('logout.php', script)
test.assertIn('M.cfg.sesskey', script)
return self.current_url == 'https://training.example/my/' or (
existing_session and self.current_url == 'https://training.example/my/courses.php'
)
def find_elements(self, by, selector):
if 'invalidkey' in selector:
return [Element(True)] if '/auth/userkey/' in self.current_url else []
if 'login_student_user' in selector:
return [] if self.awaiting_captcha else [Element(False)]
if 'captcha' in selector and self.awaiting_captcha:
return [Element(True)]
return []
def get_cookies(self):
return [{'name': 'MoodleSession', 'value': 'synthetic'}]
def quit(self):
self.quit_called = True
driver = Driver()
output = io.StringIO()
with tempfile.TemporaryDirectory() as directory:
args = SimpleNamespace(
site='https://training.example', login_url='https://lms.example/',
browser_executable=None, browser_profile=Path(directory) / 'profile',
login_timeout=30, env_values={'RAVIN_USERNAME': 'synthetic', 'RAVIN_PASSWORD': 'synthetic'},
)
with patch('ravin.auth._find_browser_executable', return_value=Path('/synthetic/zen' if use_zen else '/synthetic/chrome')), \
patch('selenium.webdriver.Chrome', return_value=driver), \
patch('selenium.webdriver.Firefox', return_value=driver), \
patch('selenium.webdriver.firefox.service.Service'), \
patch('ravin.auth._capture_chromium_session', return_value=('Synthetic Browser/1', 'MoodleSession=synthetic')) as fallback, \
patch('ravin.auth.time.sleep', side_effect=lambda _: setattr(driver, 'awaiting_captcha', False)), \
redirect_stderr(output):
if invalid_key and not use_zen:
with self.assertRaisesRegex(MoodleError, 'invalidkey'):
_capture_browser_session(args)
self.assertTrue(driver.quit_called)
self.assertEqual(driver.launches, 1)
self.assertNotIn('key=synthetic', output.getvalue())
return output.getvalue()
result = _capture_browser_session(args)
if invalid_key and use_zen:
fallback.assert_called_once_with(args, [{'name': 'MoodleSession', 'value': 'synthetic'}])
else:
fallback.assert_not_called()
self.assertTrue(driver.quit_called)
self.assertEqual(result, ('Synthetic Browser/1', 'MoodleSession=synthetic'))
self.assertEqual(driver.launches, 0 if existing_session else 1)
return output.getvalue()
def test_hidden_launch_link_and_theme_without_logout_link(self):
self.capture()
def test_captcha_waits_for_human_without_submitting_stored_credentials(self):
self.assertIn('CAPTCHA detected', self.capture(captcha=True))
def test_existing_profile_session_skips_portal_launch(self):
self.capture(existing_session=True)
def test_new_login_tab_is_followed_without_relaunching(self):
self.capture(new_tab=True)
def test_invalid_key_is_reported_without_replaying_the_link(self):
self.capture(invalid_key=True)
def test_zen_invalid_key_switches_engine_with_portal_session(self):
self.assertIn('switching to Chromium', self.capture(invalid_key=True, use_zen=True))
def test_session_from_another_origin_is_not_captured(self):
driver = SimpleNamespace(current_url='https://another.example/my/')
self.assertIsNone(_authenticated_browser_session(driver, 'https://training.example'))
def test_closed_browser_reports_actionable_error(self):
with self.assertRaisesRegex(MoodleError, 'browser was closed'):
_select_login_tab(SimpleNamespace(window_handles=[]), {'portal'})
def test_closed_active_tab_switches_to_remaining_tab(self):
from selenium.common.exceptions import NoSuchWindowException
class Driver:
window_handles = ['moodle']
@property
def current_window_handle(self):
raise NoSuchWindowException()
switched = []
driver = Driver()
driver.switch_to = SimpleNamespace(window=switched.append)
self.assertEqual(_select_login_tab(driver, {'moodle', 'portal'}), {'moodle'})
self.assertEqual(switched, ['moodle'])
class ScanUpdateTests(unittest.TestCase):
def setUp(self):
self.client = MoodleClient('https://training.example', cookie_header='MoodleSession=synthetic')
def test_browser_session_accepts_new_theme_without_logout_link(self):
page = '<script>M.cfg = {"sesskey":"synthetic","userId":42};</script>'
with patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/my/courses.php', None)):
self.assertEqual(self.client.authenticate(), 'browser-session')
def test_guest_session_with_sesskey_is_rejected(self):
for user in (0, -1, None):
page = '<script>M.cfg = ' + json.dumps({'sesskey': 'synthetic', 'userId': user}) + ';</script>'
with self.subTest(user=user), patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/my/courses.php', None)):
with self.assertRaises(MoodleError):
self.client.authenticate()
def test_login_or_unrecognized_page_cannot_become_empty_course(self):
for page, url in (
('<form><input name="password" type="password"></form>', 'https://lms.example/employee/user/login/'),
('<h1>Access denied</h1>', 'https://training.example/course/view.php?id=51'),
):
with self.subTest(url=url), patch.object(self.client, '_read_text', return_value=(page, url, None)):
with self.assertRaises(MoodleError):
self.client.course_structure(51)
self.assertNotIn(51, self.client._course_structure_cache)
def test_unexpected_course_response_is_rejected(self):
for payload in (None, {}, {'courses': None}):
with self.subTest(payload=payload), patch.object(self.client, 'ajax_call', return_value=payload):
with self.assertRaises(MoodleError):
self.client.list_courses()
def test_expired_activity_page_aborts_file_discovery(self):
page = '''<li id="section-1" data-for="section" data-id="1016" data-sectionid="1">
<li class="modtype_resource" data-for="cmitem" data-id="5685">
<a href="/mod/resource/view.php?id=5685">Schedule</a></li></li>'''
headers = email.message.Message()
headers['Content-Type'] = 'text/html'
with patch.object(self.client, '_read_text', side_effect=[
(page, 'https://training.example/course/view.php?id=51', headers),
('<form><input name="password"></form>', 'https://training.example/login/index.php', headers),
]):
with self.assertRaisesRegex(MoodleError, 'session expired'):
self.client.list_files(51)
def test_collapsed_section_and_sidebar_are_parsed_without_duplicates(self):
page = '''<div id="course-index-section-1016" data-for="section" data-id="1016" data-number="1">
<li data-for="cm" data-id="5685"><a href="/mod/resource/view.php?id=5685">Schedule</a></li></div>
<li id="section-1" data-for="section" data-id="1016" data-sectionid="1" data-sectionname="Schedule">
<div class="content collapse"><ul data-for="cmlist">
<li id="module-5685" class="activity modtype_resource" data-for="cmitem" data-id="5685">
<div data-activityname="Schedule PDF"><a href="/mod/resource/view.php?id=5685">Schedule PDF</a>
<span class="activitybadge">PDF</span><button class="btn-subtle-success">Done</button></div>
</li></ul></div></li>'''
with patch.object(self.client, '_read_text', return_value=(page, 'https://training.example/course/view.php?id=51', None)):
sections = self.client.course_structure(51)
self.assertEqual(len(sections), 1)
self.assertEqual(sections[0]['number'], 1)
self.assertEqual(sections[0]['activities'][0]['id'], 5685)
self.assertEqual(sections[0]['activities'][0]['name'], 'Schedule PDF')
self.assertTrue(sections[0]['activities'][0]['lms_completed'])
class ChromiumSessionTests(unittest.TestCase):
def capture(self, *, portal_cookies=(), invalid_key=False):
from unittest.mock import MagicMock
from ravin.auth import _capture_chromium_session
page = MagicMock()
page.url = 'https://training.example/my/courses.php'
page.is_closed.return_value = False
page.locator.return_value.count.return_value = int(invalid_key)
page.evaluate.side_effect = lambda script: 'Synthetic Chrome/140' if 'navigator.userAgent' in script else True
context = MagicMock()
context.pages = [page]
context.cookies.return_value = [{'name': 'MoodleSession', 'value': 'synthetic'}]
with tempfile.TemporaryDirectory() as directory:
args = SimpleNamespace(
site='https://training.example', login_url='https://lms.example/',
browser_profile=Path(directory), login_timeout=30,
browser_user_agent=None,
env_values={'RAVIN_USER_AGENT': 'Synthetic Chrome/140', 'RAVIN_COOKIE': 'MoodleSession=synthetic=part'},
)
with patch('playwright.sync_api.sync_playwright') as runtime, patch('pathlib.Path.is_file', return_value=True):
chromium = runtime.return_value.__enter__.return_value.chromium
chromium.launch_persistent_context.return_value = context
if invalid_key:
with self.assertRaisesRegex(MoodleError, 'Chromium too'):
_capture_chromium_session(args, portal_cookies)
else:
self.assertEqual(_capture_chromium_session(args, portal_cookies), ('Synthetic Chrome/140', 'MoodleSession=synthetic'))
context.close.assert_called_once()
return context, chromium
def test_browser_restart_rehydrates_saved_session_with_matching_user_agent(self):
context, chromium = self.capture()
context.add_cookies.assert_called_once_with([
{'name': 'MoodleSession', 'value': 'synthetic=part', 'url': 'https://training.example/', 'secure': True}
])
self.assertEqual(chromium.launch_persistent_context.call_args.kwargs['user_agent'], 'Synthetic Chrome/140')
def test_portal_session_retains_expiry_and_excludes_analytics(self):
context, chromium = self.capture(portal_cookies=[
{'name': 'sessionid', 'value': 'synthetic', 'domain': 'lms.example', 'path': '/', 'expiry': 1999999999, 'secure': True, 'httpOnly': True},
{'name': '_ga', 'value': 'synthetic', 'domain': 'lms.example', 'path': '/'},
])
cookies = context.add_cookies.call_args.args[0]
self.assertEqual(len(cookies), 1)
self.assertEqual(cookies[0]['expires'], 1999999999)
self.assertTrue(cookies[0]['secure'])
self.assertTrue(cookies[0]['httpOnly'])
self.assertNotIn('user_agent', chromium.launch_persistent_context.call_args.kwargs)
def test_invalid_key_in_chromium_closes_context_without_accepting_session(self):
self.capture(invalid_key=True)
if __name__ == '__main__':
unittest.main()
+88
View File
@@ -0,0 +1,88 @@
"""Exercise shell completion through argcomplete's shell protocol."""
import contextlib
import io
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
from ravin.cli import main
class CompletionTests(unittest.TestCase):
def complete(self, line):
with tempfile.TemporaryDirectory() as directory:
output = Path(directory) / "completions"
env = dict(os.environ, COMP_LINE=line, COMP_POINT=str(len(line)),
_ARGCOMPLETE="1", _ARGCOMPLETE_IFS="\n",
_ARGCOMPLETE_STDOUT_FILENAME=str(output))
result = subprocess.run(
[sys.executable, "-c", "from ravin.cli import main; main()"],
env=env, capture_output=True, text=True, timeout=10,
)
self.assertEqual(result.returncode, 0, result.stderr)
return [candidate.rstrip(" ") for candidate in output.read_text().splitlines()]
def test_commands_and_aliases(self):
self.assertIn("scan", self.complete("ravin sc"))
self.assertIn("recordings", self.complete("ravin recording"))
def test_command_options_and_choices(self):
self.assertIn("--no-keep-awake", self.complete("ravin transcribe --no-k"))
self.assertIn("cuda", self.complete("ravin transcribe --device cu"))
self.assertNotIn("--device", self.complete("ravin serve --d"))
def test_file_paths(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / "questions.md"
path.touch()
self.assertIn(str(path), self.complete(f"ravin questions 44 12 {directory}/qu"))
def test_setup_requires_no_authentication(self):
for shell in ("bash", "zsh"):
with self.subTest(shell=shell), patch("ravin.cli._authenticate") as authenticate:
output = io.StringIO()
with contextlib.redirect_stdout(output):
self.assertEqual(main(["completion", shell]), 0)
self.assertIn("ravin", output.getvalue())
authenticate.assert_not_called()
class PersistentCompletionTests(unittest.TestCase):
def test_install_preserves_settings_and_is_repeatable(self):
from ravin.completion import install_completion
for shell, filename in (("bash", ".bashrc"), ("zsh", ".zshrc")):
with self.subTest(shell=shell), tempfile.TemporaryDirectory() as directory:
home = Path(directory)
startup = home / filename
startup.write_text("# existing settings\nexport EXAMPLE=yes\n")
with patch("ravin.completion.Path.home", return_value=home), \
patch("ravin.completion.sys.platform", "linux"), \
patch.dict(os.environ, {"ZDOTDIR": ""}):
self.assertEqual(install_completion(shell), startup)
first = startup.read_text()
install_completion(shell)
self.assertEqual(startup.read_text(), first)
self.assertTrue(first.startswith("# existing settings\nexport EXAMPLE=yes\n"))
self.assertEqual(first.count("# >>> ravin completion >>>"), 1)
result = subprocess.run([shell, "-n", str(startup)], capture_output=True)
self.assertEqual(result.returncode, 0, result.stderr)
def test_zdotdir(self):
from ravin.completion import install_completion
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {"ZDOTDIR": directory}):
self.assertEqual(install_completion("zsh"), Path(directory) / ".zshrc")
def test_invalid_markers_preserve_file(self):
from ravin.completion import install_completion
with tempfile.TemporaryDirectory() as directory, patch.dict(os.environ, {"ZDOTDIR": directory}):
startup = Path(directory) / ".zshrc"
original = "# >>> ravin completion >>>\n# user settings\n"
startup.write_text(original)
with self.assertRaises(ValueError):
install_completion("zsh")
self.assertEqual(startup.read_text(), original)
+79
View File
@@ -0,0 +1,79 @@
from __future__ import annotations
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
from ravin.course_pdf import create_course_pdf, render_html, source_digest, summary_sources
from ravin.models import MoodleError
from ravin.scan import scan_offline
from ravin.cli import build_parser
class CoursePdfTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.public = Path(self.temp.name)
self.path = self.public / 'courses/44/content/001--001--101/artifacts/summary.fa.md'
self.path.parent.mkdir(parents=True)
self.path.write_text('# شبکه\n\nاعداد ۱۲۳ و ١٢٣ و 123، IP 192.168.1.1\n\n| نام | مقدار |\n| --- | --- |\n| پورت | 8080 |\n\n<script>alert(1)</script>\n', encoding='utf-8')
self.course = {'id': 44, 'fullname': 'شبکه Network+', 'sections': [
{'number': 1, 'name': 'فصل اول', 'items': [
{'title': 'درس اول', 'activity_id': 101, 'activity_position': 1, 'section_number': 1,
'artifacts': {'summary': {'url': self.path.relative_to(self.public).as_posix()}}}]}]}
(self.public / 'courses/44/manifest.json').write_text(json.dumps({'course': self.course}), encoding='utf-8')
def test_unicode_and_safe_markdown(self):
try:
html = render_html(self.course, summary_sources(self.public, self.course))
except ImportError:
self.skipTest('PDF optional dependencies are not installed')
for text in ['۱۲۳', '١٢٣', '123', '192.168.1.1', 'Vazirmatn', '<table>', 'فصل اول']:
self.assertIn(text, html)
self.assertNotIn('<script>', html)
self.assertIn('&lt;script&gt;', html)
def test_manifest_pdf_discovery_and_freshness(self):
scan_offline(self.public, [44])
course = json.loads((self.public / 'courses/44/manifest.json').read_text())['course']
target = self.public / 'courses/44/artifacts/summaries.fa.pdf'
target.parent.mkdir()
target.write_bytes(b'%PDF-test')
target.with_suffix('.meta.json').write_text(json.dumps({
'source_sha256': source_digest(course, summary_sources(self.public, course)), 'summary_count': 1}))
catalog = scan_offline(self.public, [44])
self.assertEqual(catalog['courses'][0]['summary_pdf']['state'], 'complete')
self.path.write_text('خلاصه جدید', encoding='utf-8')
self.assertEqual(scan_offline(self.public, [44])['courses'][0]['summary_pdf']['state'], 'stale')
def test_empty_course(self):
self.path.unlink()
with self.assertRaisesRegex(MoodleError, 'no non-empty summaries'):
create_course_pdf(self.public, 44)
def test_no_path_escape(self):
self.course['sections'][0]['items'][0]['artifacts']['summary']['url'] = '../outside.md'
with self.assertRaises(MoodleError):
summary_sources(self.public, self.course)
def test_cli(self):
args = build_parser().parse_args(['pdf', '44', '--json'])
self.assertEqual(args.course_id, 44)
self.assertTrue(args.json)
def test_render_failure_preserves_old_pdf(self):
try:
from playwright.sync_api import Error
except ImportError:
self.skipTest('PDF optional dependencies are not installed')
target = self.public / 'courses/44/artifacts/summaries.fa.pdf'
target.parent.mkdir()
target.write_bytes(b'old PDF')
with patch('playwright.sync_api.sync_playwright', side_effect=Error('failed')):
with self.assertRaises(MoodleError):
create_course_pdf(self.public, 44)
self.assertEqual(target.read_bytes(), b'old PDF')
+83 -5
View File
@@ -12,7 +12,7 @@ from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from ravin import Course, FileItem, MoodleClient from ravin import Course, FileItem, MoodleClient, MoodleError
from ravin.auth import ( from ravin.auth import (
_browser_login_url, _browser_login_url,
_capture_browser_session, _capture_browser_session,
@@ -38,9 +38,14 @@ from ravin.scan import format_scan, scan_offline, scan_remote
class _FakeResponse: class _FakeResponse:
def __init__(self, chunks, *, status=200, content_range=""): def __init__(
self, chunks, *, status=200, content_range="",
url="https://training.example/pluginfile.php/file.bin",
):
self.chunks = list(chunks) self.chunks = list(chunks)
self.status = status self.status = status
self.length = None
self.url = url
self.headers = email.message.Message() self.headers = email.message.Message()
self.headers["Content-Disposition"] = 'attachment; filename="file.bin"' self.headers["Content-Disposition"] = 'attachment; filename="file.bin"'
if content_range: if content_range:
@@ -56,9 +61,9 @@ class _FakeResponse:
return self.status return self.status
def geturl(self): def geturl(self):
return "https://training.example/pluginfile.php/file.bin" return self.url
def read(self, _size): def read(self, _size=None):
if not self.chunks: if not self.chunks:
return b"" return b""
value = self.chunks.pop(0) value = self.chunks.pop(0)
@@ -111,6 +116,12 @@ class ParserTests(unittest.TestCase):
self.assertIsNone(questions_wizard.course_id) self.assertIsNone(questions_wizard.course_id)
self.assertIsNone(questions_wizard.activity_id) self.assertIsNone(questions_wizard.activity_id)
self.assertIsNone(questions_wizard.questions) self.assertIsNone(questions_wizard.questions)
final_exam = build_parser().parse_args(
["final-exam", "44", "final-exam.md", "--file", "final-exam.pdf"]
)
self.assertEqual(final_exam.course_id, 44)
self.assertEqual(final_exam.questions, Path("final-exam.md"))
self.assertEqual(final_exam.files, [Path("final-exam.pdf")])
recording = build_parser().parse_args(["recording", "44", "5097", "class.mp4"]) recording = build_parser().parse_args(["recording", "44", "5097", "class.mp4"])
self.assertEqual(recording.course_id, 44) self.assertEqual(recording.course_id, 44)
self.assertEqual(recording.activity_id, 5097) self.assertEqual(recording.activity_id, 5097)
@@ -132,11 +143,23 @@ class ParserTests(unittest.TestCase):
) )
self.assertEqual(import_archive.url, "https://mirror.example/exports/latest.zip") self.assertEqual(import_archive.url, "https://mirror.example/exports/latest.zip")
self.assertEqual(import_archive.timeout, 120) self.assertEqual(import_archive.timeout, 120)
sync_public = build_parser().parse_args(
["sync-public", "--destination", "user@example:/srv/public/", "--dry-run", "--delete"]
)
self.assertEqual(sync_public.destination, "user@example:/srv/public/")
self.assertTrue(sync_public.dry_run)
self.assertTrue(sync_public.delete)
serve = build_parser().parse_args(["serve", "--port", "9000"]) 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):
class FakeLaunchLink: class FakeLaunchLink:
def __init__(self, driver):
self.driver = driver
def click(self):
self.driver.current_url = "https://training.example/my/"
def is_displayed(self): def is_displayed(self):
return True return True
@@ -147,6 +170,8 @@ class ParserTests(unittest.TestCase):
class FakeDriver: class FakeDriver:
current_url = "about:blank" current_url = "about:blank"
window_handles = ["main"]
current_window_handle = "main"
def get(self, url): def get(self, url):
if "/moodle/login_student_user/" in url: if "/moodle/login_student_user/" in url:
@@ -161,7 +186,7 @@ class ParserTests(unittest.TestCase):
def find_elements(self, _by, selector): def find_elements(self, _by, selector):
if "login_student_user" in selector and self.current_url == "https://lms.example/": if "login_student_user" in selector and self.current_url == "https://lms.example/":
return [FakeLaunchLink()] return [FakeLaunchLink(self)]
return [] return []
def get_cookies(self): def get_cookies(self):
@@ -192,6 +217,7 @@ class ParserTests(unittest.TestCase):
fake_common = types.ModuleType("selenium.common") fake_common = types.ModuleType("selenium.common")
fake_exceptions = types.ModuleType("selenium.common.exceptions") fake_exceptions = types.ModuleType("selenium.common.exceptions")
fake_exceptions.WebDriverException = RuntimeError fake_exceptions.WebDriverException = RuntimeError
fake_exceptions.NoSuchWindowException = RuntimeError
fake_webdriver_module = types.ModuleType("selenium.webdriver") fake_webdriver_module = types.ModuleType("selenium.webdriver")
fake_webdriver_common = types.ModuleType("selenium.webdriver.common") fake_webdriver_common = types.ModuleType("selenium.webdriver.common")
fake_by = types.ModuleType("selenium.webdriver.common.by") fake_by = types.ModuleType("selenium.webdriver.common.by")
@@ -671,6 +697,58 @@ class ParserTests(unittest.TestCase):
self.assertEqual(destination.read_bytes(), b"abcdexyz!!") self.assertEqual(destination.read_bytes(), b"abcdexyz!!")
self.assertEqual(client.request_headers, [{}, {"Range": "bytes=8-"}]) self.assertEqual(client.request_headers, [{}, {"Range": "bytes=8-"}])
def test_module_inspection_does_not_read_redirected_file_body(self):
course_url = "https://training.example/course/view.php?id=44"
course_page = b"""
<li id="section-1" data-for="section" data-id="940" data-sectionid="1">
<li class="modtype_resource" data-for="cmitem" data-id="4940">
<a href="/mod/resource/view.php?id=4940">Lesson</a></li></li>
"""
response = _FakeResponse([AssertionError("inspection read the media body")])
response.headers["Content-Type"] = "video/mp4"
response.headers.replace_header(
"Content-Disposition", 'inline; filename="lesson.mp4"'
)
response.headers["Content-Length"] = "607191032"
client = _FakeDownloadClient([_FakeResponse([course_page], url=course_url), response])
with tempfile.TemporaryDirectory() as directory, patch.object(
client, "list_courses", return_value=[Course(44, "Course")]
):
public = Path(directory)
scan_remote(client, public, [44])
manifest_path = public / "courses" / "44" / "manifest.json"
original = manifest_path.read_bytes()
item = json.loads(original)["course"]["sections"][0]["items"][0]
self.assertEqual(item["filename"], "lesson.mp4")
self.assertEqual(item["mimetype"], "video/mp4")
self.assertEqual(item["remote_size"], 607191032)
client.responses.append(_FakeResponse([course_page], url=course_url))
for _ in range(4):
interrupted = _FakeResponse([http.client.IncompleteRead(b"<html>")])
del interrupted.headers["Content-Disposition"]
interrupted.headers["Content-Type"] = "text/html"
client.responses.append(interrupted)
with patch("ravin.client.time.sleep"), self.assertRaisesRegex(
MoodleError, "connection interrupted while reading"
):
scan_remote(client, public, [44])
self.assertEqual(manifest_path.read_bytes(), original)
def test_module_inspection_retries_incomplete_html(self):
first = _FakeResponse([http.client.IncompleteRead(b"<html>")])
second = _FakeResponse([b"<html>complete</html>"])
for response in (first, second):
del response.headers["Content-Disposition"]
response.headers["Content-Type"] = "text/html; charset=utf-8"
client = _FakeDownloadClient([first, second])
with patch("ravin.client.time.sleep"):
page, _, _ = client._read_text("/mod/folder/view.php?id=1", inspect_module=True)
self.assertEqual(page, "<html>complete</html>")
def test_existing_partial_download_is_resumed(self): def test_existing_partial_download_is_resumed(self):
response = _FakeResponse([b"67890"], status=206, content_range="bytes 5-9/10") response = _FakeResponse([b"67890"], status=206, content_range="bytes 5-9/10")
client = _FakeDownloadClient([response]) client = _FakeDownloadClient([response])
+57 -1
View File
@@ -9,7 +9,63 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from ravin.scan import scan_offline from ravin.scan import scan_offline, scan_remote
from ravin.catalog import _build_library_catalog
from ravin.models import Course
class QuizVisibilityTests(unittest.TestCase):
def test_remote_scan_includes_quizzes_without_local_artifacts_as_assessments(self):
class Client:
site = "https://training.example"
def list_courses(self):
return [Course(56, "MCSA", "MCSA")]
def list_files(self, course_id):
return []
def course_structure(self, course_id):
return [{"number": 14, "name": "Practices", "activities": [
{"id": activity_id, "position": position, "type": "quiz", "name": f"Practice {position}"}
for position, activity_id in enumerate((6142, 6151, 6238), 1)
]}]
with tempfile.TemporaryDirectory() as directory:
public = Path(directory)
raw = _build_library_catalog(Client(), public)
self.assertEqual([item["kind"] for item in raw["courses"][0]["sections"][0]["items"]],
["assessment"] * 3)
scan_remote(Client(), public)
manifest = json.loads((public / "courses/56/manifest.json").read_text())
items = manifest["course"]["sections"][0]["items"]
self.assertEqual([item["activity_id"] for item in items], [6142, 6151, 6238])
self.assertTrue(all(item["kind"] == "assessment" for item in items))
self.assertTrue(all(item["state"]["questions"] == "missing" for item in items))
def test_offline_scan_repairs_legacy_quiz_kind_and_preserves_questions(self):
with tempfile.TemporaryDirectory() as directory:
public = Path(directory)
root = public / "courses/56"
artifact = root / "content/014--001--6142/artifacts/questions.fa.md"
artifact.parent.mkdir(parents=True)
artifact.write_text("# Practice three\n")
manifest_path = root / "manifest.json"
manifest_path.write_text(json.dumps({"course": {
"id": 56, "fullname": "MCSA", "sections": [{"number": 14, "items": [
{"activity_id": activity_id, "activity_position": position,
"activity_type": "quiz", "kind": "quiz", "title": f"Practice {position}"}
for position, activity_id in enumerate((6142, 6151, 6238), 1)
]}]
}}))
scan_offline(public, [56])
course = json.loads(manifest_path.read_text())["course"]
items = course["sections"][0]["items"]
self.assertTrue(all(item["kind"] == "assessment" for item in items))
self.assertEqual([item["state"]["questions"] for item in items],
["complete", "missing", "missing"])
self.assertEqual(artifact.read_text(), "# Practice three\n")
self.assertEqual(course["states"]["assessments"], {"total": 3, "complete": 1, "missing": 2})
class PortableArtifactStateTests(unittest.TestCase): class PortableArtifactStateTests(unittest.TestCase):
+50
View File
@@ -0,0 +1,50 @@
from __future__ import annotations
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
from ravin.models import MoodleError
from ravin.sync_public import VIDEO_PATTERNS, sync_public
class SyncPublicTests(unittest.TestCase):
def test_builds_video_excluding_rsync_command(self) -> None:
with tempfile.TemporaryDirectory() as directory:
public = Path(directory) / "public"
public.mkdir()
completed = subprocess.CompletedProcess([], 0)
with (
patch("ravin.sync_public.shutil.which", return_value="/usr/bin/rsync"),
patch("ravin.sync_public.subprocess.run", return_value=completed) as run,
):
exit_code = sync_public(
public,
"user@example:/srv/public/",
dry_run=True,
delete=True,
)
self.assertEqual(exit_code, 0)
command = run.call_args.args[0]
self.assertIn("--dry-run", command)
self.assertIn("--delete", command)
self.assertEqual(
[argument for argument in command if argument.startswith("--exclude=")],
[f"--exclude={pattern}" for pattern in VIDEO_PATTERNS],
)
self.assertEqual(command[-3:], ["--", f"{public.resolve()}/", "user@example:/srv/public/"])
def test_requires_a_destination(self) -> None:
with tempfile.TemporaryDirectory() as directory, patch.dict("os.environ", {}, clear=True):
with self.assertRaisesRegex(MoodleError, "no sync destination"):
sync_public(Path(directory), None)
if __name__ == "__main__":
unittest.main()