implement automate Ravin LMS login

This commit is contained in:
Meghdad committed 2026-08-02 22:57:40 +03:30
1 parent a3acea6457
commit 4b53e7b3ab
9 files changed
+445 -24

No files matched your search

+1
View File
@@ -1,5 +1,6 @@
# Copy this file to .env. Never commit real values. # Copy this file to .env. Never commit real values.
RAVIN_USERNAME="" RAVIN_USERNAME=""
RAVIN_PASSWORD="" RAVIN_PASSWORD=""
RAVIN_LOGIN_URL="https://lms.ravinacademy.com/"
RAVIN_USER_AGENT="" RAVIN_USER_AGENT=""
RAVIN_COOKIE="" RAVIN_COOKIE=""
+1
View File
@@ -123,6 +123,7 @@ celerybeat.pid
# Environments # Environments
.env .env
.ravin-browser-profile/
.venv .venv
env/ env/
venv/ venv/
+8
View File
@@ -2,6 +2,14 @@
All notable changes to this project will be documented here. All notable changes to this project will be documented here.
## 0.2.0 - 2026-08-02
- Add a persistent, interactive installed-browser login flow that handles Cloudflare normally.
- Start Ravin authentication at its account portal and automatically follow its Moodle handoff.
- Capture the launched browser's User-Agent and cookies and update `.env` automatically.
- Automatically reopen the authentication browser when a saved session expires.
- Keep manual request-header entry as an explicit fallback.
## 0.1.0 - 2026-08-02 ## 0.1.0 - 2026-08-02
- List enrolled Moodle courses through the mobile API or authenticated AJAX fallback. - List enrolled Moodle courses through the mobile API or authenticated AJAX fallback.
+1 -1
View File
@@ -5,7 +5,7 @@ Contributions are welcome. Keep changes focused, dependency-free where practical
## Development workflow ## Development workflow
1. Fork the repository and create a branch for the change. 1. Fork the repository and create a branch for the change.
2. Do not commit `.env`, browser cookies, passwords, downloaded course files, or private LMS responses. 2. Do not commit `.env`, `.ravin-browser-profile/`, browser cookies, passwords, downloaded course files, or private LMS responses.
3. Add or update tests for behavioral changes. 3. Add or update tests for behavioral changes.
4. Run: 4. Run:
+21 -16
View File
@@ -2,7 +2,7 @@
A dependency-free command-line client that lists your enrolled Moodle courses and downloads accessible course files. It defaults to Ravin Academy, but accepts another Moodle base URL through `--site`. A dependency-free command-line client that lists your enrolled Moodle courses and downloads accessible course files. It defaults to Ravin Academy, but accepts another Moodle base URL through `--site`.
The client first tries Moodle's official mobile web-service API and falls back to a normal web login plus Moodle's authenticated AJAX interface. For sites protected by Cloudflare, it can reuse request headers from a browser session. The client first tries Moodle's official mobile web-service API and falls back to a normal web login plus Moodle's authenticated AJAX interface. For sites protected by Cloudflare, it can establish and refresh an authenticated browser session automatically.
> [!IMPORTANT] > [!IMPORTANT]
> Use this tool only for courses and files your account is authorized to access. Respect the LMS terms, instructor permissions, and applicable copyright rules. This project does not bypass enrollment, DRM, or access controls. > Use this tool only for courses and files your account is authorized to access. Respect the LMS terms, instructor permissions, and applicable copyright rules. This project does not bypass enrollment, DRM, or access controls.
@@ -12,14 +12,14 @@ The client first tries Moodle's official mobile web-service API and falls back t
- Python 3.10 or newer - Python 3.10 or newer
- An active enrollment on the target Moodle site - An active enrollment on the target Moodle site
The runtime has no third-party Python dependencies. The downloader itself uses only Python's standard library. Automatic browser login uses the optional Selenium package with an installed Zen, Firefox, Chrome, Chromium, or Brave browser.
## Installation ## Installation
After cloning or downloading the repository, install the command from its root directory: After cloning or downloading the repository, install the command from its root directory:
```bash ```bash
python3 -m pip install . python3 -m pip install '.[browser]'
``` ```
You can then use `ravin-downloader` from any shell. Running `python3 ravin_downloader.py` directly from the repository remains supported. You can then use `ravin-downloader` from any shell. Running `python3 ravin_downloader.py` directly from the repository remains supported.
@@ -27,6 +27,7 @@ You can then use `ravin-downloader` from any shell. Running `python3 ravin_downl
## Quick start ## Quick start
```bash ```bash
ravin-downloader login
ravin-downloader courses ravin-downloader courses
ravin-downloader files COURSE_ID ravin-downloader files COURSE_ID
ravin-downloader download COURSE_ID ravin-downloader download COURSE_ID
@@ -45,6 +46,8 @@ ravin-downloader --json files COURSE_ID
On first use, missing values are requested interactively and saved in `.env` in the current directory. Copy [`.env.example`](.env.example) if you prefer to configure it manually. The file is Git-ignored and written with owner-only permissions. On first use, missing values are requested interactively and saved in `.env` in the current directory. Copy [`.env.example`](.env.example) if you prefer to configure it manually. The file is Git-ignored and written with owner-only permissions.
`ravin-downloader login` opens an installed browser using the Git-ignored `.ravin-browser-profile/` directory. For Ravin Academy it starts at `https://lms.ravinacademy.com/`, signs in there, follows the available Moodle course-launch link, and captures the resulting session on `training.ravinacademy.com`. If `.env` already contains `RAVIN_USERNAME` and `RAVIN_PASSWORD`, a compatible login form is filled automatically. Once login succeeds, the browser closes and `.env` is updated with the exact User-Agent and cookies. Use `--browser-executable /path/to/browser` to override automatic detection.
Never commit or share `.env`. It may contain both account credentials and a temporary authenticated browser session. Never commit or share `.env`. It may contain both account credentials and a temporary authenticated browser session.
If the academy disables its mobile token service, the fallback is automatic. You can force that path for troubleshooting: If the academy disables its mobile token service, the fallback is automatic. You can force that path for troubleshooting:
@@ -53,43 +56,45 @@ If the academy disables its mobile token service, the fallback is automatic. You
ravin-downloader --web-only --username YOUR_USERNAME courses ravin-downloader --web-only --username YOUR_USERNAME courses
``` ```
## When Cloudflare blocks terminal login ## Browser login and Cloudflare
Ravin Academy currently puts a Cloudflare browser check in front of both Moodle login endpoints. If the normal command reports that Cloudflare requires a real browser session: Ravin Academy protects its account portal and Moodle with a browser check. Set up the browser helper once:
1. Open the LMS in a normal browser and log in.
2. Open the browser's Developer Tools, select **Network**, and reload the LMS page.
3. Select the main `view.php` or `courses.php` request.
4. Under **Request Headers**, copy the complete `User-Agent` value and the complete `Cookie` value.
5. Run the browser-session mode:
```bash ```bash
ravin-downloader --browser-session courses python3 -m pip install '.[browser]'
ravin-downloader login
``` ```
Paste the User-Agent normally and the Cookie header into the hidden prompt. After the headers are validated, they are saved in `.env` with owner-only permissions and ignored by Git. The same file can contain all four values: After authentication, `.env` can contain these values:
```dotenv ```dotenv
RAVIN_USERNAME="your username" RAVIN_USERNAME="your username"
RAVIN_PASSWORD="your password" RAVIN_PASSWORD="your password"
RAVIN_LOGIN_URL="https://lms.ravinacademy.com/"
RAVIN_USER_AGENT="the complete browser User-Agent" RAVIN_USER_AGENT="the complete browser User-Agent"
RAVIN_COOKIE="the complete browser Cookie header" RAVIN_COOKIE="the complete browser Cookie header"
``` ```
Values entered at the script's prompts are written or updated automatically. Later commands reuse `.env`, so you can simply run: Later commands reuse `.env`, so you can simply run:
```bash ```bash
ravin-downloader files 44 ravin-downloader files 44
ravin-downloader download 44 ravin-downloader download 44
``` ```
The saved session is checked on every run. When it expires or Cloudflare rejects it, the tool asks for fresh headers and replaces the saved copy. You can force that refresh yourself with: The saved session is checked on every run. When it expires or Cloudflare rejects it, the authentication browser opens automatically and replaces the saved values. You can force that refresh yourself with:
```bash ```bash
ravin-downloader --refresh-session courses ravin-downloader --refresh-session courses
``` ```
Never send `.env`, your password, or its Cookie value to another person; they grant access to your LMS account or signed-in session. If browser automation is unavailable, manual header entry remains available as a fallback:
```bash
ravin-downloader --manual-session --refresh-session courses
```
Never send `.env`, `.ravin-browser-profile/`, your password, or its Cookie value to another person; they grant access to your LMS account or signed-in session.
## Development ## Development
+1 -1
View File
@@ -8,6 +8,6 @@ Include the affected version, a minimal reproduction using synthetic data, and t
## Credential handling ## Credential handling
The downloader may store `RAVIN_USERNAME`, `RAVIN_PASSWORD`, `RAVIN_USER_AGENT`, and `RAVIN_COOKIE` in a local `.env` file. That file is excluded from Git and created with owner-only permissions, but users are still responsible for protecting it. Browser cookies should be treated like passwords and refreshed if exposed. The downloader may store `RAVIN_USERNAME`, `RAVIN_PASSWORD`, `RAVIN_USER_AGENT`, and `RAVIN_COOKIE` in a local `.env` file. Automatic login also stores a dedicated browser profile in `.ravin-browser-profile/`. Both paths are excluded from Git, and `.env` is created with owner-only permissions, but users are still responsible for protecting them. Browser cookies should be treated like passwords and refreshed if exposed.
Only download content your account is authorized to access. This project does not support bypassing authentication, enrollment, DRM, or other access controls. Only download content your account is authorized to access. This project does not support bypassing authentication, enrollment, DRM, or other access controls.
+4 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project] [project]
name = "ravin-moodle-downloader" name = "ravin-moodle-downloader"
version = "0.1.0" version = "0.2.0"
description = "List and download authorized course files from Ravin Academy or another Moodle site" description = "List and download authorized course files from Ravin Academy or another Moodle site"
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
@@ -26,6 +26,9 @@ classifiers = [
] ]
dependencies = [] dependencies = []
[project.optional-dependencies]
browser = ["selenium>=4.46,<5"]
[project.scripts] [project.scripts]
ravin-downloader = "ravin_downloader:main" ravin-downloader = "ravin_downloader:main"
+289 -5
View File
@@ -19,6 +19,7 @@ import json
import mimetypes import mimetypes
import os import os
import re import re
import shutil
import sys import sys
import tempfile import tempfile
import time import time
@@ -32,13 +33,15 @@ from typing import Any, Iterable
DEFAULT_SITE = "https://training.ravinacademy.com" DEFAULT_SITE = "https://training.ravinacademy.com"
__version__ = "0.1.0" DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
__version__ = "0.2.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)" USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"} DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
DEFAULT_ENV_FILE = Path.cwd() / ".env" DEFAULT_ENV_FILE = Path.cwd() / ".env"
ENV_KEYS = { ENV_KEYS = {
"username": "RAVIN_USERNAME", "username": "RAVIN_USERNAME",
"password": "RAVIN_PASSWORD", "password": "RAVIN_PASSWORD",
"login_url": "RAVIN_LOGIN_URL",
"user_agent": "RAVIN_USER_AGENT", "user_agent": "RAVIN_USER_AGENT",
"cookie": "RAVIN_COOKIE", "cookie": "RAVIN_COOKIE",
} }
@@ -845,12 +848,253 @@ def _prompt_browser_session(args: argparse.Namespace, *, fresh: bool = False) ->
return user_agent, cookie_header return user_agent, cookie_header
def _find_browser_executable(explicit: Path | None = None) -> Path | None:
if explicit:
candidate = explicit.expanduser().resolve()
return candidate if candidate.is_file() else None
candidates = [
Path("/Applications/Zen.app/Contents/MacOS/zen"),
Path("/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"),
Path("/Applications/Chromium.app/Contents/MacOS/Chromium"),
Path("/Applications/Brave Browser.app/Contents/MacOS/Brave Browser"),
Path("/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge"),
Path("/Applications/Firefox.app/Contents/MacOS/firefox"),
]
for command in ("zen", "firefox", "google-chrome", "chromium", "chromium-browser", "brave-browser"):
found = shutil.which(command)
if found:
candidates.append(Path(found))
return next((candidate for candidate in candidates if candidate.is_file()), None)
def _browser_login_url(args: argparse.Namespace) -> str:
configured = getattr(args, "login_url", None) or _env_value(args, ENV_KEYS["login_url"])
if configured:
return configured
hostname = (urllib.parse.urlsplit(args.site).hostname or "").casefold()
if hostname == "training.ravinacademy.com":
return DEFAULT_RAVIN_LOGIN_URL
return urllib.parse.urljoin(args.site.rstrip("/") + "/", "my/courses.php")
def _capture_browser_session(args: argparse.Namespace) -> tuple[str, str]:
"""Open an installed browser through Selenium and capture its authenticated session."""
try:
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
from selenium.webdriver.common.by import By
except ImportError as exc:
raise MoodleError(
"automatic browser login is not installed. Run:\n"
" python3 -m pip install 'ravin-moodle-downloader[browser]'"
) from exc
executable = _find_browser_executable(args.browser_executable)
if executable is None:
raise MoodleError(
"no supported browser was found. Install Firefox/Zen/Chrome, or pass "
"--browser-executable /path/to/browser"
)
profile = args.browser_profile.expanduser().resolve()
profile.mkdir(parents=True, exist_ok=True, mode=0o700)
try:
os.chmod(profile, 0o700)
except OSError:
pass
browser_name = executable.name.casefold()
try:
if "firefox" in browser_name or "zen" in browser_name:
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
options = Options()
options.binary_location = str(executable)
options.add_argument("-profile")
options.add_argument(str(profile))
driver_path = shutil.which("geckodriver")
service = Service(executable_path=driver_path) if driver_path else Service()
driver = webdriver.Firefox(options=options, service=service)
else:
from selenium.webdriver.chrome.options import Options
options = Options()
options.binary_location = str(executable)
options.add_argument(f"--user-data-dir={profile}")
options.add_argument("--no-first-run")
driver = webdriver.Chrome(options=options)
except WebDriverException as exc:
raise MoodleError(
f"could not launch {executable.name}: {exc}. "
"Selenium Manager may need network access once to install the matching driver."
) from exc
login_url = _browser_login_url(args)
username = _env_value(args, ENV_KEYS["username"])
password = _env_value(args, ENV_KEYS["password"])
deadline = time.monotonic() + max(args.login_timeout, 30)
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)
try:
driver.get(login_url)
submitted_credentials = False
credential_attempts = 0
last_location = ""
while time.monotonic() < deadline:
current_location = urllib.parse.urlsplit(driver.current_url)._replace(query="", fragment="").geturl()
if current_location != last_location:
print(f"Browser is at {current_location}", file=sys.stderr)
last_location = current_location
try:
logged_in = bool(
driver.execute_script(
"""return Boolean(
window.M && M.cfg && Number(M.cfg.userId) > 0 &&
document.querySelector('a[href*="/login/logout.php"]')
);"""
)
)
except WebDriverException:
logged_in = False
if logged_in:
cookies = driver.get_cookies()
user_agent = str(driver.execute_script("return navigator.userAgent;"))
cookie_header = "; ".join(
f"{cookie['name']}={cookie['value']}"
for cookie in 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 user_agent, cookie_header
# Ravin's account portal owns the login. Its Moodle launch link creates
# the session on training.ravinacademy.com and redirects there.
launch_links = driver.find_elements(
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)
driver.get(launch_urls[0])
submitted_credentials = False
continue
if submitted_credentials:
error_elements = driver.find_elements(
By.CSS_SELECTOR,
".loginerrors, .alert-danger, .invalid-feedback, "
".field-validation-error, .error-message, .toast-error, "
".swal2-validation-message, [data-region=\"login-error\"], [role=\"alert\"]",
)
error_messages = [
" ".join(element.text.split())
for element in error_elements
if element.is_displayed() and element.text.strip()
]
if error_messages:
if credential_attempts >= 3:
raise MoodleError(f"the LMS rejected the login: {error_messages[0][:300]}")
print(f"The LMS rejected the saved login: {error_messages[0][:300]}", file=sys.stderr)
print("Enter fresh credentials in this terminal.", file=sys.stderr)
username, password = _credentials(args, fresh=True)
_save_env_values(
args.env_file,
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
},
)
args.env_values.update(
{
ENV_KEYS["username"]: username,
ENV_KEYS["password"]: password,
}
)
submitted_credentials = False
if username and password and not submitted_credentials:
login_controls = driver.execute_script(
"""const visible = (element) => {
const style = window.getComputedStyle(element);
const box = element.getBoundingClientRect();
return !element.disabled && style.display !== 'none' &&
style.visibility !== 'hidden' && box.width > 0 && box.height > 0;
};
const passwords = [...document.querySelectorAll('input[type="password"]')]
.filter(visible);
if (passwords.length !== 1) return null;
const password = passwords[0];
const form = password.form || password.closest('form');
if (!form) return null;
const candidates = [...form.querySelectorAll('input')].filter((element) => {
const type = (element.type || 'text').toLowerCase();
return visible(element) && ![
'password', 'hidden', 'submit', 'button', 'checkbox',
'radio', 'file', 'reset'
].includes(type);
});
const preferred = /user|mobile|phone|email|login|national/i;
const username = candidates.find((element) => preferred.test(
`${element.name} ${element.id} ${element.autocomplete}`
)) || candidates[0];
const submits = [...form.querySelectorAll('button, input[type="submit"]')]
.filter((element) => visible(element) && element.type === 'submit');
return username && submits.length ? [username, password, submits[0]] : null;"""
)
if login_controls:
username_input, password_input, submit_button = login_controls
driver.execute_script(
"""const setValue = (element, value) => {
const setter = Object.getOwnPropertyDescriptor(
HTMLInputElement.prototype, 'value'
).set;
setter.call(element, value);
element.dispatchEvent(new Event('input', {bubbles: true}));
element.dispatchEvent(new Event('change', {bubbles: true}));
};
setValue(arguments[0], arguments[1]);
setValue(arguments[2], arguments[3]);
const form = arguments[0].closest('form');
if (form && form.requestSubmit) {
form.requestSubmit(arguments[4]);
} else {
arguments[4].click();
}""",
username_input,
username,
password_input,
password,
submit_button,
)
submitted_credentials = True
credential_attempts += 1
print("Submitted the stored LMS credentials.", file=sys.stderr)
time.sleep(1)
raise MoodleError(f"browser login did not finish within {max(args.login_timeout, 30)} seconds")
except WebDriverException as exc:
raise MoodleError(f"browser authentication failed: {exc}") from exc
finally:
driver.quit()
def _authenticate_browser_session( def _authenticate_browser_session(
args: argparse.Namespace, args: argparse.Namespace,
saved: tuple[str, str] | None = None, saved: tuple[str, str] | None = None,
) -> tuple[MoodleClient, str]: ) -> tuple[MoodleClient, str]:
from_saved = saved is not None and not args.refresh_session from_saved = saved is not None and not args.refresh_session
user_agent, cookie_header = saved if from_saved else _prompt_browser_session(args) if from_saved:
user_agent, cookie_header = saved
elif args.manual_session:
user_agent, cookie_header = _prompt_browser_session(args, fresh=True)
else:
user_agent, cookie_header = _capture_browser_session(args)
client = MoodleClient( client = MoodleClient(
args.site, args.site,
cookie_header=cookie_header, cookie_header=cookie_header,
@@ -862,8 +1106,12 @@ def _authenticate_browser_session(
if not from_saved: if not from_saved:
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:
print("Please paste fresh headers from a logged-in browser request.", file=sys.stderr) print("Please paste fresh headers from a logged-in browser request.", file=sys.stderr)
user_agent, cookie_header = _prompt_browser_session(args, fresh=True) user_agent, cookie_header = _prompt_browser_session(args, fresh=True)
else:
print("Opening the authentication browser to refresh it.", file=sys.stderr)
user_agent, cookie_header = _capture_browser_session(args)
client = MoodleClient( client = MoodleClient(
args.site, args.site,
cookie_header=cookie_header, cookie_header=cookie_header,
@@ -873,12 +1121,14 @@ def _authenticate_browser_session(
_save_env_values( _save_env_values(
args.env_file, args.env_file,
{ {
ENV_KEYS["login_url"]: _browser_login_url(args),
ENV_KEYS["user_agent"]: user_agent, ENV_KEYS["user_agent"]: user_agent,
ENV_KEYS["cookie"]: cookie_header, ENV_KEYS["cookie"]: cookie_header,
}, },
) )
args.env_values.update( args.env_values.update(
{ {
ENV_KEYS["login_url"]: _browser_login_url(args),
ENV_KEYS["user_agent"]: user_agent, ENV_KEYS["user_agent"]: user_agent,
ENV_KEYS["cookie"]: cookie_header, ENV_KEYS["cookie"]: cookie_header,
} }
@@ -902,12 +1152,19 @@ def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.") parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}") parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})") parser.add_argument("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})")
parser.add_argument(
"--login-url",
help=(
"account portal used for browser login; defaults to "
f"{DEFAULT_RAVIN_LOGIN_URL} for Ravin Academy"
),
)
parser.add_argument("--username", help="LMS username; password is prompted securely") parser.add_argument("--username", help="LMS username; password is prompted securely")
parser.add_argument("--web-only", action="store_true", help="skip the Moodle mobile API and use a normal web session") parser.add_argument("--web-only", action="store_true", help="skip the Moodle mobile API and use a normal web session")
parser.add_argument( parser.add_argument(
"--browser-session", "--browser-session",
action="store_true", action="store_true",
help="reuse request headers from an already logged-in browser (works with Cloudflare)", help="force saved or automatic browser-session authentication",
) )
parser.add_argument( parser.add_argument(
"--browser-user-agent", "--browser-user-agent",
@@ -922,11 +1179,34 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument( parser.add_argument(
"--refresh-session", "--refresh-session",
action="store_true", action="store_true",
help="ignore the saved browser session and ask for fresh headers", help="ignore the saved browser session and open the authentication browser",
)
parser.add_argument(
"--manual-session",
action="store_true",
help="prompt for User-Agent and Cookie headers instead of opening a browser",
)
parser.add_argument(
"--browser-profile",
type=Path,
default=Path.cwd() / ".ravin-browser-profile",
help="persistent profile for automatic browser login",
)
parser.add_argument(
"--browser-executable",
type=Path,
help="installed Zen, Firefox, Chrome, Chromium, or Brave executable",
)
parser.add_argument(
"--login-timeout",
type=int,
default=600,
help="seconds to wait for interactive browser login (default: 600)",
) )
parser.add_argument("--json", action="store_true", help="print machine-readable JSON") parser.add_argument("--json", action="store_true", help="print machine-readable JSON")
subparsers = parser.add_subparsers(dest="command", required=True) subparsers = parser.add_subparsers(dest="command", required=True)
subparsers.add_parser("login", help="open a browser and refresh the saved LMS session")
subparsers.add_parser("courses", help="list enrolled courses") subparsers.add_parser("courses", help="list enrolled courses")
files_parser = subparsers.add_parser("files", help="list downloadable files in a course") files_parser = subparsers.add_parser("files", help="list downloadable files in a course")
files_parser.add_argument("course_id", type=int) files_parser.add_argument("course_id", type=int)
@@ -943,6 +1223,10 @@ def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv) args = build_parser().parse_args(argv)
try: try:
args.env_values = _load_env_file(args.env_file) args.env_values = _load_env_file(args.env_file)
if args.command == "login":
client, mode = _authenticate_browser_session(args)
print(f"Authenticated using {mode}; updated {args.env_file}.")
return 0
saved_session = _browser_session_values(args, fresh=args.refresh_session) saved_session = _browser_session_values(args, fresh=args.refresh_session)
if args.browser_session or args.refresh_session or saved_session is not None: if args.browser_session or args.refresh_session or saved_session is not None:
client, mode = _authenticate_browser_session(args, saved_session) client, mode = _authenticate_browser_session(args, saved_session)
@@ -967,7 +1251,7 @@ def main(argv: list[str] | None = None) -> int:
except MoodleError as exc: except MoodleError as exc:
if "cloudflare requires a real browser session" not in str(exc).casefold(): if "cloudflare requires a real browser session" not in str(exc).casefold():
raise raise
print("Cloudflare blocked password login; switching to a saved browser session.", file=sys.stderr) print("Cloudflare blocked password login; opening the authentication browser.", file=sys.stderr)
client, mode = _authenticate_browser_session(args) client, mode = _authenticate_browser_session(args)
print(f"Authenticated using {mode}.", file=sys.stderr) print(f"Authenticated using {mode}.", file=sys.stderr)
+119
View File
@@ -1,9 +1,13 @@
import email.message import email.message
import http.client import http.client
import os import os
import sys
import tempfile import tempfile
import types
import unittest import unittest
from pathlib import Path from pathlib import Path
from types import SimpleNamespace
from unittest.mock import patch
from ravin_downloader import ( from ravin_downloader import (
FileItem, FileItem,
@@ -11,12 +15,15 @@ from ravin_downloader import (
_FormParser, _FormParser,
_LinkParser, _LinkParser,
_clean_name, _clean_name,
_browser_login_url,
_capture_browser_session,
_filename_from_headers, _filename_from_headers,
_is_cloudflare_challenge, _is_cloudflare_challenge,
_load_env_file, _load_env_file,
_parse_moodle_config, _parse_moodle_config,
_save_env_values, _save_env_values,
_unique, _unique,
build_parser,
) )
@@ -62,6 +69,118 @@ class _FakeDownloadClient(MoodleClient):
class ParserTests(unittest.TestCase): class ParserTests(unittest.TestCase):
def test_login_command_parses_without_course_id(self):
args = build_parser().parse_args(["login"])
self.assertEqual(args.command, "login")
self.assertFalse(args.manual_session)
def test_browser_login_captures_user_agent_and_cookies(self):
class FakeLaunchLink:
def is_displayed(self):
return True
def get_attribute(self, name):
if name == "href":
return "https://lms.example/moodle/login_student_user/162/"
return None
class FakeDriver:
current_url = "about:blank"
def get(self, url):
if "/moodle/login_student_user/" in url:
self.current_url = "https://training.example/my/"
else:
self.current_url = url
def execute_script(self, expression):
if "navigator.userAgent" in expression:
return "Synthetic Browser/1"
return self.current_url == "https://training.example/my/"
def find_elements(self, _by, selector):
if "login_student_user" in selector and self.current_url == "https://lms.example/":
return [FakeLaunchLink()]
return []
def get_cookies(self):
return [
{"name": "MoodleSession", "value": "synthetic"},
{"name": "cf_clearance", "value": "synthetic"},
]
def quit(self):
return None
class FakeOptions:
binary_location = ""
def add_argument(self, _argument):
return None
class FakeService:
def __init__(self, **_kwargs):
return None
fake_webdriver = SimpleNamespace(
Firefox=lambda **_kwargs: FakeDriver(),
Chrome=lambda **_kwargs: FakeDriver(),
)
fake_selenium = types.ModuleType("selenium")
fake_selenium.webdriver = fake_webdriver
fake_common = types.ModuleType("selenium.common")
fake_exceptions = types.ModuleType("selenium.common.exceptions")
fake_exceptions.WebDriverException = RuntimeError
fake_webdriver_module = types.ModuleType("selenium.webdriver")
fake_webdriver_common = types.ModuleType("selenium.webdriver.common")
fake_by = types.ModuleType("selenium.webdriver.common.by")
fake_by.By = SimpleNamespace(CSS_SELECTOR="css selector")
fake_firefox = types.ModuleType("selenium.webdriver.firefox")
fake_firefox_options = types.ModuleType("selenium.webdriver.firefox.options")
fake_firefox_options.Options = FakeOptions
fake_firefox_service = types.ModuleType("selenium.webdriver.firefox.service")
fake_firefox_service.Service = FakeService
with tempfile.TemporaryDirectory() as directory:
executable = Path(directory) / "zen"
executable.touch()
args = SimpleNamespace(
site="https://training.example",
login_url="https://lms.example/",
browser_profile=Path(directory) / "profile",
browser_executable=executable,
login_timeout=30,
env_values={},
)
with patch.dict(
sys.modules,
{
"selenium": fake_selenium,
"selenium.common": fake_common,
"selenium.common.exceptions": fake_exceptions,
"selenium.webdriver": fake_webdriver_module,
"selenium.webdriver.common": fake_webdriver_common,
"selenium.webdriver.common.by": fake_by,
"selenium.webdriver.firefox": fake_firefox,
"selenium.webdriver.firefox.options": fake_firefox_options,
"selenium.webdriver.firefox.service": fake_firefox_service,
},
):
user_agent, cookie_header = _capture_browser_session(args)
self.assertEqual(user_agent, "Synthetic Browser/1")
self.assertEqual(
cookie_header,
"MoodleSession=synthetic; cf_clearance=synthetic",
)
def test_ravin_browser_login_starts_at_account_portal(self):
args = SimpleNamespace(
site="https://training.ravinacademy.com",
login_url=None,
env_values={},
)
self.assertEqual(_browser_login_url(args), "https://lms.ravinacademy.com/")
def test_parses_login_form_and_hidden_token(self): def test_parses_login_form_and_hidden_token(self):
parser = _FormParser() parser = _FormParser()
parser.feed( parser.feed(