skip file bodies during Moodle activity scans
This commit is contained in:
14 files changed
+184
-30
No files matched your search
@@ -2,6 +2,12 @@
|
||||
|
||||
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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
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.
|
||||
@@ -24,6 +24,7 @@ python3 -m pip install .
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
@@ -101,6 +102,8 @@ 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.
|
||||
|
||||
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:
|
||||
|
||||
```bash
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<meta name="description" content="Browse the resources in a downloaded course.">
|
||||
<title>Course · Learning Library</title>
|
||||
<link rel="stylesheet" href="assets/styles.css?v=course-pdf-3">
|
||||
<script src="assets/app.js?v=course-pdf-3" defer></script>
|
||||
<script src="assets/app.js?v=0.16.4" defer></script>
|
||||
</head>
|
||||
<body data-page="course">
|
||||
<header class="topbar">
|
||||
|
||||
+1
-1
@@ -6,7 +6,7 @@
|
||||
<meta name="description" content="A private, local library for downloaded course materials.">
|
||||
<title>Learning Library</title>
|
||||
<link rel="stylesheet" href="assets/styles.css?v=course-pdf-3">
|
||||
<script src="assets/app.js?v=course-pdf-3" defer></script>
|
||||
<script src="assets/app.js?v=0.16.4" defer></script>
|
||||
</head>
|
||||
<body data-page="index">
|
||||
<header class="topbar">
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "ravin-moodle-downloader"
|
||||
version = "0.16.3"
|
||||
version = "0.16.4"
|
||||
description = "Scan, download, transcribe, summarize, and organize authorized Moodle course materials"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.10"
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import mimetypes
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -139,9 +140,9 @@ def merge_assessments(public: Path, course: dict[str, Any]) -> dict[str, Any]:
|
||||
"activity_type": "assessment",
|
||||
"title": assessment["title"],
|
||||
"description": str(assessment.get("description") or ""),
|
||||
"filename": "",
|
||||
"extension": "",
|
||||
"mimetype": "",
|
||||
"filename": str(assessment.get("filename") or ""),
|
||||
"extension": Path(str(assessment.get("filename") or "")).suffix.lstrip(".").casefold(),
|
||||
"mimetype": mimetypes.guess_type(str(assessment.get("filename") or ""))[0] or "",
|
||||
"source_url": course.get("source_url"),
|
||||
"lms_completed": None,
|
||||
**common,
|
||||
|
||||
+2
-2
@@ -14,7 +14,7 @@ from pathlib import Path
|
||||
|
||||
from .client import MoodleClient
|
||||
from .constants import DEFAULT_RAVIN_LOGIN_URL, ENV_KEYS
|
||||
from .models import MoodleError
|
||||
from .models import MoodleConnectionError, MoodleError
|
||||
|
||||
|
||||
class _InvalidSSOKey(MoodleError):
|
||||
@@ -588,7 +588,7 @@ def _authenticate_browser_session(
|
||||
try:
|
||||
mode = client.authenticate()
|
||||
except MoodleError as exc:
|
||||
if not from_saved:
|
||||
if not from_saved or isinstance(exc, MoodleConnectionError):
|
||||
raise
|
||||
print(f"Saved browser session is no longer valid ({exc}).", file=sys.stderr)
|
||||
if args.manual_session:
|
||||
|
||||
+61
-15
@@ -4,7 +4,6 @@ import http.client
|
||||
import http.cookiejar
|
||||
import html
|
||||
import json
|
||||
import mimetypes
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
@@ -16,7 +15,7 @@ from typing import Any
|
||||
|
||||
from .constants import DOWNLOADABLE_MODULES, USER_AGENT
|
||||
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 .paths import (
|
||||
_activity_root,
|
||||
@@ -112,15 +111,55 @@ class MoodleClient:
|
||||
detail = exc.read(500).decode("utf-8", "replace").strip()
|
||||
raise MoodleError(f"HTTP {exc.code} from {url}: {detail or exc.reason}") from exc
|
||||
except urllib.error.URLError as exc:
|
||||
raise MoodleError(f"Could not connect to {url}: {exc.reason}") from exc
|
||||
except (TimeoutError, http.client.HTTPException) as exc:
|
||||
raise MoodleError(f"connection to {url} failed: {exc}") from exc
|
||||
raise MoodleConnectionError(f"Could not connect to {url}: {exc.reason}") from exc
|
||||
except (ConnectionError, TimeoutError, http.client.HTTPException) as 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]:
|
||||
with self._request(path_or_url, **kwargs) as response:
|
||||
raw = response.read()
|
||||
charset = response.headers.get_content_charset() or "utf-8"
|
||||
return raw.decode(charset, "replace"), response.geturl(), response.headers
|
||||
def _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:
|
||||
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()
|
||||
charset = headers.get_content_charset() or "utf-8"
|
||||
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:
|
||||
if self.has_browser_session:
|
||||
@@ -387,13 +426,14 @@ class MoodleClient:
|
||||
separator = "&" if urllib.parse.urlparse(module_url).query else "?"
|
||||
inspect_url = module_url + separator + "redirect=0"
|
||||
try:
|
||||
module_page, module_final_url, headers = self._read_text(inspect_url)
|
||||
module_page, module_final_url, headers = self._read_text(inspect_url, inspect_module=True)
|
||||
except MoodleError as exc:
|
||||
if not isinstance(exc.__cause__, urllib.error.HTTPError):
|
||||
raise
|
||||
print(f"warning: skipped {activity}: {exc}", file=sys.stderr)
|
||||
continue
|
||||
content_type = headers.get_content_type() if hasattr(headers, "get_content_type") else ""
|
||||
if not (content_type.startswith("text/") or content_type in {"application/xhtml+xml", "application/xml"}):
|
||||
files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata))
|
||||
if self._is_module_file(headers):
|
||||
files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata, headers))
|
||||
continue
|
||||
self._validate_web_page(module_page, module_final_url)
|
||||
module_parser = _LinkParser(module_final_url)
|
||||
@@ -413,15 +453,21 @@ class MoodleClient:
|
||||
activity: str,
|
||||
url: str,
|
||||
metadata: tuple[dict[str, Any], dict[str, Any]] | None = None,
|
||||
headers: Any = None,
|
||||
) -> FileItem:
|
||||
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 ({}, {})
|
||||
return FileItem(
|
||||
course_id=course_id,
|
||||
section=section,
|
||||
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,
|
||||
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),
|
||||
section_id=section_metadata.get("id"),
|
||||
section_number=section_metadata.get("number"),
|
||||
|
||||
@@ -5,7 +5,7 @@ from pathlib import Path
|
||||
|
||||
DEFAULT_SITE = "https://training.ravinacademy.com"
|
||||
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
|
||||
__version__ = "0.16.3"
|
||||
__version__ = "0.16.4"
|
||||
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
|
||||
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
|
||||
LIVE_CLASS_MODULES = {"bigbluebuttonbn", "zoom", "teamsmeeting", "webexactivity"}
|
||||
|
||||
@@ -7,6 +7,10 @@ class MoodleError(RuntimeError):
|
||||
"""A friendly, expected Moodle/API error."""
|
||||
|
||||
|
||||
class MoodleConnectionError(MoodleError):
|
||||
"""A failure to connect to Moodle or finish reading its response."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Course:
|
||||
id: int
|
||||
|
||||
@@ -109,6 +109,23 @@ class CourseAssessmentTests(unittest.TestCase):
|
||||
self.assertEqual(item["kind"], "assessment")
|
||||
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:
|
||||
course = self.write_course(51)
|
||||
self.write_overlay(course)
|
||||
|
||||
@@ -11,12 +11,26 @@ from types import SimpleNamespace
|
||||
from unittest.mock import patch
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
|
||||
from ravin.auth import _capture_browser_session, _authenticated_browser_session, _select_login_tab
|
||||
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 MoodleError
|
||||
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
|
||||
|
||||
|
||||
+61
-4
@@ -12,7 +12,7 @@ from unittest.mock import patch
|
||||
|
||||
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 (
|
||||
_browser_login_url,
|
||||
_capture_browser_session,
|
||||
@@ -38,9 +38,14 @@ from ravin.scan import format_scan, scan_offline, scan_remote
|
||||
|
||||
|
||||
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.status = status
|
||||
self.length = None
|
||||
self.url = url
|
||||
self.headers = email.message.Message()
|
||||
self.headers["Content-Disposition"] = 'attachment; filename="file.bin"'
|
||||
if content_range:
|
||||
@@ -56,9 +61,9 @@ class _FakeResponse:
|
||||
return self.status
|
||||
|
||||
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:
|
||||
return b""
|
||||
value = self.chunks.pop(0)
|
||||
@@ -692,6 +697,58 @@ class ParserTests(unittest.TestCase):
|
||||
self.assertEqual(destination.read_bytes(), b"abcdexyz!!")
|
||||
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):
|
||||
response = _FakeResponse([b"67890"], status=206, content_range="bytes 5-9/10")
|
||||
client = _FakeDownloadClient([response])
|
||||
|
||||
Reference in new issue
Block a user