From 45392c14b9c01b29ff85cbf9a19eb6e5d1df4483 Mon Sep 17 00:00:00 2001
From: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com>
Date: Sun, 22 Nov 2026 17:57:04 +0330
Subject: [PATCH] skip file bodies during Moodle activity scans
---
CHANGELOG.md | 6 ++++
CONTRIBUTING.md | 6 ++++
README.md | 3 ++
public/course.html | 2 +-
public/index.html | 2 +-
pyproject.toml | 2 +-
src/ravin/assessments.py | 7 ++--
src/ravin/auth.py | 4 +--
src/ravin/client.py | 76 +++++++++++++++++++++++++++++++--------
src/ravin/constants.py | 2 +-
src/ravin/models.py | 4 +++
tests/test_assessments.py | 17 +++++++++
tests/test_auth_update.py | 18 ++++++++--
tests/test_ravin.py | 65 ++++++++++++++++++++++++++++++---
14 files changed, 184 insertions(+), 30 deletions(-)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e8ec1ec..d0bbb03 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6478517..d6ec318 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -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.
diff --git a/README.md b/README.md
index 8f7b981..2c01fba 100644
--- a/README.md
+++ b/README.md
@@ -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
diff --git a/public/course.html b/public/course.html
index 3086590..59e8640 100644
--- a/public/course.html
+++ b/public/course.html
@@ -6,7 +6,7 @@
Course ยท Learning Library
-
+
diff --git a/public/index.html b/public/index.html
index 9235fcc..e520422 100644
--- a/public/index.html
+++ b/public/index.html
@@ -6,7 +6,7 @@
Learning Library
-
+
diff --git a/pyproject.toml b/pyproject.toml
index a8154fb..6449325 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -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"
diff --git a/src/ravin/assessments.py b/src/ravin/assessments.py
index f6ffd85..0c5ebe7 100644
--- a/src/ravin/assessments.py
+++ b/src/ravin/assessments.py
@@ -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,
diff --git a/src/ravin/auth.py b/src/ravin/auth.py
index 343a6b6..ef4053e 100644
--- a/src/ravin/auth.py
+++ b/src/ravin/auth.py
@@ -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:
diff --git a/src/ravin/client.py b/src/ravin/client.py
index c3246a0..b200414 100644
--- a/src/ravin/client.py
+++ b/src/ravin/client.py
@@ -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"),
diff --git a/src/ravin/constants.py b/src/ravin/constants.py
index 85cf2dd..07910e5 100644
--- a/src/ravin/constants.py
+++ b/src/ravin/constants.py
@@ -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"}
diff --git a/src/ravin/models.py b/src/ravin/models.py
index 3af1c94..f149837 100644
--- a/src/ravin/models.py
+++ b/src/ravin/models.py
@@ -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
diff --git a/tests/test_assessments.py b/tests/test_assessments.py
index cdecd62..0c3fe3a 100644
--- a/tests/test_assessments.py
+++ b/tests/test_assessments.py
@@ -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)
diff --git a/tests/test_auth_update.py b/tests/test_auth_update.py
index 73f441e..af2694f 100644
--- a/tests/test_auth_update.py
+++ b/tests/test_auth_update.py
@@ -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
diff --git a/tests/test_ravin.py b/tests/test_ravin.py
index 8087ee0..8b9da6e 100644
--- a/tests/test_ravin.py
+++ b/tests/test_ravin.py
@@ -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"""
+