feat(downloader): add M4B download pipeline with resume (closes #5)

Add streaming chunked M4B download via .partial files and atomic
rename, resume support through HTTP Range headers, full CLI
orchestration loop, --verbose flag, and config/secrets templates.

Fix 4 API-shape bugs found during live testing: library endpoint
returns audiobooks not books, M4B endpoint returns m4b_url not url,
narrators nested under audiobook_info, and ISBN int/str type mismatch
in history lookup causing re-downloads.

12 new tests (109 total). 6 books downloaded live (~2.9 GB).
This commit is contained in:
AlexKucera committed 2026-06-03 12:56:41 +02:00
1 parent 25ee66b95d
commit 33aa80b7aa
11 files changed
+989 -15

No files matched your search

+126 -6
View File
@@ -1,12 +1,14 @@
"""CLI entry point — wire config → auth → fetch library → filter → print."""
"""CLI entry point — wire config → auth → fetch library → download → history."""
import sys
from pathlib import Path
from rich.console import Console
from librofm_downloader.config import load_config, ConfigError
from librofm_downloader.client import LibroFmClient, AuthError
from librofm_downloader.history import DownloadHistory
from librofm_downloader.downloader import Book, download_book
console = Console()
@@ -15,18 +17,43 @@ def run(
config_path: str = "config.yaml",
secrets_path: str = "secrets.yaml",
history_path: str = "download_history.json",
verbose: bool = False,
) -> int:
"""Main pipeline: load config → auth → fetch library → filter → print.
"""Main pipeline: load config → auth → fetch library → filter → download → summary.
Args:
config_path: Path to config.yaml.
secrets_path: Path to secrets.yaml (gitignored).
history_path: Path to download_history.json.
verbose: Print extra detail (URLs, paths, API responses).
Returns:
Exit code: 0 on success, 1 on failure.
"""
if verbose:
console.print("[dim]── config ──────────────────────────────────────[/dim]")
console.print(f" config: {config_path}")
console.print(f" secrets: {secrets_path}")
console.print(f" history: {history_path}")
# 1. Load config
try:
config = load_config(config_path, secrets_path)
except ConfigError as exc:
console.print(f"[red]Config error:[/red] {exc}")
return 1
if verbose:
console.print(f" format: {config.format}")
console.print(f" output: {config.output_dir}")
console.print(f" extras: {config.download_extras}")
console.print(f" covers: {config.download_covers}")
console.print(f" user: {config.username}")
# 2. Authenticate
if verbose:
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
client = LibroFmClient(
username=config.username,
password=config.password,
@@ -38,23 +65,116 @@ def run(
console.print(f"[red]Authentication failed:[/red] {exc}")
return 1
if verbose:
console.print(" [green]✓[/green] authenticated")
# 3. Fetch library
if verbose:
console.print("[dim]── library ─────────────────────────────────────[/dim]")
try:
books = client.fetch_library()
except Exception as exc:
console.print(f"[red]Failed to fetch library:[/red] {exc}")
return 1
if verbose:
console.print(f" {len(books)} book(s) in library")
# 4. Filter already-downloaded
if verbose:
console.print("[dim]── filtering ───────────────────────────────────[/dim]")
history = DownloadHistory(history_path)
new_books = [b for b in books if not history.is_downloaded(b.get("isbn", ""))]
if verbose:
downloaded_count = len(books) - len(new_books)
console.print(f" {downloaded_count} already downloaded, {len(new_books)} new")
if not new_books:
console.print("[green]All caught up! No new books to download.[/green]")
return 0
# 5. Download loop
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
for book in new_books:
title = book.get("title", "Unknown")
isbn = book.get("isbn", "?")
console.print(f" • {title} [dim]({isbn})[/dim]")
downloaded = 0
skipped = 0
failed = 0
for raw_book in new_books:
title = raw_book.get("title", "Unknown")
isbn = raw_book.get("isbn", "?")
authors = raw_book.get("authors", [])
# Narrators are nested inside audiobook_info in the API response
audiobook_info = raw_book.get("audiobook_info", {}) or {}
narrators = audiobook_info.get("narrators", []) or raw_book.get("narrators", [])
console.print(f" ⬇ {title} [dim]({isbn})[/dim]")
if verbose:
console.print(f" authors: {', '.join(authors) or '?'}")
console.print(f" narrators: {', '.join(narrators) or '?'}")
book = Book(
title=title,
authors=authors,
narrators=narrators,
isbn=isbn,
series=raw_book.get("series", ""),
series_num=raw_book.get("series_num"),
cover_url=raw_book.get("cover_url", ""),
# pdf_extras is a list inside audiobook_info in the API response
pdf_extras=bool(audiobook_info.get("pdf_extras")) if audiobook_info else False,
publication_year=raw_book.get("publication_year"),
publication_month=raw_book.get("publication_month"),
publication_day=raw_book.get("publication_day"),
)
try:
result = download_book(
book=book,
client=client,
output_base=config.output_dir,
history=history,
)
if result is None:
console.print(f" [yellow]⏭ Skipped (no M4B available)[/yellow]")
skipped += 1
else:
console.print(f" [green]✓ Downloaded → {result}[/green]")
if verbose:
console.print(f" [dim] {result.stat().st_size:,} bytes[/dim]")
downloaded += 1
except Exception as exc:
console.print(f" [red]✗ Failed: {exc}[/red]")
if verbose:
import traceback
traceback.print_exc()
failed += 1
# 6. Summary
console.print(f"\n[bold]Summary:[/bold] {downloaded} downloaded, {skipped} skipped, {failed} failed")
if verbose:
console.print("[dim]── done ────────────────────────────────────────[/dim]")
return 0
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Download audiobooks from Libro.fm")
parser.add_argument("--config", default="config.yaml", help="Path to config.yaml")
parser.add_argument("--secrets", default="secrets.yaml", help="Path to secrets.yaml")
parser.add_argument("--history", default="download_history.json", help="Path to download history JSON")
parser.add_argument("-v", "--verbose", action="store_true", help="Verbose output (URLs, sizes, tracebacks)")
args = parser.parse_args()
sys.exit(run(
config_path=args.config,
secrets_path=args.secrets,
history_path=args.history,
verbose=args.verbose,
))
+41 -1
View File
@@ -7,6 +7,10 @@ class AuthError(Exception):
"""Authentication failed (bad credentials, network error, etc.)."""
class M4BUnavailableError(Exception):
"""M4B format is not available for this book (404 from API)."""
class LibroFmClient:
"""Libro.fm API client with OAuth2 password grant and library fetching."""
@@ -93,7 +97,43 @@ class LibroFmClient:
resp = client.get(next_url)
resp.raise_for_status()
data = resp.json()
all_books.extend(data.get("books", []))
all_books.extend(data.get("audiobooks", []))
next_url = data.get("next_page") or None
return all_books
def fetch_m4b_url(self, isbn: str, transport: httpx.BaseTransport | None = None) -> str:
"""Fetch the M4B download URL for a given ISBN.
Args:
isbn: The ISBN of the audiobook.
transport: Optional httpx transport override for testing.
Returns:
The CDN URL string for the M4B file.
Raises:
AuthError: If not authenticated.
M4BUnavailableError: If the book has no M4B format available (404).
"""
if not self._access_token:
raise AuthError("Not authenticated. Call authenticate() first.")
headers = {**self.DEFAULT_HEADERS, "Authorization": f"Bearer {self._access_token}"}
client = httpx.Client(
base_url=self._base_url,
headers=headers,
timeout=self._timeout,
transport=transport,
)
resp = client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b")
if resp.status_code == 404:
raise M4BUnavailableError(f"M4B not available for ISBN {isbn}")
resp.raise_for_status()
data = resp.json()
return data["m4b_url"]
+123
View File
@@ -3,8 +3,17 @@
Pure logic module — no I/O, no network. All deterministic string manipulation.
"""
import logging
import re
from dataclasses import dataclass
from pathlib import Path
import httpx
from librofm_downloader.client import M4BUnavailableError
from librofm_downloader.history import HistoryEntry
logger = logging.getLogger(__name__)
# Characters that are unsafe in filesystem path components
_ILLEGAL_CHARS = str.maketrans("", "", "<>/\\|?*")
@@ -147,3 +156,117 @@ def needs_subdirectory(book: Book) -> bool:
Returns True when PDF extras or cover art are present.
"""
return bool(book.pdf_extras) or bool(book.cover_url)
# ---------------------------------------------------------------------------
# M4B streaming download
# ---------------------------------------------------------------------------
# Constants for M4B download
CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB
def download_m4b(
url: str,
output_path: Path | str,
transport: httpx.BaseTransport | None = None,
) -> Path:
"""Download an M4B file via streaming chunks.
Writes to ``{output_path}.partial`` during transfer, then atomically
renames to the final ``{output_path}`` on completion.
Args:
url: The CDN URL for the M4B file.
output_path: Destination path (will have .m4b extension).
transport: Optional httpx transport override for testing.
Returns:
The Path of the completed .m4b file.
"""
output_path = Path(output_path)
partial_path = output_path.with_suffix(output_path.suffix + ".partial")
# Ensure parent directory exists
output_path.parent.mkdir(parents=True, exist_ok=True)
# Resume support: detect existing partial file
resume_from = 0
if partial_path.exists():
resume_from = partial_path.stat().st_size
logger.info("Resuming download from byte %d", resume_from)
headers: dict[str, str] = {}
if resume_from > 0:
headers["Range"] = f"bytes={resume_from}-"
client = httpx.Client(transport=transport, follow_redirects=True)
mode = "ab" if resume_from > 0 else "wb"
with client.stream("GET", url, headers=headers) as resp:
resp.raise_for_status()
with open(partial_path, mode) as f:
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
f.write(chunk)
# Atomic rename from .partial to final filename
partial_path.rename(output_path)
logger.info("Downloaded %s → %s", url, output_path)
return output_path
def download_book(
book: Book,
client: "LibroFmClient",
output_base: Path | str,
history: "DownloadHistory",
transport: httpx.BaseTransport | None = None,
) -> Path | None:
"""Orchestrate a single book download: resolve path → query M4B → download → history.
Args:
book: The book metadata.
client: Authenticated LibroFmClient instance.
output_base: Base directory for downloads.
history: DownloadHistory instance to record successful downloads.
transport: Optional httpx transport override for testing.
Returns:
Path to the downloaded file, or None if M4B is unavailable (book skipped).
"""
from datetime import datetime, timezone
# 1. Resolve output path using Slice 3a logic
relative = resolve_path(book)
title_sanitized = sanitize(book.title)
if needs_subdirectory(book):
output_path = Path(output_base) / relative / f"{title_sanitized}.m4b"
else:
output_path = Path(output_base) / f"{relative}.m4b"
# 2. Query M4B availability
try:
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
except M4BUnavailableError:
logger.info("Skipping %s (%s): no M4B available", book.title, book.isbn)
return None
# 3. Download
result = download_m4b(m4b_url, output_path, transport=transport)
# 4. Write history entry (only after successful complete download)
entry = HistoryEntry(
isbn=book.isbn,
title=book.title,
format="m4b",
path=str(result),
downloaded_at=datetime.now(timezone.utc).isoformat(),
)
history.write(entry)
return result
+2 -2
View File
@@ -41,14 +41,14 @@ class DownloadHistory:
def find(self, isbn: str) -> HistoryEntry | None:
"""Look up a history entry by ISBN. Returns None if not found."""
entry_dict = self._data.get(isbn)
entry_dict = self._data.get(str(isbn))
if entry_dict is None:
return None
return HistoryEntry(**entry_dict)
def is_downloaded(self, isbn: str) -> bool:
"""Check whether an ISBN was previously downloaded."""
return isbn in self._data
return str(isbn) in self._data
def write(self, entry: HistoryEntry) -> None:
"""Persist a history entry to disk."""