add static course library with chapter-aware media browsing

This commit is contained in:
Meghdad committed 2026-08-02 23:31:17 +03:30
1 parent 4b53e7b3ab
commit c8ede57792
11 files changed
+1545 -7

No files matched your search

+1
View File
@@ -12,6 +12,7 @@ build/
develop-eggs/
dist/
downloads/
library/
eggs/
.eggs/
lib/
+9
View File
@@ -2,6 +2,15 @@
All notable changes to this project will be documented here.
## 0.3.0 - 2026-08-02
- Add a generated static Learning Library with responsive course and resource pages.
- Export rich course, chapter, activity, file, completion, and local download metadata to `library/courses.json`.
- Add course search, file filters, video playback, dark mode, and local completion tracking.
- Preserve Moodle chapter ordering and include forums, quizzes, live classes, and course links.
- Stream local media with HTTP byte-range support for efficient seeking.
- Add `library` and `serve-library` commands while keeping generated enrollment data private.
## 0.2.0 - 2026-08-02
- Add a persistent, interactive installed-browser login flow that handles Cloudflare normally.
+24
View File
@@ -31,6 +31,8 @@ ravin-downloader login
ravin-downloader courses
ravin-downloader files COURSE_ID
ravin-downloader download COURSE_ID
ravin-downloader library
ravin-downloader serve-library --open
```
Files are saved under `downloads/<course-id>/...`. Existing completed files are skipped; interrupted downloads use a temporary `.part` suffix and resume automatically with HTTP byte-range requests. Use `--overwrite` if you want to replace existing files, or `--retries` to change the default five retries per file.
@@ -82,6 +84,28 @@ ravin-downloader files 44
ravin-downloader download 44
```
## Static course library
Build a clean local website from your enrolled courses and downloaded files:
```bash
ravin-downloader library
ravin-downloader serve-library --open
```
The first command refreshes `library/courses.json` from the LMS and copies the static HTML, CSS, and JavaScript pages into `library/`. The catalog preserves the LMS chapter order and includes section IDs and summaries, every activity and its type, lesson descriptions, LMS completion state, original filenames, MIME types, sizes, extensions, local download status, and safe LMS activity links. It does not copy the large course files. The pages link to the originals under `downloads/`, keeping their original filenames.
The second command serves both directories locally at `http://localhost:8765/library/`. The library includes course search, true chapter grouping, offline progress, resource filters, efficient seekable video playback, document links, online LMS activities, dark mode, and completion checkboxes saved in your browser. Run `ravin-downloader library` again after downloading new files to refresh the catalog.
To build only selected courses or choose other directories:
```bash
ravin-downloader library 44 --output library --downloads downloads
ravin-downloader serve-library --site-dir library --downloads downloads --port 8765
```
The generated `library/` directory is Git-ignored because its JSON contains details about your enrollments. No passwords, cookies, session tokens, or remote file URLs are written to the catalog.
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
+5 -1
View File
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "ravin-moodle-downloader"
version = "0.2.0"
version = "0.3.0"
description = "List and download authorized course files from Ravin Academy or another Moodle site"
readme = "README.md"
requires-python = ">=3.10"
@@ -34,3 +34,7 @@ ravin-downloader = "ravin_downloader:main"
[tool.setuptools]
py-modules = ["ravin_downloader"]
packages = ["ravin_downloader_assets"]
[tool.setuptools.package-data]
ravin_downloader_assets = ["*.html", "*.css", "*.js"]
+563 -6
View File
@@ -11,10 +11,13 @@ Only Python's standard library is required.
from __future__ import annotations
import argparse
import functools
import getpass
import hashlib
import html
import http.cookiejar
import http.client
import http.server
import json
import mimetypes
import os
@@ -27,14 +30,16 @@ import urllib.error
import urllib.parse
import urllib.request
from dataclasses import asdict, dataclass
from datetime import datetime, timezone
from html.parser import HTMLParser
from importlib import resources
from pathlib import Path
from typing import Any, Iterable
DEFAULT_SITE = "https://training.ravinacademy.com"
DEFAULT_RAVIN_LOGIN_URL = "https://lms.ravinacademy.com/"
__version__ = "0.2.0"
__version__ = "0.3.0"
USER_AGENT = f"RavinMoodleDownloader/{__version__} (+personal Moodle client)"
DOWNLOADABLE_MODULES = {"resource", "folder", "page", "book"}
DEFAULT_ENV_FILE = Path.cwd() / ".env"
@@ -45,6 +50,7 @@ ENV_KEYS = {
"user_agent": "RAVIN_USER_AGENT",
"cookie": "RAVIN_COOKIE",
}
LIBRARY_ASSETS = ("index.html", "course.html", "styles.css", "app.js")
class MoodleError(RuntimeError):
@@ -67,6 +73,13 @@ class FileItem:
url: str
mimetype: str = ""
filesize: int | None = None
chapter: str = ""
section_id: int | None = None
section_number: int | None = None
activity_id: int | None = None
activity_type: str = ""
activity_position: int | None = None
description: str = ""
class _FormParser(HTMLParser):
@@ -146,6 +159,114 @@ class _LinkParser(HTMLParser):
self.title = " ".join("".join(self._title_text).split())
class _CourseStructureParser(HTMLParser):
"""Collect Moodle sections and activities from a course page."""
VOID_TAGS = {"area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"}
def __init__(self, base_url: str) -> None:
super().__init__(convert_charrefs=True)
self.base_url = base_url
self.sections: list[dict[str, Any]] = []
self._section: dict[str, Any] | None = None
self._activity: dict[str, Any] | None = None
self._markers: list[str | None] = []
self._captures: list[tuple[int, dict[str, Any], str]] = []
@staticmethod
def _integer(value: str | None) -> int | None:
try:
return int(value or "")
except ValueError:
return None
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
values = dict(attrs)
classes = set((values.get("class") or "").split())
marker: str | None = None
if (
tag == "li"
and values.get("data-for") == "section"
and (values.get("id") or "").startswith("section-")
):
self._section = {
"id": self._integer(values.get("data-id")),
"number": self._integer(values.get("data-sectionid") or values.get("data-number")),
"position": len(self.sections) + 1,
"name": " ".join((values.get("data-sectionname") or "Section").split()),
"summary": "",
"activities": [],
}
self.sections.append(self._section)
marker = "section"
elif tag == "li" and self._section is not None and values.get("data-for") == "cmitem":
module_type = next(
(value.removeprefix("modtype_") for value in classes if value.startswith("modtype_")),
"activity",
)
self._activity = {
"id": self._integer(values.get("data-id")),
"position": len(self._section["activities"]) + 1,
"name": "",
"type": module_type,
"url": "",
"description": "",
"badge": "",
"lms_completed": None,
}
self._section["activities"].append(self._activity)
marker = "activity"
if tag not in self.VOID_TAGS:
self._markers.append(marker)
depth = len(self._markers)
if self._activity is not None:
activity_name = values.get("data-activityname")
if activity_name and not self._activity["name"]:
self._activity["name"] = " ".join(activity_name.split())
if tag == "a" and values.get("href") and "/mod/" in (values.get("href") or ""):
self._activity["url"] = urllib.parse.urljoin(self.base_url, values["href"] or "")
if "activity-description" in classes:
self._captures.append((depth, self._activity, "description"))
if "activitybadge" in classes:
self._captures.append((depth, self._activity, "badge"))
class_value = values.get("class") or ""
if "btn-subtle-success" in class_value:
self._activity["lms_completed"] = True
if self._section is not None and "summary" in classes:
self._captures.append((depth, self._section, "summary"))
def handle_endtag(self, _tag: str) -> None:
if _tag in self.VOID_TAGS:
return
depth = len(self._markers)
self._captures = [capture for capture in self._captures if capture[0] != depth]
if not self._markers:
return
marker = self._markers.pop()
if marker == "activity":
self._activity = None
elif marker == "section":
self._section = None
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
self.handle_starttag(tag, attrs)
def handle_data(self, data: str) -> None:
if not data.strip():
return
for _, target, field in self._captures:
target[field] = f"{target.get(field, '')} {data}".strip()
def result(self) -> list[dict[str, Any]]:
for section in self.sections:
section["summary"] = " ".join(section["summary"].split())
for activity in section["activities"]:
activity["name"] = " ".join((activity["name"] or activity["type"]).split())
activity["description"] = " ".join(activity["description"].split())
activity["badge"] = " ".join(activity["badge"].split())
return self.sections
def _parse_moodle_config(page: str) -> dict[str, Any]:
match = re.search(r"\bM\.cfg\s*=\s*", page)
if not match:
@@ -256,6 +377,7 @@ class MoodleClient:
self.user_id: int | None = None
self.sesskey: str | None = None
self.mode = ""
self._course_structure_cache: dict[int, list[dict[str, Any]]] = {}
def _install_cookie_header(self, cookie_header: str) -> None:
parsed_site = urllib.parse.urlparse(self.site)
@@ -519,9 +641,9 @@ class MoodleClient:
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:
for section_position, section in enumerate(sections, 1):
section_name = str(section.get("name") or f"Section {section.get('section', '')}")
for module in section.get("modules", []):
for activity_position, module in enumerate(section.get("modules", []), 1):
activity = str(module.get("name") or module.get("modname") or "activity")
for content in module.get("contents", []) or []:
file_url = content.get("fileurl")
@@ -536,12 +658,29 @@ class MoodleClient:
url=str(file_url),
mimetype=str(content.get("mimetype") or ""),
filesize=int(content["filesize"]) if content.get("filesize") is not None else None,
chapter=section_name,
section_id=int(section["id"]) if section.get("id") is not None else None,
section_number=int(section["section"]) if section.get("section") is not None else section_position,
activity_id=int(module["id"]) if module.get("id") is not None else None,
activity_type=str(module.get("modname") or ""),
activity_position=activity_position,
description=re.sub(r"<[^>]+>", " ", str(module.get("description") or "")).strip(),
)
)
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}")
structure_parser = _CourseStructureParser(final_url)
structure_parser.feed(page)
structure = structure_parser.result()
self._course_structure_cache[course_id] = structure
activity_by_url: dict[str, tuple[dict[str, Any], dict[str, Any]]] = {}
for section in structure:
for activity_metadata in section["activities"]:
if activity_metadata["url"]:
key = urllib.parse.urlsplit(activity_metadata["url"])._replace(fragment="").geturl()
activity_by_url[key] = (section, activity_metadata)
parser = _LinkParser(final_url)
parser.feed(page)
module_links: list[tuple[str, str]] = []
@@ -564,6 +703,9 @@ class MoodleClient:
if module_key in seen_modules:
continue
seen_modules.add(module_key)
metadata = activity_by_url.get(module_key)
if metadata:
activity = metadata[1]["name"] or activity
separator = "&" if urllib.parse.urlparse(module_url).query else "?"
inspect_url = module_url + separator + "redirect=0"
try:
@@ -573,7 +715,7 @@ class MoodleClient:
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))
files.append(self._web_file_item(course_id, "Course files", activity, module_final_url, metadata))
continue
module_parser = _LinkParser(module_final_url)
module_parser.feed(module_page)
@@ -582,19 +724,45 @@ class MoodleClient:
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))
files.append(self._web_file_item(course_id, "Course files", activity, candidate, metadata))
return _unique(files)
def _web_file_item(self, course_id: int, section: str, activity: str, url: str) -> FileItem:
def _web_file_item(
self,
course_id: int,
section: str,
activity: str,
url: str,
metadata: tuple[dict[str, Any], dict[str, Any]] | None = None,
) -> FileItem:
path_name = Path(urllib.parse.unquote(urllib.parse.urlparse(url).path)).name
section_metadata, activity_metadata = metadata or ({}, {})
return FileItem(
course_id=course_id,
section=section,
activity=activity or path_name,
filename=path_name or _clean_name(activity),
url=url,
chapter=str(section_metadata.get("name") or section),
section_id=section_metadata.get("id"),
section_number=section_metadata.get("number"),
activity_id=activity_metadata.get("id"),
activity_type=str(activity_metadata.get("type") or ""),
activity_position=activity_metadata.get("position"),
description=str(activity_metadata.get("description") or ""),
)
def course_structure(self, course_id: int) -> list[dict[str, Any]]:
cached = self._course_structure_cache.get(course_id)
if cached is not None:
return cached
page, final_url, _ = self._read_text(f"/course/view.php?id={course_id}")
parser = _CourseStructureParser(final_url)
parser.feed(page)
structure = parser.result()
self._course_structure_cache[course_id] = structure
return structure
def download(
self,
item: FileItem,
@@ -1148,6 +1316,370 @@ def _format_size(size: int | None) -> str:
return str(size)
def _resource_kind(item: FileItem) -> str:
mimetype = item.mimetype.casefold()
suffix = Path(item.filename).suffix.casefold()
if mimetype.startswith("video/") or suffix in {".mp4", ".mkv", ".webm", ".mov", ".m4v"}:
return "video"
if mimetype.startswith("audio/") or suffix in {".mp3", ".m4a", ".wav", ".ogg", ".flac"}:
return "audio"
if (
mimetype.startswith("text/")
or mimetype in {"application/pdf", "application/msword"}
or suffix in {".pdf", ".doc", ".docx", ".ppt", ".pptx", ".txt", ".md"}
):
return "document"
if suffix in {".zip", ".rar", ".7z", ".tar", ".gz"}:
return "archive"
return "file"
def _browser_path(path: Path, relative_to: Path) -> str:
relative = Path(os.path.relpath(path, relative_to))
return "/".join(
part if part in {".", ".."} else urllib.parse.quote(part)
for part in relative.parts
)
def _local_resource(item: FileItem, downloads: Path) -> tuple[str, Path | None]:
directory = downloads / _clean_name(str(item.course_id), "course") / _clean_name(
item.section,
"Course files",
)
expected = directory / _clean_name(item.filename, _clean_name(item.activity, "activity"))
if expected.is_file():
return "downloaded", expected
partial = expected.with_name(expected.name + ".part")
if partial.is_file():
return "partial", partial
if directory.is_dir():
expected_name = expected.name.casefold()
matches = [path for path in directory.iterdir() if path.is_file() and path.name.casefold() == expected_name]
if len(matches) == 1:
return "downloaded", matches[0]
return "missing", None
def _build_library_catalog(
client: MoodleClient,
downloads: Path,
output: Path,
selected_course_ids: Iterable[int] = (),
) -> dict[str, Any]:
selected_ids = set(selected_course_ids)
available_courses = client.list_courses()
courses = [course for course in available_courses if not selected_ids or course.id in selected_ids]
missing_ids = selected_ids - {course.id for course in courses}
if missing_ids:
missing = ", ".join(str(course_id) for course_id in sorted(missing_ids))
raise MoodleError(f"course ID(s) not found in your enrollments: {missing}")
catalog_courses: list[dict[str, Any]] = []
total_files = 0
total_activities = 0
total_records = 0
total_downloaded = 0
total_downloaded_bytes = 0
for course in courses:
print(f"Reading course {course.id}: {course.fullname}", file=sys.stderr)
downloaded_count = 0
downloaded_bytes = 0
items = client.list_files(course.id)
try:
structure_method = getattr(client, "course_structure")
structure = structure_method(course.id)
except (AttributeError, MoodleError):
structure = []
consumed: set[int] = set()
def file_record(
item: FileItem,
item_index: int,
section_metadata: dict[str, Any] | None = None,
activity_metadata: dict[str, Any] | None = None,
) -> dict[str, Any]:
nonlocal downloaded_count, downloaded_bytes
section_metadata = section_metadata or {}
activity_metadata = activity_metadata or {}
status, local_path = _local_resource(item, downloads)
local_bytes = local_path.stat().st_size if local_path else 0
if status == "downloaded":
downloaded_count += 1
downloaded_bytes += local_bytes
stable_source = urllib.parse.urlsplit(item.url)._replace(query="", fragment="").geturl()
resource_id = hashlib.sha1(
f"{course.id}\0{stable_source}\0{item.filename}".encode("utf-8")
).hexdigest()[:14]
title = activity_metadata.get("name") or re.sub(r"\s*فایل\s*$", "", item.activity).strip()
consumed.add(item_index)
return {
"id": resource_id,
"section": item.section,
"section_id": section_metadata.get("id", item.section_id),
"section_number": section_metadata.get("number", item.section_number),
"activity_id": activity_metadata.get("id", item.activity_id),
"activity_position": activity_metadata.get("position", item.activity_position),
"activity_type": activity_metadata.get("type", item.activity_type or "resource"),
"title": title or item.filename,
"description": activity_metadata.get("description") or item.description,
"badge": activity_metadata.get("badge") or Path(item.filename).suffix.removeprefix(".").upper(),
"filename": item.filename,
"extension": Path(item.filename).suffix.removeprefix(".").casefold(),
"kind": _resource_kind(item),
"mimetype": item.mimetype,
"status": status,
"size": local_bytes if status == "downloaded" else item.filesize,
"local_bytes": local_bytes,
"local_url": _browser_path(local_path, output) if status == "downloaded" and local_path else None,
"source_url": activity_metadata.get("url") or f"{client.site}/course/view.php?id={course.id}",
"lms_completed": activity_metadata.get("lms_completed"),
}
files_by_activity: dict[int, list[tuple[int, FileItem]]] = {}
for item_index, item in enumerate(items):
if item.activity_id is not None:
files_by_activity.setdefault(item.activity_id, []).append((item_index, item))
catalog_sections: list[dict[str, Any]] = []
activity_count = 0
for section in structure:
section_records: list[dict[str, Any]] = []
activities = section.get("activities", [])
activity_count += len(activities)
for activity in activities:
matches = files_by_activity.get(activity.get("id"), [])
if not matches:
activity_name = re.sub(r"\s*فایل\s*$", "", str(activity.get("name") or "")).strip().casefold()
matches = [
(item_index, item)
for item_index, item in enumerate(items)
if item_index not in consumed
and re.sub(r"\s*فایل\s*$", "", item.activity).strip().casefold() == activity_name
]
if matches:
for item_index, item in matches:
if item_index not in consumed:
section_records.append(file_record(item, item_index, section, activity))
continue
activity_type = str(activity.get("type") or "activity")
type_names = {
"bigbluebuttonbn": "live class",
"forum": "discussion",
"quiz": "quiz",
"url": "link",
"resource": "resource",
}
section_records.append(
{
"id": f"activity-{activity.get('id') or hashlib.sha1(str(activity).encode()).hexdigest()[:10]}",
"section": section.get("name") or "Course",
"section_id": section.get("id"),
"section_number": section.get("number"),
"activity_id": activity.get("id"),
"activity_position": activity.get("position"),
"activity_type": activity_type,
"title": activity.get("name") or activity_type,
"description": activity.get("description") or "",
"badge": activity.get("badge") or type_names.get(activity_type, activity_type),
"filename": "",
"extension": "",
"kind": type_names.get(activity_type, "activity"),
"mimetype": "",
"status": "online",
"size": None,
"local_bytes": 0,
"local_url": None,
"source_url": activity.get("url") or f"{client.site}/course/view.php?id={course.id}",
"lms_completed": activity.get("lms_completed"),
}
)
catalog_sections.append(
{
"id": section.get("id"),
"number": section.get("number"),
"position": section.get("position"),
"name": section.get("name") or "Section",
"summary": section.get("summary") or "",
"activity_count": len(activities),
"items": section_records,
}
)
for item_index, item in enumerate(items):
if item_index in consumed:
continue
chapter_name = item.chapter or item.section
target = next((section for section in catalog_sections if section["name"] == chapter_name), None)
if target is None:
target = {
"id": item.section_id,
"number": item.section_number,
"position": len(catalog_sections) + 1,
"name": chapter_name,
"summary": "",
"activity_count": 0,
"items": [],
}
catalog_sections.append(target)
target["items"].append(file_record(item, item_index))
if not structure:
activity_count = len(items)
for section in catalog_sections:
section["activity_count"] = len(section["items"])
file_count = len(items)
record_count = sum(len(section["items"]) for section in catalog_sections)
type_counts: dict[str, int] = {}
for section in catalog_sections:
for record in section["items"]:
type_counts[record["kind"]] = type_counts.get(record["kind"], 0) + 1
catalog_courses.append(
{
"id": course.id,
"fullname": course.fullname,
"shortname": course.shortname,
"source_url": f"{client.site}/course/view.php?id={course.id}",
"section_count": len(catalog_sections),
"activity_count": activity_count,
"record_count": record_count,
"file_count": file_count,
"downloaded_count": downloaded_count,
"downloaded_bytes": downloaded_bytes,
"type_counts": type_counts,
"sections": catalog_sections,
}
)
total_files += file_count
total_activities += activity_count
total_records += record_count
total_downloaded += downloaded_count
total_downloaded_bytes += downloaded_bytes
return {
"schema_version": 2,
"generated_at": datetime.now(timezone.utc).isoformat(),
"stats": {
"courses": len(catalog_courses),
"files": total_files,
"activities": total_activities,
"records": total_records,
"downloaded_files": total_downloaded,
"downloaded_bytes": total_downloaded_bytes,
},
"courses": catalog_courses,
}
def _write_library_site(output: Path, catalog: dict[str, Any]) -> Path:
output.mkdir(parents=True, exist_ok=True)
asset_root = resources.files("ravin_downloader_assets")
for name in LIBRARY_ASSETS:
(output / name).write_bytes(asset_root.joinpath(name).read_bytes())
catalog_path = output / "courses.json"
catalog_path.write_text(
json.dumps(catalog, ensure_ascii=False, indent=2) + "\n",
encoding="utf-8",
)
return catalog_path
class _RangeRequestHandler(http.server.SimpleHTTPRequestHandler):
"""Static-file handler with byte ranges for efficient local media playback."""
_byte_range: tuple[int, int] | None = None
def send_head(self) -> Any:
self._byte_range = None
path = self.translate_path(self.path)
if os.path.isdir(path):
return super().send_head()
try:
source = open(path, "rb")
except OSError:
self.send_error(404, "File not found")
return None
try:
size = os.fstat(source.fileno()).st_size
range_header = self.headers.get("Range", "")
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
if match and (match.group(1) or match.group(2)):
if match.group(1):
start = int(match.group(1))
end = int(match.group(2)) if match.group(2) else size - 1
else:
suffix_length = int(match.group(2))
start = max(size - suffix_length, 0)
end = size - 1
if start >= size or start > end:
self.send_response(416)
self.send_header("Content-Range", f"bytes */{size}")
self.end_headers()
source.close()
return None
end = min(end, size - 1)
self._byte_range = (start, end)
self.send_response(206)
self.send_header("Content-Type", self.guess_type(path))
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
self.send_header("Content-Length", str(end - start + 1))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Last-Modified", self.date_time_string(os.fstat(source.fileno()).st_mtime))
self.end_headers()
return source
self.send_response(200)
self.send_header("Content-Type", self.guess_type(path))
self.send_header("Content-Length", str(size))
self.send_header("Accept-Ranges", "bytes")
self.send_header("Last-Modified", self.date_time_string(os.fstat(source.fileno()).st_mtime))
self.end_headers()
return source
except Exception:
source.close()
raise
def copyfile(self, source: Any, outputfile: Any) -> None:
if self._byte_range is None:
shutil.copyfileobj(source, outputfile)
return
start, end = self._byte_range
source.seek(start)
remaining = end - start + 1
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk:
break
outputfile.write(chunk)
remaining -= len(chunk)
def _serve_library(site_dir: Path, downloads: Path, host: str, port: int, open_browser: bool) -> None:
site_dir = site_dir.expanduser().resolve()
downloads = downloads.expanduser().resolve()
if not (site_dir / "index.html").is_file() or not (site_dir / "courses.json").is_file():
raise MoodleError(f"{site_dir} is not built yet; run `ravin-downloader library` first")
if site_dir.parent != downloads.parent:
raise MoodleError("the site directory and downloads directory must share the same parent")
handler = functools.partial(_RangeRequestHandler, directory=str(site_dir.parent))
try:
server = http.server.ThreadingHTTPServer((host, port), handler)
except OSError as exc:
raise MoodleError(f"could not start the library server on {host}:{port}: {exc}") from exc
display_host = "localhost" if host in {"127.0.0.1", "0.0.0.0", "::"} else host
site_name = urllib.parse.quote(site_dir.name)
url = f"http://{display_host}:{server.server_port}/{site_name}/"
print(f"Learning Library: {url}")
print("Press Ctrl+C to stop.")
if open_browser:
import webbrowser
webbrowser.open(url)
try:
server.serve_forever()
finally:
server.server_close()
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description="List and download your Ravin Academy Moodle course files.")
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
@@ -1216,12 +1748,28 @@ def build_parser() -> argparse.ArgumentParser:
download_parser.add_argument("--output", type=Path, default=Path("downloads"))
download_parser.add_argument("--overwrite", action="store_true")
download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)")
library_parser = subparsers.add_parser(
"library",
help="generate a private static course library and courses.json",
)
library_parser.add_argument("course_ids", nargs="*", type=int, help="optional course IDs; defaults to all courses")
library_parser.add_argument("--output", type=Path, default=Path("library"), help="generated site directory")
library_parser.add_argument("--downloads", type=Path, default=Path("downloads"), help="download root to index")
serve_parser = subparsers.add_parser("serve-library", help="serve the generated library locally")
serve_parser.add_argument("--site-dir", type=Path, default=Path("library"), help="generated site directory")
serve_parser.add_argument("--downloads", type=Path, default=Path("downloads"), help="download root")
serve_parser.add_argument("--host", default="127.0.0.1", help="local bind address (default: 127.0.0.1)")
serve_parser.add_argument("--port", type=int, default=8765, help="local port (default: 8765)")
serve_parser.add_argument("--open", action="store_true", help="open the library in your default browser")
return parser
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
try:
if args.command == "serve-library":
_serve_library(args.site_dir, args.downloads, args.host, args.port, args.open)
return 0
args.env_values = _load_env_file(args.env_file)
if args.command == "login":
client, mode = _authenticate_browser_session(args)
@@ -1265,6 +1813,15 @@ def main(argv: list[str] | None = None) -> int:
print(f"{course.id:>6} {course.fullname}{suffix}")
return 0
if args.command == "library":
output = args.output.expanduser().resolve()
downloads = args.downloads.expanduser().resolve()
catalog = _build_library_catalog(client, downloads, output, args.course_ids)
catalog_path = _write_library_site(output, catalog)
print(f"Generated {catalog_path} and the static library pages.")
print("View it with: ravin-downloader serve-library --open")
return 0
files = client.list_files(args.course_id)
if args.command == "files":
if args.json:
+1
View File
@@ -0,0 +1 @@
"""Static assets for the generated local course library."""
+325
View File
@@ -0,0 +1,325 @@
const state = { catalog: null, course: null, query: "", filter: "all" };
const byId = (id) => document.getElementById(id);
const clampPercent = (value) => Math.max(0, Math.min(100, Math.round(value || 0)));
function formatBytes(bytes) {
if (!Number.isFinite(bytes) || bytes <= 0) return "—";
const units = ["B", "KB", "MB", "GB", "TB"];
let value = bytes;
let index = 0;
while (value >= 1024 && index < units.length - 1) {
value /= 1024;
index += 1;
}
const digits = value >= 10 || index === 0 ? 0 : 1;
return `${value.toFixed(digits)} ${units[index]}`;
}
function normalized(value) {
return String(value || "").toLocaleLowerCase().trim();
}
function setText(id, value) {
const element = byId(id);
if (element) element.textContent = value;
}
function applyTheme(theme) {
document.documentElement.dataset.theme = theme;
localStorage.setItem("ravin-library-theme", theme);
}
function setupTheme() {
const stored = localStorage.getItem("ravin-library-theme");
const preferred = window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
applyTheme(stored || preferred);
byId("themeToggle")?.addEventListener("click", () => {
applyTheme(document.documentElement.dataset.theme === "dark" ? "light" : "dark");
});
}
async function loadCatalog() {
const response = await fetch("courses.json", { cache: "no-store" });
if (!response.ok) throw new Error(`Could not load courses.json (${response.status})`);
return response.json();
}
function showLoadError(error) {
const target = byId("courseGrid") || byId("sectionList");
if (!target) return;
target.innerHTML = "";
const box = document.createElement("div");
box.className = "empty-state";
const title = document.createElement("strong");
title.textContent = "The course data could not be loaded";
const detail = document.createElement("span");
detail.textContent = "Open this library with ‘ravin-downloader serve-library’, then refresh the page.";
box.append(title, detail);
target.append(box);
console.error(error);
}
function courseCard(course) {
const percent = clampPercent((course.downloaded_count / Math.max(course.file_count, 1)) * 100);
const card = document.createElement("article");
card.className = "course-card";
const top = document.createElement("div");
top.className = "course-card-top";
const code = document.createElement("span");
code.className = "course-code";
code.textContent = course.shortname || `Course ${course.id}`;
const badge = document.createElement("span");
badge.className = "course-badge";
badge.textContent = `${course.activity_count ?? course.file_count} activities`;
top.append(code, badge);
const title = document.createElement("h3");
title.dir = "auto";
title.textContent = course.fullname;
const meta = document.createElement("p");
meta.className = "course-card-meta";
meta.textContent = `${course.section_count} chapters · ${course.file_count} files · ${formatBytes(course.downloaded_bytes)} offline`;
const bottom = document.createElement("div");
bottom.className = "course-card-bottom";
const track = document.createElement("div");
track.className = "progress-track";
const fill = document.createElement("span");
fill.style.setProperty("--progress", `${percent}%`);
track.append(fill);
const progress = document.createElement("div");
progress.className = "progress-copy";
progress.innerHTML = `<span>${course.downloaded_count} offline</span><strong>${percent}%</strong>`;
const link = document.createElement("a");
link.className = "course-link";
link.href = `course.html?id=${encodeURIComponent(course.id)}`;
link.innerHTML = `Open course <span aria-hidden="true">→</span>`;
bottom.append(track, progress, link);
card.append(top, title, meta, bottom);
return card;
}
function renderCourseGrid() {
const grid = byId("courseGrid");
const query = normalized(byId("courseSearch")?.value);
const courses = state.catalog.courses.filter((course) => normalized(`${course.fullname} ${course.shortname}`).includes(query));
grid.innerHTML = "";
courses.forEach((course) => grid.append(courseCard(course)));
byId("emptyCourses").hidden = courses.length !== 0;
}
function renderIndex() {
const stats = state.catalog.stats;
const percent = clampPercent((stats.downloaded_files / Math.max(stats.files, 1)) * 100);
setText("heroPercent", `${percent}%`);
setText("courseCount", stats.courses.toLocaleString());
setText("resourceCount", (stats.activities ?? stats.files).toLocaleString());
setText("downloadedCount", stats.downloaded_files.toLocaleString());
setText("librarySize", formatBytes(stats.downloaded_bytes));
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
byId("courseSearch").addEventListener("input", renderCourseGrid);
renderCourseGrid();
}
function completionKey(item) {
return `ravin-complete-${state.course.id}-${item.id}`;
}
function isComplete(item) {
return localStorage.getItem(completionKey(item)) === "1";
}
function resourceMatches(item) {
const haystack = normalized(`${item.title} ${item.filename} ${item.section}`);
if (state.query && !haystack.includes(state.query)) return false;
if (state.filter === "all") return true;
if (state.filter === "downloaded" || state.filter === "missing") return item.status === state.filter;
return item.kind === state.filter;
}
function resourceRow(item, index) {
const row = document.createElement("article");
row.className = `resource-row${isComplete(item) ? " completed" : ""}`;
const number = document.createElement("span");
number.className = "resource-index";
number.textContent = String(index + 1).padStart(2, "0");
const main = document.createElement("div");
main.className = "resource-main";
const title = document.createElement("span");
title.className = "resource-title";
title.dir = "auto";
title.textContent = item.title;
const filename = document.createElement("span");
filename.className = "resource-file";
filename.dir = "auto";
filename.textContent = item.filename || item.badge || item.activity_type;
main.append(title, filename);
if (item.description) {
const description = document.createElement("span");
description.className = "resource-description";
description.dir = "auto";
description.textContent = item.description;
main.append(description);
}
const meta = document.createElement("div");
meta.className = "resource-meta";
const type = document.createElement("span");
type.className = "type-pill";
type.textContent = item.kind;
const dot = document.createElement("span");
dot.className = `status-dot${item.status === "missing" ? " missing" : item.status === "online" ? " online" : ""}`;
const size = document.createElement("span");
size.textContent = item.status === "partial"
? `${formatBytes(item.local_bytes)} partial`
: item.status === "online"
? (item.lms_completed ? "LMS complete" : "Online")
: formatBytes(item.size);
meta.append(type, dot, size);
let action;
if (item.status === "downloaded" && item.kind === "video") {
action = document.createElement("button");
action.type = "button";
action.textContent = "Play";
action.addEventListener("click", () => openVideo(item));
} else if (item.status === "downloaded") {
action = document.createElement("a");
action.href = item.local_url;
action.target = "_blank";
action.rel = "noopener";
action.textContent = item.kind === "document" ? "Open" : "View";
} else if (item.status === "online" && item.source_url) {
action = document.createElement("a");
action.href = item.source_url;
action.target = "_blank";
action.rel = "noopener";
action.textContent = "Open LMS";
} else {
action = document.createElement("span");
action.textContent = item.status === "partial" ? "Partial" : "Missing";
action.setAttribute("aria-disabled", "true");
}
action.className = "action-button";
const complete = document.createElement("input");
complete.className = "complete-check";
complete.type = "checkbox";
complete.checked = isComplete(item);
complete.setAttribute("aria-label", `Mark ${item.title} complete`);
complete.addEventListener("change", () => {
localStorage.setItem(completionKey(item), complete.checked ? "1" : "0");
row.classList.toggle("completed", complete.checked);
});
row.append(number, main, meta, action, complete);
return row;
}
function renderResources() {
const container = byId("sectionList");
container.innerHTML = "";
let visibleCount = 0;
let runningIndex = 0;
state.course.sections.forEach((section) => {
const items = section.items.filter(resourceMatches);
if (!items.length) return;
visibleCount += items.length;
const wrapper = document.createElement("section");
wrapper.className = "resource-section";
const heading = document.createElement("div");
heading.className = "resource-section-header";
const title = document.createElement("h2");
title.dir = "auto";
title.textContent = section.name;
const count = document.createElement("span");
count.textContent = `${items.length} resource${items.length === 1 ? "" : "s"}`;
heading.append(title, count);
if (section.summary) {
const summary = document.createElement("p");
summary.className = "section-summary";
summary.dir = "auto";
summary.textContent = section.summary;
heading.append(summary);
}
const list = document.createElement("div");
list.className = "resource-list";
items.forEach((item) => {
list.append(resourceRow(item, runningIndex));
runningIndex += 1;
});
wrapper.append(heading, list);
container.append(wrapper);
});
byId("emptyResources").hidden = visibleCount !== 0;
}
function openVideo(item) {
const dialog = byId("mediaDialog");
const player = byId("mediaPlayer");
setText("mediaTitle", item.title);
player.src = item.local_url;
dialog.showModal();
player.play().catch(() => {});
}
function closeVideo() {
const dialog = byId("mediaDialog");
const player = byId("mediaPlayer");
player.pause();
player.removeAttribute("src");
player.load();
dialog.close();
}
function renderCourse() {
const id = new URLSearchParams(window.location.search).get("id");
state.course = state.catalog.courses.find((course) => String(course.id) === String(id));
if (!state.course) {
showLoadError(new Error(`Course ${id || "(missing)"} was not found`));
return;
}
const course = state.course;
document.title = `${course.fullname} · Learning Library`;
const percent = clampPercent((course.downloaded_count / Math.max(course.file_count, 1)) * 100);
setText("breadcrumbCourse", course.fullname);
setText("courseCode", course.shortname || `Course ${course.id}`);
setText("courseTitle", course.fullname);
setText("courseSummary", `${course.activity_count ?? course.file_count} activities, ${course.file_count} downloadable files, and ${course.section_count} chapters.`);
setText("coursePercent", `${percent}%`);
setText("courseDownloaded", `${course.downloaded_count} of ${course.file_count}`);
setText("generatedAt", `Updated ${new Date(state.catalog.generated_at).toLocaleString()}`);
byId("courseProgress").style.setProperty("--progress", percent);
byId("courseSource").href = course.source_url;
byId("resourceSearch").addEventListener("input", (event) => {
state.query = normalized(event.target.value);
renderResources();
});
byId("resourceFilters").addEventListener("click", (event) => {
const button = event.target.closest("button[data-filter]");
if (!button) return;
state.filter = button.dataset.filter;
document.querySelectorAll("button[data-filter]").forEach((item) => item.classList.toggle("active", item === button));
renderResources();
});
byId("closeMedia").addEventListener("click", closeVideo);
byId("mediaDialog").addEventListener("click", (event) => {
if (event.target === byId("mediaDialog")) closeVideo();
});
renderResources();
}
async function start() {
setupTheme();
try {
state.catalog = await loadCatalog();
if (document.body.dataset.page === "course") renderCourse();
else renderIndex();
} catch (error) {
showLoadError(error);
}
}
start();
+75
View File
@@ -0,0 +1,75 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Browse the resources in a downloaded course.">
<title>Course · Learning Library</title>
<link rel="stylesheet" href="styles.css">
<script src="app.js" defer></script>
</head>
<body data-page="course">
<header class="topbar">
<a class="brand" href="index.html" aria-label="Back to Learning Library">
<span class="brand-mark" aria-hidden="true">R</span>
<span>Learning Library</span>
</a>
<button class="icon-button" id="themeToggle" type="button" aria-label="Toggle color theme">◐</button>
</header>
<main>
<nav class="breadcrumbs" aria-label="Breadcrumb">
<a href="index.html">Library</a><span aria-hidden="true">/</span><span id="breadcrumbCourse">Course</span>
</nav>
<section class="course-hero" aria-labelledby="courseTitle">
<div class="course-heading">
<p class="eyebrow" id="courseCode">Course</p>
<h1 id="courseTitle">Loading course…</h1>
<p class="hero-copy" id="courseSummary"></p>
<a class="hero-source" id="courseSource" href="#" target="_blank" rel="noopener">Open in LMS ↗</a>
</div>
<div class="progress-panel">
<div class="progress-ring" id="courseProgress" style="--progress: 0">
<span id="coursePercent">0%</span>
</div>
<div><strong id="courseDownloaded">0 of 0</strong><span>files available offline</span></div>
</div>
</section>
<section class="course-toolbar" aria-label="Resource controls">
<label class="search-box resource-search">
<span aria-hidden="true">⌕</span>
<span class="sr-only">Search lessons and files</span>
<input id="resourceSearch" type="search" placeholder="Search lessons and files" autocomplete="off">
</label>
<div class="filter-group" id="resourceFilters" aria-label="Filter resources">
<button class="filter-chip active" type="button" data-filter="all">All</button>
<button class="filter-chip" type="button" data-filter="video">Videos</button>
<button class="filter-chip" type="button" data-filter="document">Documents</button>
<button class="filter-chip" type="button" data-filter="downloaded">Offline</button>
<button class="filter-chip" type="button" data-filter="missing">Missing</button>
</div>
</section>
<div class="section-list" id="sectionList" aria-live="polite"></div>
<div class="empty-state" id="emptyResources" hidden>
<strong>No matching resources</strong>
<span>Change the search or filter to see more.</span>
</div>
</main>
<dialog class="media-dialog" id="mediaDialog">
<div class="dialog-heading">
<div><p class="eyebrow">Now playing</p><h2 id="mediaTitle"></h2></div>
<button class="icon-button" id="closeMedia" type="button" aria-label="Close player">×</button>
</div>
<video id="mediaPlayer" controls preload="metadata"></video>
</dialog>
<footer>
<a href="index.html">← All courses</a>
<span id="generatedAt"></span>
</footer>
</body>
</html>
+65
View File
@@ -0,0 +1,65 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="A private, local library for downloaded course materials.">
<title>Learning Library</title>
<link rel="stylesheet" href="styles.css">
<script src="app.js" defer></script>
</head>
<body data-page="index">
<header class="topbar">
<a class="brand" href="index.html" aria-label="Learning Library home">
<span class="brand-mark" aria-hidden="true">R</span>
<span>Learning Library</span>
</a>
<button class="icon-button" id="themeToggle" type="button" aria-label="Toggle color theme">◐</button>
</header>
<main>
<section class="hero" aria-labelledby="pageTitle">
<div>
<p class="eyebrow">Your offline study space</p>
<h1 id="pageTitle">Pick up where you left off.</h1>
<p class="hero-copy">Every course, lesson, video, and document—organized around the work you want to finish.</p>
</div>
<div class="hero-orbit" aria-hidden="true">
<span class="orbit-number" id="heroPercent">0%</span>
<span class="orbit-label">available offline</span>
</div>
</section>
<section class="stat-grid" aria-label="Library summary">
<article class="stat-card"><span class="stat-label">Courses</span><strong id="courseCount">—</strong></article>
<article class="stat-card"><span class="stat-label">Resources</span><strong id="resourceCount">—</strong></article>
<article class="stat-card"><span class="stat-label">Downloaded</span><strong id="downloadedCount">—</strong></article>
<article class="stat-card"><span class="stat-label">Library size</span><strong id="librarySize">—</strong></article>
</section>
<section class="library-section" aria-labelledby="coursesHeading">
<div class="section-heading">
<div>
<p class="eyebrow">Course collection</p>
<h2 id="coursesHeading">Your courses</h2>
</div>
<label class="search-box">
<span aria-hidden="true">⌕</span>
<span class="sr-only">Search courses</span>
<input id="courseSearch" type="search" placeholder="Search courses" autocomplete="off">
</label>
</div>
<div class="course-grid" id="courseGrid" aria-live="polite"></div>
<div class="empty-state" id="emptyCourses" hidden>
<strong>No matching courses</strong>
<span>Try a different search phrase.</span>
</div>
</section>
</main>
<footer>
<span>Private library generated from your authorized LMS access.</span>
<span id="generatedAt"></span>
</footer>
</body>
</html>
+392
View File
@@ -0,0 +1,392 @@
:root {
color-scheme: light;
--ink: #172126;
--muted: #617077;
--paper: #f5f3ec;
--surface: #fffdf8;
--surface-strong: #ffffff;
--line: #dcded8;
--accent: #d8f26a;
--accent-strong: #93ad20;
--blue: #1c5166;
--blue-soft: #dbeaf0;
--danger: #b64d3c;
--shadow: 0 18px 55px rgba(37, 48, 52, .09);
--radius: 22px;
}
:root[data-theme="dark"] {
color-scheme: dark;
--ink: #f2f4ec;
--muted: #aab6b8;
--paper: #101719;
--surface: #172124;
--surface-strong: #1d292d;
--line: #304044;
--accent: #d8f26a;
--accent-strong: #bfd94f;
--blue: #8fc5d6;
--blue-soft: #223a42;
--danger: #f28f7d;
--shadow: 0 18px 55px rgba(0, 0, 0, .24);
}
* { box-sizing: border-box; }
html { scroll-behavior: smooth; }
body {
margin: 0;
min-height: 100vh;
color: var(--ink);
background:
radial-gradient(circle at 87% 7%, color-mix(in srgb, var(--accent) 22%, transparent), transparent 26rem),
var(--paper);
font-family: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", Tahoma, Arial, sans-serif;
line-height: 1.5;
}
button, input { font: inherit; }
button, a { -webkit-tap-highlight-color: transparent; }
a { color: inherit; }
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
.topbar {
max-width: 1240px;
margin: 0 auto;
padding: 24px 28px;
display: flex;
align-items: center;
justify-content: space-between;
}
.brand {
display: inline-flex;
gap: 12px;
align-items: center;
color: var(--ink);
font-weight: 750;
text-decoration: none;
letter-spacing: -.02em;
}
.brand-mark {
display: grid;
place-items: center;
width: 36px;
height: 36px;
border-radius: 12px;
color: #142024;
background: var(--accent);
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, .08);
}
.icon-button {
width: 42px;
height: 42px;
border: 1px solid var(--line);
border-radius: 14px;
color: var(--ink);
background: var(--surface);
cursor: pointer;
transition: transform .18s ease, border-color .18s ease;
}
.icon-button:hover { transform: translateY(-2px); border-color: var(--accent-strong); }
.icon-button:focus-visible, .filter-chip:focus-visible, .action-button:focus-visible, input:focus-visible, .complete-check:focus-visible { outline: 3px solid color-mix(in srgb, var(--blue) 35%, transparent); outline-offset: 2px; }
main {
width: min(1184px, calc(100% - 40px));
margin: 0 auto;
}
.hero, .course-hero {
position: relative;
overflow: hidden;
display: grid;
grid-template-columns: minmax(0, 1fr) auto;
gap: 48px;
align-items: center;
min-height: 330px;
margin-top: 24px;
padding: clamp(34px, 6vw, 72px);
border-radius: 34px;
color: #f7fbf8;
background: #163b49;
box-shadow: var(--shadow);
}
.hero::after, .course-hero::after {
content: "";
position: absolute;
width: 260px;
height: 260px;
right: -65px;
bottom: -120px;
border: 42px solid rgba(216, 242, 106, .16);
border-radius: 50%;
}
.hero h1, .course-hero h1 {
max-width: 760px;
margin: 7px 0 16px;
font-size: clamp(2.5rem, 6vw, 5.2rem);
line-height: .98;
letter-spacing: -.065em;
}
.course-hero h1 { font-size: clamp(2.15rem, 5vw, 4.2rem); }
.eyebrow {
margin: 0;
color: var(--accent-strong);
font-size: .75rem;
font-weight: 850;
letter-spacing: .16em;
text-transform: uppercase;
}
.hero .eyebrow, .course-hero .eyebrow { color: var(--accent); }
.hero-copy {
max-width: 650px;
margin: 0;
color: rgba(247, 251, 248, .72);
font-size: clamp(1rem, 2vw, 1.18rem);
}
.hero-source {
display: inline-flex;
margin-top: 22px;
color: var(--accent);
font-size: .86rem;
font-weight: 800;
text-decoration: none;
}
.hero-orbit {
position: relative;
z-index: 1;
display: grid;
place-items: center;
align-content: center;
width: 190px;
aspect-ratio: 1;
border: 1px solid rgba(255, 255, 255, .2);
border-radius: 50%;
background: rgba(255, 255, 255, .06);
backdrop-filter: blur(12px);
}
.orbit-number { font-size: 3.2rem; font-weight: 800; letter-spacing: -.06em; }
.orbit-label { max-width: 100px; color: rgba(255,255,255,.65); font-size: .75rem; text-align: center; }
.stat-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 14px;
margin: 16px 0 76px;
}
.stat-card {
min-height: 118px;
padding: 24px;
border: 1px solid var(--line);
border-radius: var(--radius);
background: var(--surface);
}
.stat-label { display: block; color: var(--muted); font-size: .82rem; }
.stat-card strong { display: block; margin-top: 8px; font-size: 1.8rem; letter-spacing: -.04em; }
.library-section { margin-bottom: 70px; }
.section-heading {
display: flex;
align-items: end;
justify-content: space-between;
gap: 24px;
margin-bottom: 26px;
}
.section-heading h2 { margin: 5px 0 0; font-size: clamp(1.8rem, 4vw, 3rem); letter-spacing: -.045em; }
.search-box {
display: flex;
align-items: center;
gap: 10px;
min-width: min(330px, 100%);
padding: 0 15px;
border: 1px solid var(--line);
border-radius: 15px;
color: var(--muted);
background: var(--surface);
}
.search-box input {
width: 100%;
padding: 13px 0;
border: 0;
outline: 0;
color: var(--ink);
background: transparent;
}
.course-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }
.course-card {
display: flex;
flex-direction: column;
min-height: 300px;
padding: 26px;
border: 1px solid var(--line);
border-radius: 26px;
background: var(--surface);
box-shadow: 0 6px 24px rgba(37,48,52,.04);
transition: transform .2s ease, box-shadow .2s ease;
}
.course-card:hover { transform: translateY(-4px); box-shadow: var(--shadow); }
.course-card-top { display: flex; justify-content: space-between; align-items: center; gap: 12px; }
.course-code { color: var(--muted); font-size: .75rem; font-weight: 750; letter-spacing: .08em; text-transform: uppercase; }
.course-badge { padding: 5px 9px; border-radius: 999px; color: var(--blue); background: var(--blue-soft); font-size: .72rem; font-weight: 750; }
.course-card h3 { margin: 36px 0 10px; font-size: 1.4rem; line-height: 1.28; letter-spacing: -.025em; }
.course-card-meta { margin: 0; color: var(--muted); font-size: .85rem; }
.course-card-bottom { margin-top: auto; }
.progress-track { height: 7px; margin: 28px 0 12px; overflow: hidden; border-radius: 99px; background: var(--line); }
.progress-track span { display: block; width: var(--progress); height: 100%; border-radius: inherit; background: var(--accent-strong); }
.progress-copy { display: flex; justify-content: space-between; color: var(--muted); font-size: .78rem; }
.course-link { display: inline-flex; align-items: center; gap: 8px; margin-top: 22px; color: var(--ink); font-weight: 800; text-decoration: none; }
.course-link span { transition: transform .18s ease; }
.course-link:hover span { transform: translateX(4px); }
.breadcrumbs { display: flex; gap: 9px; margin: 24px 4px 14px; color: var(--muted); font-size: .85rem; }
.breadcrumbs a { text-decoration: none; }
.course-hero { min-height: 300px; margin-top: 0; }
.course-heading { position: relative; z-index: 1; }
.progress-panel { position: relative; z-index: 1; display: flex; align-items: center; gap: 18px; min-width: 250px; }
.progress-panel > div:last-child { display: grid; }
.progress-panel span { color: rgba(255,255,255,.62); font-size: .78rem; }
.progress-ring {
display: grid;
place-items: center;
width: 100px;
aspect-ratio: 1;
border-radius: 50%;
background: radial-gradient(circle closest-side, #163b49 78%, transparent 80% 100%), conic-gradient(var(--accent) calc(var(--progress) * 1%), rgba(255,255,255,.14) 0);
}
.progress-ring span { color: #fff; font-size: 1.25rem; font-weight: 850; }
.course-toolbar {
position: sticky;
top: 12px;
z-index: 5;
display: flex;
justify-content: space-between;
gap: 18px;
margin: 22px 0 34px;
padding: 13px;
border: 1px solid var(--line);
border-radius: 20px;
background: color-mix(in srgb, var(--paper) 84%, transparent);
backdrop-filter: blur(18px);
}
.resource-search { flex: 1; max-width: 420px; }
.filter-group { display: flex; gap: 7px; overflow-x: auto; }
.filter-chip { padding: 10px 14px; border: 1px solid var(--line); border-radius: 12px; color: var(--muted); background: var(--surface); cursor: pointer; white-space: nowrap; }
.filter-chip.active { border-color: var(--ink); color: var(--paper); background: var(--ink); }
.section-list { display: grid; gap: 30px; margin-bottom: 70px; }
.resource-section { overflow: hidden; border: 1px solid var(--line); border-radius: 24px; background: var(--surface); }
.resource-section-header { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 7px 16px; padding: 22px 24px; border-bottom: 1px solid var(--line); }
.resource-section-header h2 { margin: 0; font-size: 1.12rem; }
.resource-section-header span { color: var(--muted); font-size: .8rem; }
.section-summary { grid-column: 1 / -1; max-width: 850px; margin: 0; color: var(--muted); font-size: .82rem; }
.resource-list { display: grid; }
.resource-row {
display: grid;
grid-template-columns: 38px minmax(0, 1fr) auto auto auto;
gap: 16px;
align-items: center;
min-height: 88px;
padding: 14px 22px;
border-bottom: 1px solid var(--line);
}
.resource-row:last-child { border-bottom: 0; }
.resource-row:hover { background: color-mix(in srgb, var(--blue-soft) 34%, transparent); }
.resource-index { color: var(--muted); font-size: .75rem; font-variant-numeric: tabular-nums; }
.resource-main { min-width: 0; }
.resource-title { display: block; overflow: hidden; font-weight: 730; text-overflow: ellipsis; white-space: nowrap; }
.resource-file { display: block; overflow: hidden; margin-top: 4px; color: var(--muted); font-size: .78rem; text-overflow: ellipsis; white-space: nowrap; }
.resource-description { display: -webkit-box; overflow: hidden; margin-top: 5px; color: var(--muted); font-size: .76rem; -webkit-box-orient: vertical; -webkit-line-clamp: 2; }
.resource-meta { display: flex; gap: 8px; align-items: center; color: var(--muted); font-size: .74rem; white-space: nowrap; }
.type-pill { padding: 4px 8px; border-radius: 8px; color: var(--blue); background: var(--blue-soft); font-weight: 750; }
.status-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--accent-strong); }
.status-dot.missing { background: var(--danger); }
.status-dot.online { background: var(--blue); }
.action-button { min-width: 70px; padding: 9px 12px; border: 1px solid var(--line); border-radius: 11px; color: var(--ink); background: var(--surface-strong); cursor: pointer; font-weight: 750; text-align: center; text-decoration: none; }
.action-button[aria-disabled="true"] { color: var(--muted); cursor: not-allowed; opacity: .6; }
.complete-check { width: 20px; height: 20px; accent-color: var(--accent-strong); cursor: pointer; }
.resource-row.completed .resource-title { color: var(--muted); text-decoration: line-through; }
.empty-state { padding: 60px 24px; border: 1px dashed var(--line); border-radius: var(--radius); color: var(--muted); text-align: center; }
.empty-state strong, .empty-state span { display: block; }
.empty-state strong { color: var(--ink); font-size: 1.1rem; }
.media-dialog { width: min(1000px, calc(100% - 30px)); padding: 20px; border: 1px solid var(--line); border-radius: 24px; color: var(--ink); background: var(--surface); box-shadow: 0 30px 100px rgba(0,0,0,.4); }
.media-dialog::backdrop { background: rgba(8, 15, 17, .76); backdrop-filter: blur(7px); }
.dialog-heading { display: flex; align-items: center; justify-content: space-between; gap: 20px; margin-bottom: 16px; }
.dialog-heading h2 { margin: 4px 0 0; font-size: 1.2rem; }
.media-dialog video { display: block; width: 100%; max-height: 72vh; border-radius: 15px; background: #000; }
footer { width: min(1184px, calc(100% - 40px)); margin: 0 auto; padding: 28px 0 40px; display: flex; justify-content: space-between; gap: 20px; border-top: 1px solid var(--line); color: var(--muted); font-size: .78rem; }
footer a { text-decoration: none; font-weight: 700; }
@media (max-width: 900px) {
.hero, .course-hero { grid-template-columns: 1fr; gap: 28px; }
.hero-orbit { width: 145px; }
.stat-grid, .course-grid { grid-template-columns: repeat(2, 1fr); }
.course-toolbar { position: static; flex-direction: column; }
.resource-search { max-width: none; }
.resource-row { grid-template-columns: 30px minmax(0, 1fr) auto auto; }
.resource-meta { display: none; }
}
@media (max-width: 600px) {
.topbar { padding: 18px 20px; }
main { width: min(100% - 24px, 1184px); }
.hero, .course-hero { min-height: auto; padding: 34px 24px; border-radius: 24px; }
.hero h1, .course-hero h1 { letter-spacing: -.045em; }
.stat-grid { grid-template-columns: repeat(2, 1fr); margin-bottom: 54px; }
.stat-card { min-height: 100px; padding: 18px; }
.section-heading { align-items: stretch; flex-direction: column; }
.course-grid { grid-template-columns: 1fr; }
.progress-panel { min-width: 0; }
.course-toolbar { border-radius: 17px; }
.resource-row { grid-template-columns: 24px minmax(0, 1fr) auto; gap: 10px; padding: 13px 14px; }
.complete-check { display: none; }
.action-button { min-width: 58px; }
footer { width: calc(100% - 28px); flex-direction: column; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { scroll-behavior: auto !important; transition: none !important; }
}
+85
View File
@@ -1,5 +1,6 @@
import email.message
import http.client
import json
import os
import sys
import tempfile
@@ -10,18 +11,22 @@ from types import SimpleNamespace
from unittest.mock import patch
from ravin_downloader import (
Course,
FileItem,
MoodleClient,
_CourseStructureParser,
_FormParser,
_LinkParser,
_clean_name,
_browser_login_url,
_build_library_catalog,
_capture_browser_session,
_filename_from_headers,
_is_cloudflare_challenge,
_load_env_file,
_parse_moodle_config,
_save_env_values,
_write_library_site,
_unique,
build_parser,
)
@@ -74,6 +79,13 @@ class ParserTests(unittest.TestCase):
self.assertEqual(args.command, "login")
self.assertFalse(args.manual_session)
def test_library_commands_parse(self):
build = build_parser().parse_args(["library", "44", "--output", "my-library"])
self.assertEqual(build.course_ids, [44])
self.assertEqual(build.output, Path("my-library"))
serve = build_parser().parse_args(["serve-library", "--port", "9000"])
self.assertEqual(serve.port, 9000)
def test_browser_login_captures_user_agent_and_cookies(self):
class FakeLaunchLink:
def is_displayed(self):
@@ -207,6 +219,27 @@ class ParserTests(unittest.TestCase):
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_parses_course_chapters_and_activities(self):
parser = _CourseStructureParser("https://training.example/course/view.php?id=44")
parser.feed(
'<li id="section-2" data-for="section" data-id="940" '
'data-sectionid="2" data-sectionname="Chapter 1">'
'<input type="checkbox">'
'<div class="summary"><p>Core networking concepts</p></div>'
'<ul><li class="activity resource modtype_resource" data-for="cmitem" data-id="4940">'
'<div data-activityname="Introduction to Networks">'
'<img src="icon.png"><a href="/mod/resource/view.php?id=4940">Lesson</a>'
'<span class="activitybadge">MP4</span><button class="btn-subtle-success">Done</button>'
'</div></li></ul></li>'
)
sections = parser.result()
self.assertEqual(sections[0]["name"], "Chapter 1")
self.assertEqual(sections[0]["summary"], "Core networking concepts")
self.assertEqual(sections[0]["activities"][0]["id"], 4940)
self.assertEqual(sections[0]["activities"][0]["type"], "resource")
self.assertEqual(sections[0]["activities"][0]["badge"], "MP4")
self.assertTrue(sections[0]["activities"][0]["lms_completed"])
def test_filename_prefers_content_disposition(self):
headers = email.message.Message()
headers["Content-Disposition"] = "attachment; filename*=UTF-8''lesson%201.mp4"
@@ -245,6 +278,58 @@ class ParserTests(unittest.TestCase):
)
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
def test_builds_static_library_catalog_from_downloads(self):
class FakeClient:
site = "https://training.example"
def list_courses(self):
return [Course(44, "Network +", "NET-44")]
def list_files(self, course_id):
self.assert_course_id = course_id
return [
FileItem(
44,
"Course files",
"Introduction فایل",
"1.mp4",
"https://training.example/pluginfile.php/10/1.mp4?token=secret",
"video/mp4",
10,
),
FileItem(
44,
"Course files",
"Notes فایل",
"notes.pdf",
"https://training.example/pluginfile.php/11/notes.pdf",
"application/pdf",
20,
),
]
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
downloads = root / "downloads"
output = root / "library"
video = downloads / "44" / "Course files" / "1.mp4"
video.parent.mkdir(parents=True)
video.write_bytes(b"video")
catalog = _build_library_catalog(FakeClient(), downloads, output)
self.assertEqual(catalog["stats"]["courses"], 1)
self.assertEqual(catalog["stats"]["downloaded_files"], 1)
items = catalog["courses"][0]["sections"][0]["items"]
self.assertEqual(items[0]["title"], "Introduction")
self.assertEqual(items[0]["kind"], "video")
self.assertEqual(items[0]["status"], "downloaded")
self.assertEqual(items[0]["local_url"], "../downloads/44/Course%20files/1.mp4")
self.assertEqual(items[1]["status"], "missing")
catalog_path = _write_library_site(output, catalog)
written = json.loads(catalog_path.read_text(encoding="utf-8"))
self.assertEqual(written["schema_version"], 2)
self.assertTrue((output / "index.html").is_file())
self.assertTrue((output / "course.html").is_file())
def test_interrupted_download_retries_with_range(self):
first = _FakeResponse(
[