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
This commit is contained in:
Meghdad committed 2026-10-08 02:19:26 +03:30
1 parent ff467ab2ea
commit 3e37df980c
10 files changed
+632 -44

No files matched your search

+22
View File
@@ -2,6 +2,28 @@
All notable changes to this project will be documented here. All notable changes to this project will be documented here.
## 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.
+19
View File
@@ -118,6 +118,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
+2 -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.3"
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,7 +24,7 @@ classifiers = [
"Programming Language :: Python :: 3.14", "Programming Language :: Python :: 3.14",
"Topic :: Education", "Topic :: Education",
] ]
dependencies = ["selenium>=4.46,<5", "argcomplete>=3.6,<4"] 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"] pdf = ["playwright>=1.50,<2", "markdown-it-py>=3,<5"]
+6 -5
View File
@@ -99,6 +99,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 +108,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,6 +134,7 @@ 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"],
+229 -30
View File
@@ -17,6 +17,10 @@ from .constants import DEFAULT_RAVIN_LOGIN_URL, ENV_KEYS
from .models import MoodleError from .models import 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:
return os.environ.get(key) or args.env_values.get(key, "") return os.environ.get(key) or args.env_values.get(key, "")
@@ -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:
+29 -5
View File
@@ -2,6 +2,7 @@
import http.client import http.client
import http.cookiejar import http.cookiejar
import html
import json import json
import mimetypes import mimetypes
import re import re
@@ -233,6 +234,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 +298,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 +351,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:
@@ -392,6 +395,7 @@ class MoodleClient:
if not (content_type.startswith("text/") or content_type in {"application/xhtml+xml", "application/xml"}): 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)) 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)
@@ -432,12 +436,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,
+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.3"
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"}
+29
View File
@@ -130,6 +130,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")
+285
View File
@@ -0,0 +1,285 @@
"""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 _capture_browser_session, _authenticated_browser_session, _select_login_tab
from ravin.client import MoodleClient
from ravin.models import MoodleError
class BrowserUpdateTests(unittest.TestCase):
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()
+10 -1
View File
@@ -149,6 +149,12 @@ class ParserTests(unittest.TestCase):
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
@@ -159,6 +165,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:
@@ -173,7 +181,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):
@@ -204,6 +212,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")