feat(progress): add TTY-aware download reporting (closes #8)

Rich progress bars with live %/ETA/speed/file size for interactive
terminals; plain log lines for pipes/cron. Reads Content-Length from
HTTP response so percentage works from first chunk onward. Per-book
failure isolation prevents one bad book from stopping the batch.
18 new tests, 156 total passing.
This commit is contained in:
AlexKucera committed 2026-06-03 14:43:56 +02:00
1 parent aceaece504
commit 8004dcf315
8 files changed
+951 -11

No files matched your search

+10 -6
View File
@@ -9,6 +9,7 @@ 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
from librofm_downloader.progress import DownloadReporter
console = Console()
@@ -99,7 +100,8 @@ def run(
console.print("[green]All caught up! No new books to download.[/green]")
return 0
# 5. Download loop
# 5. Download loop with TTY-aware reporting
reporter = DownloadReporter()
console.print(f"\n[bold]{len(new_books)} book(s) to download:[/bold]\n")
downloaded = 0
@@ -113,9 +115,9 @@ def run(
# 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" ⬇ {title} [dim]({isbn})[/dim]")
console.print(f" authors: {', '.join(authors) or '?'}")
console.print(f" narrators: {', '.join(narrators) or '?'}")
@@ -135,6 +137,7 @@ def run(
)
try:
reporter.start_download(book)
result = download_book(
book=book,
client=client,
@@ -142,24 +145,25 @@ def run(
history=history,
format_strategy=config.format,
config=config,
progress=reporter.update,
)
if result is None:
console.print(f" [yellow]⏭ Skipped[/yellow]")
skipped += 1
else:
console.print(f" [green]✓ Downloaded → {result}[/green]")
reporter.complete(book)
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]")
reporter.fail(book, reason=str(exc))
if verbose:
import traceback
traceback.print_exc()
failed += 1
# 6. Summary
console.print(f"\n[bold]Summary:[/bold] {downloaded} downloaded, {skipped} skipped, {failed} failed")
reporter.summary(downloaded=downloaded, skipped=skipped, failed=failed)
if verbose:
console.print("[dim]── done ────────────────────────────────────────[/dim]")
+30 -3
View File
@@ -181,6 +181,7 @@ def download_zip_part(
url: str,
output_dir: Path | str,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
) -> list[Path]:
"""Download a single ZIP part and extract its contents.
@@ -222,8 +223,19 @@ def download_zip_part(
with client.stream("GET", url, headers=headers) as resp:
resp.raise_for_status()
with open(partial_path, mode) as f:
downloaded = resume_from
content_length: int | None = None
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
f.write(chunk)
downloaded += len(chunk)
if progress:
if content_length is None:
cl_header = resp.headers.get("content-length")
if cl_header:
content_length = int(cl_header)
progress(downloaded, total=content_length)
else:
progress(downloaded)
# Atomic rename from .partial to .zip
partial_path.rename(zip_path)
@@ -251,6 +263,7 @@ def download_m4b(
url: str,
output_path: Path | str,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
) -> Path:
"""Download an M4B file via streaming chunks.
@@ -289,8 +302,19 @@ def download_m4b(
resp.raise_for_status()
with open(partial_path, mode) as f:
downloaded = resume_from
content_length: int | None = None
for chunk in resp.iter_bytes(chunk_size=CHUNK_SIZE):
f.write(chunk)
downloaded += len(chunk)
if progress:
if content_length is None:
cl_header = resp.headers.get("content-length")
if cl_header:
content_length = int(cl_header)
progress(downloaded, total=content_length)
else:
progress(downloaded)
# Atomic rename from .partial to final filename
partial_path.rename(output_path)
@@ -325,6 +349,7 @@ def download_book(
format_strategy: str = "m4b_mp3_fallback",
config: "Config | None" = None,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
) -> Path | None:
"""Orchestrate a single book download with format strategy.
@@ -352,7 +377,7 @@ def download_book(
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
title_sanitized = sanitize(book.title)
m4b_path = output_dir / f"{title_sanitized}.m4b"
result = download_m4b(m4b_url, m4b_path, transport=transport)
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress)
_write_history(history, book, "m4b", str(result))
if config:
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
@@ -379,7 +404,7 @@ def download_book(
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
title_sanitized = sanitize(book.title)
m4b_path = output_dir / f"{title_sanitized}.m4b"
result = download_m4b(m4b_url, m4b_path, transport=transport)
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress)
_write_history(history, book, "m4b", str(result))
if config:
download_accompanying_files(book, output_dir, config, client=client, transport=transport)
@@ -397,6 +422,7 @@ def _download_mp3(
output_dir: Path,
history: "DownloadHistory",
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
) -> Path | None:
"""Fetch MP3 manifest and download all ZIP parts."""
try:
@@ -413,7 +439,7 @@ def _download_mp3(
all_extracted: list[Path] = []
for part in parts:
part_url = part["url"]
extracted = download_zip_part(part_url, output_dir, transport=transport)
extracted = download_zip_part(part_url, output_dir, transport=transport, progress=progress)
all_extracted.extend(extracted)
# Record first extracted file as representative path
@@ -511,6 +537,7 @@ def download_accompanying_files(
config: "Config",
client: "LibroFmClient | None" = None,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
) -> list[Path]:
"""Download PDF extras and/or cover art for a book.
+153
View File
@@ -0,0 +1,153 @@
"""User-facing output polish — Issue #8.
TTY-aware download reporting:
- TTY (interactive): rich.Progress bars with %, speed, ETA, size
- Non-TTY (cron/pipe): plain log lines
All output goes through DownloadReporter so cli.py stays clean.
"""
from __future__ import annotations
import sys
import time
from typing import IO, TextIO
class PlainTextReporter:
"""Plain-text log lines for non-TTY output (cron, piped)."""
def __init__(self, stdout: TextIO | None = None) -> None:
self._out: TextIO = stdout or sys.stdout
def start_download(self, book, total_bytes: int = 0) -> None:
"""Log download start with author, title, and file size."""
authors = ", ".join(book.authors) if book.authors else "Unknown"
size_str = _fmt_size(total_bytes)
self._print(f"Downloading: {authors} - {book.title} ({size_str})")
def complete(self, book) -> None:
"""Log successful completion."""
authors = ", ".join(book.authors) if book.authors else "Unknown"
self._print(f"Completed: {authors} - {book.title}")
def fail(self, book, reason: str = "") -> None:
"""Log failure with ISBN, title, and error reason."""
authors = ", ".join(book.authors) if book.authors else "Unknown"
detail = f" ({reason})" if reason else ""
self._print(f"Failed: {authors} - {book.title} [{book.isbn}]{detail}")
def update(self, completed: int, *, total: int | None = None) -> None:
"""No-op progress update — plain text mode has no progress bar."""
def summary(self, downloaded: int, skipped: int, failed: int) -> None:
"""Print summary line."""
self._print(f"\nSummary: {downloaded} downloaded, {skipped} skipped, {failed} failed")
def _print(self, message: str) -> None:
self._out.write(message + "\n")
self._out.flush()
class ProgressReporter:
"""Rich Progress-based reporter for TTY (interactive) output."""
def __init__(self, stdout: TextIO | None = None) -> None:
from rich.console import Console
self._console = Console(file=stdout or sys.stdout)
self._progress = None # Lazy init on first download
def start_download(self, book, total_bytes: int = 0) -> None:
"""Start a progress bar for this book's download."""
from rich.progress import (
BarColumn,
DownloadColumn,
Progress,
TimeRemainingColumn,
TransferSpeedColumn,
)
if self._progress is None:
self._progress = Progress(
"[progress.description]{task.description}",
BarColumn(),
"[progress.percentage]{task.percentage:>3.1f}%",
TransferSpeedColumn(),
TimeRemainingColumn(),
DownloadColumn(),
console=self._console,
)
self._progress.start()
authors = ", ".join(book.authors) if book.authors else "Unknown"
description = f"{authors} - {book.title}"
task_id = self._progress.add_task(description, total=total_bytes or None)
# Store task_id on self for update() to find it
# In practice we'd track per-book; for now store as current
self._current_task = task_id
self._current_book = book
self._start_time = time.monotonic()
def update(self, completed: int, *, total: int | None = None) -> None:
"""Update progress bar with bytes completed.
If *total* is provided (e.g. from a Content-Length header), also
updates the task's total so that percentage and ETA can be computed.
"""
if self._progress and hasattr(self, "_current_task"):
kwargs: dict = {"completed": completed}
if total is not None:
kwargs["total"] = total
self._progress.update(self._current_task, **kwargs)
def complete(self, book) -> None:
"""Mark current progress bar as complete."""
if self._progress and hasattr(self, "_current_task"):
self._progress.update(self._current_task, completed=self._progress.tasks[self._current_task].total or 0)
self._console.print(f" [green]✓[/green] {book.title}")
self._current_task = None
def fail(self, book, reason: str = "") -> None:
"""Mark current progress bar as failed."""
if self._progress and hasattr(self, "_current_task"):
self._progress.stop_task(self._current_task)
detail = f" ({reason})" if reason else ""
self._console.print(f" [red]✗[/red] {book.title}[dim] [{book.isbn}]{detail}[/dim]")
self._current_task = None
def summary(self, downloaded: int, skipped: int, failed: int) -> None:
"""Print summary line and stop progress."""
if self._progress:
self._progress.stop()
self._console.print(f"\n[bold]Summary:[/bold] {downloaded} downloaded, {skipped} skipped, {failed} failed")
def _fmt_size(bytes_val: int) -> str:
"""Format byte count as human-readable size string."""
if bytes_val <= 0:
return "unknown size"
for unit in ("B", "KB", "MB", "GB"):
if bytes_val < 1024:
return f"{bytes_val:.1f} {unit}" if unit != "B" else f"{bytes_val} {unit}"
bytes_val /= 1024
return f"{bytes_val:.1f} TB"
def DownloadReporter(stdout=None):
"""Factory: returns appropriate reporter based on TTY detection.
Args:
stdout: File-like object to check for TTY and write to.
Defaults to sys.stdout.
Returns:
ProgressReporter if stdout is a TTY, else PlainTextReporter.
"""
if stdout is None:
stdout = sys.stdout
if getattr(stdout, "isatty", lambda: False)():
return ProgressReporter(stdout=stdout)
return PlainTextReporter(stdout=stdout)