implement resume downloading

This commit is contained in:
Meghdad committed 2026-08-02 22:02:42 +03:30
1 parent 187878a774
commit a3acea6457
4 files changed
+201 -34

No files matched your search

+1
View File
@@ -6,6 +6,7 @@ All notable changes to this project will be documented here.
- List enrolled Moodle courses through the mobile API or authenticated AJAX fallback. - List enrolled Moodle courses through the mobile API or authenticated AJAX fallback.
- List and download accessible course resources with safe partial-file handling. - List and download accessible course resources with safe partial-file handling.
- Resume interrupted files with HTTP byte ranges and automatic retry backoff.
- Support Cloudflare-protected sites through a user-provided browser session. - Support Cloudflare-protected sites through a user-provided browser session.
- Load and securely update credentials and browser-session values in a Git-ignored `.env` file. - Load and securely update credentials and browser-session values in a Git-ignored `.env` file.
- Provide JSON output for scripting. - Provide JSON output for scripting.
+1 -1
View File
@@ -32,7 +32,7 @@ ravin-downloader files COURSE_ID
ravin-downloader download COURSE_ID ravin-downloader download COURSE_ID
``` ```
Files are saved under `downloads/<course-id>/...`. Existing completed files are skipped; interrupted downloads use a temporary `.part` suffix. Use `--overwrite` if you want to replace existing files. 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.
For scripting, use JSON output: For scripting, use JSON output:
+129 -33
View File
@@ -14,6 +14,7 @@ import argparse
import getpass import getpass
import html import html
import http.cookiejar import http.cookiejar
import http.client
import json import json
import mimetypes import mimetypes
import os import os
@@ -591,7 +592,14 @@ class MoodleClient:
url=url, url=url,
) )
def download(self, item: FileItem, root: Path, overwrite: bool = False) -> Path: def download(
self,
item: FileItem,
root: Path,
overwrite: bool = False,
retries: int = 5,
retry_delay: float = 1.0,
) -> Path:
section = _clean_name(item.section, "Course files") section = _clean_name(item.section, "Course files")
activity = _clean_name(item.activity, "activity") activity = _clean_name(item.activity, "activity")
directory = root / _clean_name(str(item.course_id), "course") / section directory = root / _clean_name(str(item.course_id), "course") / section
@@ -604,38 +612,120 @@ class MoodleClient:
query.setdefault("token", self.token) query.setdefault("token", self.token)
url = parts._replace(query=urllib.parse.urlencode(query)).geturl() url = parts._replace(query=urllib.parse.urlencode(query)).geturl()
with self._request(url, timeout=120) as response: suggested_filename = _clean_name(item.filename, activity)
filename = _filename_from_headers(response.headers, response.geturl(), activity) destination = directory / suggested_filename
destination = directory / filename if destination.exists() and not overwrite:
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 return destination
temporary = destination.with_name(destination.name + ".part")
if overwrite:
temporary.unlink(missing_ok=True)
expected_total = item.filesize
started = time.monotonic()
retry_number = 0
while True:
resume_at = temporary.stat().st_size if temporary.exists() else 0
headers: dict[str, str] = {}
if resume_at:
headers["Range"] = f"bytes={resume_at}-"
try:
with self._request(url, headers=headers, timeout=120) as response:
status_code = getattr(response, "status", response.getcode())
response_filename = _filename_from_headers(response.headers, response.geturl(), activity)
if not temporary.exists() and response_filename != suggested_filename:
destination = directory / response_filename
if destination.exists() and not overwrite:
return destination
temporary = destination.with_name(destination.name + ".part")
resume_at = temporary.stat().st_size if temporary.exists() else 0
content_range = response.headers.get("Content-Range", "")
range_match = re.fullmatch(r"bytes\s+(\d+)-(\d+)/(\d+|\*)", content_range.strip(), flags=re.I)
if resume_at and status_code == 206:
if not range_match or int(range_match.group(1)) != resume_at:
raise MoodleError("server returned an unexpected byte range")
if range_match.group(3) != "*":
expected_total = int(range_match.group(3))
file_mode = "ab"
downloaded = resume_at
elif resume_at and status_code == 200:
print(
f"warning: server did not honor resume for {destination.name}; restarting this file",
file=sys.stderr,
)
file_mode = "wb"
downloaded = 0
resume_at = 0
else:
file_mode = "wb"
downloaded = 0
content_length = response.headers.get("Content-Length", "")
if expected_total is None and content_length.isdigit():
expected_total = downloaded + int(content_length)
with temporary.open(file_mode) as output:
while True:
try:
chunk = response.read(1024 * 1024)
except http.client.IncompleteRead as exc:
if exc.partial:
output.write(exc.partial)
downloaded += len(exc.partial)
output.flush()
raise
if not chunk:
break
output.write(chunk)
downloaded += len(chunk)
if sys.stderr.isatty():
if expected_total:
progress = f"{downloaded / expected_total:6.1%}"
else:
progress = f"{downloaded / 1024 / 1024:7.1f} MiB"
print(
f"\r {progress} {destination.name[:60]}",
end="",
file=sys.stderr,
flush=True,
)
if expected_total is not None and downloaded != expected_total:
raise MoodleError(
f"connection closed early at {downloaded} of {expected_total} 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) {destination.name}",
file=sys.stderr,
)
return destination
except (
MoodleError,
http.client.IncompleteRead,
http.client.RemoteDisconnected,
ConnectionError,
TimeoutError,
OSError,
) as exc:
retry_number += 1
if retry_number > retries:
saved = temporary.stat().st_size if temporary.exists() else 0
raise MoodleError(
f"download failed after {retries + 1} attempts; "
f"kept {saved / 1024 / 1024:.1f} MiB in {temporary} ({exc})"
) from exc
saved = temporary.stat().st_size if temporary.exists() else 0
delay = min(retry_delay * (2 ** (retry_number - 1)), 15.0)
print(
f"\n connection interrupted; retry {retry_number}/{retries} "
f"from {saved / 1024 / 1024:.1f} MiB in {delay:g}s",
file=sys.stderr,
)
if delay:
time.sleep(delay)
def _env_value(args: argparse.Namespace, key: str) -> str: def _env_value(args: argparse.Namespace, key: str) -> str:
@@ -845,6 +935,7 @@ def build_parser() -> argparse.ArgumentParser:
download_parser.add_argument("course_id", type=int) download_parser.add_argument("course_id", type=int)
download_parser.add_argument("--output", type=Path, default=Path("downloads")) download_parser.add_argument("--output", type=Path, default=Path("downloads"))
download_parser.add_argument("--overwrite", action="store_true") download_parser.add_argument("--overwrite", action="store_true")
download_parser.add_argument("--retries", type=int, default=5, help="retry interrupted files (default: 5)")
return parser return parser
@@ -905,7 +996,12 @@ def main(argv: list[str] | None = None) -> int:
downloaded: list[str] = [] downloaded: list[str] = []
for number, item in enumerate(files, 1): for number, item in enumerate(files, 1):
print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr) print(f"[{number}/{len(files)}] {item.activity}: {item.filename}", file=sys.stderr)
path = client.download(item, args.output, overwrite=args.overwrite) path = client.download(
item,
args.output,
overwrite=args.overwrite,
retries=max(args.retries, 0),
)
downloaded.append(str(path)) downloaded.append(str(path))
if args.json: if args.json:
print(json.dumps(downloaded, ensure_ascii=False, indent=2)) print(json.dumps(downloaded, ensure_ascii=False, indent=2))
+70
View File
@@ -1,4 +1,5 @@
import email.message import email.message
import http.client
import os import os
import tempfile import tempfile
import unittest import unittest
@@ -6,6 +7,7 @@ from pathlib import Path
from ravin_downloader import ( from ravin_downloader import (
FileItem, FileItem,
MoodleClient,
_FormParser, _FormParser,
_LinkParser, _LinkParser,
_clean_name, _clean_name,
@@ -18,6 +20,47 @@ from ravin_downloader import (
) )
class _FakeResponse:
def __init__(self, chunks, *, status=200, content_range=""):
self.chunks = list(chunks)
self.status = status
self.headers = email.message.Message()
self.headers["Content-Disposition"] = 'attachment; filename="file.bin"'
if content_range:
self.headers["Content-Range"] = content_range
def __enter__(self):
return self
def __exit__(self, *_args):
return False
def getcode(self):
return self.status
def geturl(self):
return "https://training.example/pluginfile.php/file.bin"
def read(self, _size):
if not self.chunks:
return b""
value = self.chunks.pop(0)
if isinstance(value, BaseException):
raise value
return value
class _FakeDownloadClient(MoodleClient):
def __init__(self, responses):
super().__init__("https://training.example")
self.responses = list(responses)
self.request_headers = []
def _request(self, _path_or_url, *, data=None, headers=None, timeout=45):
self.request_headers.append(headers or {})
return self.responses.pop(0)
class ParserTests(unittest.TestCase): class ParserTests(unittest.TestCase):
def test_parses_login_form_and_hidden_token(self): def test_parses_login_form_and_hidden_token(self):
parser = _FormParser() parser = _FormParser()
@@ -83,6 +126,33 @@ class ParserTests(unittest.TestCase):
) )
self.assertEqual(os.stat(path).st_mode & 0o777, 0o600) self.assertEqual(os.stat(path).st_mode & 0o777, 0o600)
def test_interrupted_download_retries_with_range(self):
first = _FakeResponse(
[
b"abcde",
http.client.IncompleteRead(b"xyz", 2),
]
)
second = _FakeResponse([b"!!"], status=206, content_range="bytes 8-9/10")
client = _FakeDownloadClient([first, second])
item = FileItem(44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin")
with tempfile.TemporaryDirectory() as directory:
destination = client.download(item, Path(directory), retries=1, retry_delay=0)
self.assertEqual(destination.read_bytes(), b"abcdexyz!!")
self.assertEqual(client.request_headers, [{}, {"Range": "bytes=8-"}])
def test_existing_partial_download_is_resumed(self):
response = _FakeResponse([b"67890"], status=206, content_range="bytes 5-9/10")
client = _FakeDownloadClient([response])
item = FileItem(44, "Course files", "Lesson", "file.bin", "https://training.example/file.bin")
with tempfile.TemporaryDirectory() as directory:
partial = Path(directory) / "44" / "Course files" / "file.bin.part"
partial.parent.mkdir(parents=True)
partial.write_bytes(b"12345")
destination = client.download(item, Path(directory), retries=0, retry_delay=0)
self.assertEqual(destination.read_bytes(), b"1234567890")
self.assertEqual(client.request_headers, [{"Range": "bytes=5-"}])
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()