commit 6acde30753d790d1edd9d0576ccfe7e8b70ba15c Author: Meghdad <61308304+MeghdadFadaee@users.noreply.github.com> Date: Sun Aug 2 21:22:26 2026 +0330 init diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..983850f --- /dev/null +++ b/.gitignore @@ -0,0 +1,164 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ +temp/ +output.* + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +.idea/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..70d3a46 --- /dev/null +++ b/README.md @@ -0,0 +1,34 @@ +# Ravin Academy course downloader + +This small, dependency-free command-line tool lists the Moodle courses available to your account and downloads the files in a selected course. It first tries Moodle's official mobile web-service API and automatically falls back to a normal web login plus Moodle's own authenticated AJAX interface. + +Your password is read with a hidden prompt and is never written to disk. + +## Usage + +Python 3.10 or newer is recommended. + +```bash +python3 ravin_downloader.py --username YOUR_USERNAME courses +python3 ravin_downloader.py --username YOUR_USERNAME files 44 +python3 ravin_downloader.py --username YOUR_USERNAME download 44 +``` + +Files are saved under `downloads//...`. Existing completed files are skipped; interrupted downloads use a temporary `.part` suffix. Use `--overwrite` if you want to replace existing files. + +For scripting, credentials can be supplied for the current shell process and output can be JSON: + +```bash +RAVIN_USERNAME='your-user' RAVIN_PASSWORD='your-password' \ + python3 ravin_downloader.py --json courses +``` + +Avoid putting the password directly in shell history. Prefer the normal hidden password prompt when working interactively. + +If the academy disables its mobile token service, the fallback is automatic. You can force that path for troubleshooting: + +```bash +python3 ravin_downloader.py --web-only --username YOUR_USERNAME courses +``` + +The tool only requests content that the supplied account is already authorized to view. It does not bypass enrollment, permissions, DRM, or access controls. diff --git a/ravin_downloader.py b/ravin_downloader.py new file mode 100644 index 0000000..bbc18bf --- /dev/null +++ b/ravin_downloader.py @@ -0,0 +1,634 @@ +#!/usr/bin/env python3 +"""List and download files from an enrolled Moodle course. + +The client prefers Moodle's documented mobile web-service API. If that +service is disabled by the site administrator, it falls back to an ordinary +web login plus the same AJAX endpoint used by Moodle's "My courses" page. + +Only Python's standard library is required. +""" + +from __future__ import annotations + +import argparse +import getpass +import html +import http.cookiejar +import json +import mimetypes +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import asdict, dataclass +from html.parser import HTMLParser +from pathlib import Path +from typing import Any, Iterable + + +DEFAULT_SITE = "https://training.ravinacademy.com" +USER_AGENT = "RavinCourseDownloader/1.0 (+personal Moodle client)" +DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"} + + +class MoodleError(RuntimeError): + """A friendly, expected Moodle/API error.""" + + +@dataclass(frozen=True) +class Course: + id: int + fullname: str + shortname: str = "" + + +@dataclass(frozen=True) +class FileItem: + course_id: int + section: str + activity: str + filename: str + url: str + mimetype: str = "" + filesize: int | None = None + + +class _FormParser(HTMLParser): + def __init__(self) -> None: + super().__init__(convert_charrefs=True) + self.forms: list[dict[str, Any]] = [] + self._form: dict[str, Any] | None = None + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + values = dict(attrs) + if tag == "form": + self._form = { + "action": values.get("action", ""), + "method": values.get("method", "get").lower(), + "inputs": {}, + } + elif tag == "input" and self._form is not None: + name = values.get("name") + if name: + self._form["inputs"][name] = values.get("value", "") + + def handle_endtag(self, tag: str) -> None: + if tag == "form" and self._form is not None: + self.forms.append(self._form) + self._form = None + + +class _LinkParser(HTMLParser): + """Collect links and embedded media without keeping the whole DOM.""" + + MEDIA_ATTRIBUTES = { + "source": "src", + "video": "src", + "audio": "src", + "track": "src", + "embed": "src", + "iframe": "src", + "object": "data", + } + + def __init__(self, base_url: str) -> None: + super().__init__(convert_charrefs=True) + self.base_url = base_url + self.links: list[tuple[str, str]] = [] + self.media: list[str] = [] + self.title = "" + self._anchor_href: str | None = None + self._anchor_text: list[str] = [] + self._in_title = False + self._title_text: list[str] = [] + + def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: + values = dict(attrs) + if tag == "a" and values.get("href"): + self._anchor_href = urllib.parse.urljoin(self.base_url, values["href"] or "") + self._anchor_text = [] + if tag == "title": + self._in_title = True + media_attr = self.MEDIA_ATTRIBUTES.get(tag) + if media_attr and values.get(media_attr): + self.media.append(urllib.parse.urljoin(self.base_url, values[media_attr] or "")) + + def handle_data(self, data: str) -> None: + if self._anchor_href is not None: + self._anchor_text.append(data) + if self._in_title: + self._title_text.append(data) + + def handle_endtag(self, tag: str) -> None: + if tag == "a" and self._anchor_href is not None: + label = " ".join("".join(self._anchor_text).split()) + self.links.append((self._anchor_href, label)) + self._anchor_href = None + self._anchor_text = [] + if tag == "title": + self._in_title = False + self.title = " ".join("".join(self._title_text).split()) + + +def _parse_moodle_config(page: str) -> dict[str, Any]: + match = re.search(r"\bM\.cfg\s*=\s*", page) + if not match: + return {} + start = page.find("{", match.end()) + if start < 0: + return {} + depth = 0 + in_string = False + escaped = False + end = -1 + for index in range(start, len(page)): + character = page[index] + if in_string: + if escaped: + escaped = False + elif character == "\\": + escaped = True + elif character == '"': + in_string = False + continue + if character == '"': + in_string = True + elif character == "{": + depth += 1 + elif character == "}": + depth -= 1 + if depth == 0: + end = index + 1 + break + if end < 0: + return {} + try: + return json.loads(page[start:end]) + except json.JSONDecodeError: + return {} + + +def _clean_name(value: str, fallback: str = "item") -> str: + value = html.unescape(value).strip() + value = re.sub(r"[\\/:*?\"<>|\x00-\x1f]", "_", value) + value = re.sub(r"\s+", " ", value).strip(" .") + return value[:180] or fallback + + +def _filename_from_headers(headers: Any, url: str, fallback: str) -> str: + disposition = headers.get("Content-Disposition", "") + star = re.search(r"filename\*=UTF-8''([^;]+)", disposition, flags=re.I) + normal = re.search(r'filename="?([^";]+)', disposition, flags=re.I) + if star: + name = urllib.parse.unquote(star.group(1)) + elif normal: + name = normal.group(1).strip() + else: + name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name + if not name: + content_type = headers.get_content_type() if hasattr(headers, "get_content_type") else "" + extension = mimetypes.guess_extension(content_type) or "" + name = fallback + extension + return _clean_name(name, fallback) + + +def _unique(items: Iterable[FileItem]) -> list[FileItem]: + result: list[FileItem] = [] + seen: set[str] = set() + for item in items: + key = urllib.parse.urlsplit(item.url)._replace(query="", fragment="").geturl() + if key not in seen: + seen.add(key) + result.append(item) + return result + + +class MoodleClient: + def __init__(self, site: str, username: str, password: str, web_only: bool = False) -> None: + self.site = site.rstrip("/") + self.username = username + self.password = password + self.web_only = web_only + self.cookies = http.cookiejar.CookieJar() + self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookies)) + self.token: str | None = None + self.user_id: int | None = None + self.sesskey: str | None = None + self.mode = "" + + def _request( + self, + path_or_url: str, + *, + data: dict[str, Any] | bytes | None = None, + headers: dict[str, str] | None = None, + timeout: int = 45, + ) -> Any: + url = urllib.parse.urljoin(self.site + "/", path_or_url) + body: bytes | None + if isinstance(data, dict): + body = urllib.parse.urlencode(data, doseq=True).encode() + else: + body = data + request_headers = {"User-Agent": USER_AGENT, "Accept-Language": "en,fa;q=0.8"} + request_headers.update(headers or {}) + request = urllib.request.Request(url, data=body, headers=request_headers) + try: + return self.opener.open(request, timeout=timeout) + except urllib.error.HTTPError as exc: + 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 + + 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 authenticate(self) -> str: + mobile_error = "" + if not self.web_only: + try: + self._login_mobile_api() + self.mode = "mobile-api" + return self.mode + except MoodleError as exc: + mobile_error = str(exc) + + try: + self._login_web() + self.mode = "web-session" + return self.mode + except MoodleError as exc: + if mobile_error: + raise MoodleError( + f"Mobile API login was unavailable ({mobile_error}); " + f"web login also failed ({exc})." + ) from exc + raise + + def _login_mobile_api(self) -> None: + text, _, _ = self._read_text( + "/login/token.php", + data={ + "username": self.username, + "password": self.password, + "service": "moodle_mobile_app", + }, + ) + try: + payload = json.loads(text) + except json.JSONDecodeError as exc: + raise MoodleError("the token endpoint did not return JSON") from exc + token = payload.get("token") + if not token: + message = payload.get("error") or payload.get("message") or "token service rejected the login" + raise MoodleError(str(message)) + self.token = str(token) + site_info = self.api_call("core_webservice_get_site_info") + self.user_id = int(site_info["userid"]) + + def _login_web(self) -> None: + login_page, login_url, _ = self._read_text("/login/index.php") + parser = _FormParser() + parser.feed(login_page) + form = next( + (form for form in parser.forms if "username" in form["inputs"] and "password" in form["inputs"]), + None, + ) + if form is None: + raise MoodleError("could not find Moodle's login form") + fields = dict(form["inputs"]) + fields.update({"username": self.username, "password": self.password}) + action = urllib.parse.urljoin(login_url, form["action"] or "/login/index.php") + result, final_url, _ = self._read_text(action, data=fields) + result_parser = _FormParser() + result_parser.feed(result) + still_has_login = any( + "username" in item["inputs"] and "password" in item["inputs"] + for item in result_parser.forms + ) + if still_has_login or "/login/index.php" in urllib.parse.urlparse(final_url).path: + error_match = re.search( + r'class="[^"]*(?:loginerrors|alert-danger)[^"]*"[^>]*>(.*?)]+>", " ", error_match.group(1)) if error_match else "login rejected" + raise MoodleError(" ".join(html.unescape(detail).split())) + config = _parse_moodle_config(result) + self.sesskey = str(config.get("sesskey") or "") or None + if config.get("userId") is not None: + self.user_id = int(config["userId"]) + if not self.sesskey: + dashboard, _, _ = self._read_text("/my/courses.php") + config = _parse_moodle_config(dashboard) + self.sesskey = str(config.get("sesskey") or "") or None + if config.get("userId") is not None: + self.user_id = int(config["userId"]) + if not self.sesskey: + raise MoodleError("login succeeded, but Moodle's session key was not found") + + def api_call(self, function: str, **params: Any) -> Any: + if not self.token: + raise MoodleError("the mobile API is not authenticated") + fields = { + "wstoken": self.token, + "wsfunction": function, + "moodlewsrestformat": "json", + **params, + } + text, _, _ = self._read_text("/webservice/rest/server.php", data=fields) + try: + payload = json.loads(text) + except json.JSONDecodeError as exc: + raise MoodleError(f"{function} returned invalid JSON") from exc + if isinstance(payload, dict) and (payload.get("exception") or payload.get("errorcode")): + raise MoodleError(str(payload.get("message") or payload.get("errorcode"))) + return payload + + def ajax_call(self, function: str, args: dict[str, Any]) -> Any: + if not self.sesskey: + raise MoodleError("the web session is not authenticated") + body = json.dumps([{"index": 0, "methodname": function, "args": args}]).encode() + text, _, _ = self._read_text( + f"/lib/ajax/service.php?sesskey={urllib.parse.quote(self.sesskey)}&info={urllib.parse.quote(function)}", + data=body, + headers={"Content-Type": "application/json", "Accept": "application/json"}, + ) + try: + payload = json.loads(text) + except json.JSONDecodeError as exc: + raise MoodleError(f"{function} returned invalid JSON") from exc + if not isinstance(payload, list) or not payload: + raise MoodleError(f"{function} returned an unexpected response") + result = payload[0] + if result.get("error"): + exception = result.get("exception") or {} + raise MoodleError(str(exception.get("message") or exception.get("errorcode") or "AJAX error")) + return result.get("data") + + def list_courses(self) -> list[Course]: + if self.token: + if self.user_id is None: + raise MoodleError("Moodle did not return the current user ID") + payload = self.api_call("core_enrol_get_users_courses", userid=self.user_id) + courses = [ + Course(int(item["id"]), str(item.get("fullname") or item.get("displayname") or item["id"]), str(item.get("shortname") or "")) + for item in payload + ] + else: + data = self.ajax_call( + "core_course_get_enrolled_courses_by_timeline_classification", + { + "classification": "all", + "limit": 0, + "offset": 0, + "sort": "fullname", + "customfieldname": "", + "customfieldvalue": "", + "requiredfields": ["id", "fullname", "shortname", "visible", "enddate"], + }, + ) + raw_courses = data.get("courses", []) if isinstance(data, dict) else [] + courses = [ + 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 + ] + return sorted(courses, key=lambda course: course.fullname.casefold()) + + def list_files(self, course_id: int) -> list[FileItem]: + if self.token: + try: + return self._list_files_api(course_id) + except MoodleError as exc: + print(f"warning: course-content API unavailable ({exc}); using web pages", file=sys.stderr) + self._login_web() + self.token = None + self.mode = "web-session" + return self._list_files_web(course_id) + + def _list_files_api(self, course_id: int) -> list[FileItem]: + sections = self.api_call("core_course_get_contents", courseid=course_id) + files: list[FileItem] = [] + for section in sections: + section_name = str(section.get("name") or f"Section {section.get('section', '')}") + for module in section.get("modules", []): + activity = str(module.get("name") or module.get("modname") or "activity") + for content in module.get("contents", []) or []: + file_url = content.get("fileurl") + if not file_url or content.get("type", "file") != "file": + continue + files.append( + FileItem( + course_id=course_id, + section=section_name, + activity=activity, + filename=str(content.get("filename") or "file"), + url=str(file_url), + mimetype=str(content.get("mimetype") or ""), + filesize=int(content["filesize"]) if content.get("filesize") is not None else None, + ) + ) + return _unique(files) + + def _list_files_web(self, course_id: int) -> list[FileItem]: + page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}") + parser = _LinkParser(final_url) + parser.feed(page) + module_links: list[tuple[str, str]] = [] + direct_files: list[FileItem] = [] + for url, label in parser.links: + parsed = urllib.parse.urlparse(url) + module_match = re.search(r"/mod/([^/]+)/view\.php$", parsed.path) + if module_match and module_match.group(1) in DOWNLOADABLE_MODULES: + module_links.append((url, label or module_match.group(1))) + elif "/pluginfile.php/" in parsed.path: + direct_files.append(self._web_file_item(course_id, "Course files", label, url)) + for url in parser.media: + if "/pluginfile.php/" in urllib.parse.urlparse(url).path: + direct_files.append(self._web_file_item(course_id, "Course files", "media", url)) + + files = list(direct_files) + seen_modules: set[str] = set() + for module_url, activity in module_links: + module_key = urllib.parse.urlsplit(module_url)._replace(query=urllib.parse.urlencode(dict(urllib.parse.parse_qsl(urllib.parse.urlsplit(module_url).query))), fragment="").geturl() + if module_key in seen_modules: + continue + seen_modules.add(module_key) + 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) + except MoodleError as exc: + 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)) + continue + module_parser = _LinkParser(module_final_url) + module_parser.feed(module_page) + candidates = list(module_parser.media) + candidates.extend(url for url, _ in module_parser.links) + for candidate in candidates: + candidate_path = urllib.parse.urlparse(candidate).path + if "/pluginfile.php/" in candidate_path or "/webservice/pluginfile.php/" in candidate_path: + files.append(self._web_file_item(course_id, "Course files", activity, candidate)) + return _unique(files) + + def _web_file_item(self, course_id: int, section: str, activity: str, url: str) -> FileItem: + path_name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name + return FileItem( + course_id=course_id, + section=section, + activity=activity or path_name, + filename=path_name or _clean_name(activity), + url=url, + ) + + def download(self, item: FileItem, root: Path, overwrite: bool = False) -> Path: + section = _clean_name(item.section, "Course files") + activity = _clean_name(item.activity, "activity") + directory = root / _clean_name(str(item.course_id), "course") / section + directory.mkdir(parents=True, exist_ok=True) + + url = item.url + if self.token: + parts = urllib.parse.urlsplit(url) + query = dict(urllib.parse.parse_qsl(parts.query, keep_blank_values=True)) + query.setdefault("token", self.token) + url = parts._replace(query=urllib.parse.urlencode(query)).geturl() + + with self._request(url, timeout=120) as response: + filename = _filename_from_headers(response.headers, response.geturl(), activity) + destination = directory / filename + if destination.exists() and not overwrite: + return destination + temporary = destination.with_name(destination.name + ".part") + total = response.headers.get("Content-Length") + expected = int(total) if total and total.isdigit() else None + downloaded = 0 + started = time.monotonic() + with temporary.open("wb") as output: + while True: + chunk = response.read(1024 * 1024) + if not chunk: + break + output.write(chunk) + downloaded += len(chunk) + if sys.stderr.isatty(): + if expected: + status = f"{downloaded / expected:6.1%}" + else: + status = f"{downloaded / 1024 / 1024:7.1f} MiB" + print(f"\r {status} {filename[:60]}", end="", file=sys.stderr, flush=True) + if expected is not None and downloaded != expected: + temporary.unlink(missing_ok=True) + raise MoodleError(f"incomplete download for {filename}: got {downloaded} of {expected} bytes") + temporary.replace(destination) + if sys.stderr.isatty(): + elapsed = max(time.monotonic() - started, 0.01) + rate = downloaded / 1024 / 1024 / elapsed + print(f"\r done {downloaded / 1024 / 1024:7.1f} MiB ({rate:.1f} MiB/s) {filename}", file=sys.stderr) + return destination + + +def _credentials(args: argparse.Namespace) -> tuple[str, str]: + username = args.username or os.environ.get("RAVIN_USERNAME") + password = os.environ.get("RAVIN_PASSWORD") + if not username: + username = input("LMS username: ").strip() + if not password: + password = getpass.getpass("LMS password: ") + if not username or not password: + raise MoodleError("username and password are required") + return username, password + + +def _format_size(size: int | None) -> str: + if size is None: + return "?" + units = ["B", "KiB", "MiB", "GiB"] + value = float(size) + for unit in units: + if value < 1024 or unit == units[-1]: + return f"{value:.1f} {unit}" + value /= 1024 + return str(size) + + +def build_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.") + parser.add_argument("--site", default=DEFAULT_SITE, help=f"Moodle base URL (default: {DEFAULT_SITE})") + 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("--json", action="store_true", help="print machine-readable JSON") + subparsers = parser.add_subparsers(dest="command", required=True) + + subparsers.add_parser("courses", help="list enrolled courses") + files_parser = subparsers.add_parser("files", help="list downloadable files in a course") + files_parser.add_argument("course_id", type=int) + + download_parser = subparsers.add_parser("download", help="download files from one course") + download_parser.add_argument("course_id", type=int) + download_parser.add_argument("--output", type=Path, default=Path("downloads")) + download_parser.add_argument("--overwrite", action="store_true") + return parser + + +def main(argv: list[str] | None = None) -> int: + args = build_parser().parse_args(argv) + try: + username, password = _credentials(args) + client = MoodleClient(args.site, username, password, web_only=args.web_only) + mode = client.authenticate() + print(f"Authenticated using {mode}.", file=sys.stderr) + + if args.command == "courses": + courses = client.list_courses() + if args.json: + print(json.dumps([asdict(course) for course in courses], ensure_ascii=False, indent=2)) + else: + for course in courses: + suffix = f" [{course.shortname}]" if course.shortname else "" + print(f"{course.id:>6} {course.fullname}{suffix}") + return 0 + + files = client.list_files(args.course_id) + if args.command == "files": + if args.json: + print(json.dumps([asdict(item) for item in files], ensure_ascii=False, indent=2)) + else: + for number, item in enumerate(files, 1): + print(f"{number:>3}. {_format_size(item.filesize):>10} {item.section} / {item.activity} / {item.filename}") + return 0 + + if not files: + print("No downloadable files were found.") + return 0 + downloaded: list[str] = [] + for number, item in enumerate(files, 1): + print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr) + path = client.download(item, args.output, overwrite=args.overwrite) + downloaded.append(str(path)) + if args.json: + print(json.dumps(downloaded, ensure_ascii=False, indent=2)) + else: + print(f"Downloaded {len(downloaded)} file(s) to {args.output.resolve()}") + return 0 + except (MoodleError, KeyboardInterrupt) as exc: + if isinstance(exc, KeyboardInterrupt): + print("\nCancelled.", file=sys.stderr) + else: + print(f"error: {exc}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/test_ravin_downloader.py b/test_ravin_downloader.py new file mode 100644 index 0000000..5013626 --- /dev/null +++ b/test_ravin_downloader.py @@ -0,0 +1,55 @@ +import email.message +import unittest + +from ravin_downloader import ( + FileItem, + _FormParser, + _LinkParser, + _clean_name, + _filename_from_headers, + _parse_moodle_config, + _unique, +) + + +class ParserTests(unittest.TestCase): + def test_parses_login_form_and_hidden_token(self): + parser = _FormParser() + parser.feed( + '
' + '' + '
' + ) + self.assertEqual(parser.forms[0]["inputs"]["logintoken"], "abc") + self.assertEqual(parser.forms[0]["method"], "post") + + def test_parses_moodle_config(self): + page = '' + self.assertEqual( + _parse_moodle_config(page), + {"homeurl": {}, "sesskey": "sec}ret", "userId": 1818}, + ) + + def test_collects_links_and_embedded_media(self): + parser = _LinkParser("https://training.example/mod/resource/view.php?id=1") + parser.feed( + ' Notes ' + '' + ) + self.assertEqual(parser.links[0], ("https://training.example/pluginfile.php/10/file.pdf", "Notes")) + self.assertEqual(parser.media[0], "https://training.example/pluginfile.php/11/video.mp4") + + def test_filename_prefers_content_disposition(self): + headers = email.message.Message() + headers["Content-Disposition"] = "attachment; filename*=UTF-8''lesson%201.mp4" + self.assertEqual(_filename_from_headers(headers, "https://x/file.php/1", "lesson"), "lesson 1.mp4") + + def test_sanitizes_names_and_deduplicates_files(self): + self.assertEqual(_clean_name('Week 1: Intro/Setup?'), "Week 1_ Intro_Setup_") + item = FileItem(44, "Chapter 1", "Intro", "1.mp4", "https://x/pluginfile.php/1/1.mp4?token=a") + duplicate = FileItem(44, "Other", "Other", "1.mp4", "https://x/pluginfile.php/1/1.mp4?token=b") + self.assertEqual(_unique([item, duplicate]), [item]) + + +if __name__ == "__main__": + unittest.main()