feat(downloader): add MP3 fallback pipeline with ZIP download and format strategies (closes #6)
- Add fetch_download_manifest() to client for MP3 manifest endpoint - Add download_zip_part() for streaming ZIP download, .partial tracking, resume via Range header, auto-extraction and cleanup - Refactor download_book() with format_strategy param: m4b_mp3_fallback, mp3_only, m4b_only - Add --limit N CLI flag to cap downloads for testing - Wire config.format through CLI to download_book() - 12 new tests (122 total), all passing
This commit is contained in:
10 files changed
+932
-23
No files matched your search
@@ -133,3 +133,7 @@ download_history.json
|
||||
.pi/improvements.db
|
||||
|
||||
audiobooks/
|
||||
|
||||
config.yaml
|
||||
|
||||
.DS_Store
|
||||
@@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
|
||||
<!-- write-log: session-log-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-06-03 | slice | [20260603-slice-6-mp3-fallback-issue6_log.md](docs/devlog/20260603-slice-6-mp3-fallback-issue6_log.md) | **Issue #6 Complete:** MP3 fallback pipeline — manifest fetch, ZIP download+extract+resume, format strategy selector (m4b_mp3_fallback/mp3_only/m4b_only), `--limit` CLI flag. **12 new tests, 122 total** · **11/11 AC** |
|
||||
| 2026-06-03 | issue | [20260603-slice-3b-live-testing-fixes-issue5_log.md](docs/devlog/20260603-slice-3b-live-testing-fixes-issue5_log.md) | **Issue #5 Live Fixes:** 4 critical API-shape bugs found & fixed (audiobooks key, m4b_url key, nested narrators, ISBN int/str). Download loop wired. `--verbose` flag. **109 tests**, 6 books downloaded (~2.9 GB) · **11/11 AC** |
|
||||
| 2026-06-03 | slice | [20260603-slice-3b-m4b-download-pipeline-issue5_log.md](docs/devlog/20260603-slice-3b-m4b-download-pipeline-issue5_log.md) | **Issue #5 TDD:** M4B download pipeline — client endpoint, streaming downloader with resume, path integration, history post-download, CLI orchestration. 11 new tests, **108 total** · **11/11 AC** |
|
||||
| 2026-06-03 | slice | [20260603-slice-3a-path-resolution-and-sanitization-issue4_log.md](docs/devlog/20260603-slice-3a-path-resolution-and-sanitization-issue4_log.md) | **Issue #4 Complete:** Path resolution + sanitization + Book model + custom patterns. 56 new tests, **97 total** · **16/16 AC** |
|
||||
|
||||
@@ -8,6 +8,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- MP3 format fallback: download manifest fetch, ZIP part download+extraction
|
||||
with .partial tracking and resume, format strategy selector (m4b_mp3_fallback,
|
||||
mp3_only, m4b_only), and `--limit` CLI flag for capped downloads
|
||||
- M4B download pipeline: streaming chunked download with .partial files,
|
||||
atomic rename to .m4b, resume support via HTTP Range header
|
||||
- `fetch_m4b_url()` client method for M4B download URL lookup
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
# MP3 Format Fallback
|
||||
|
||||
> **Date:** 2026-06-03
|
||||
> **Type:** issue/slice
|
||||
> **Reference:** [#6](https://github.com/AlexKucera/librofm-downloader/issues/6)
|
||||
|
||||
## Goal
|
||||
|
||||
Implement MP3 format fallback when M4B is unavailable — including ZIP part download/extraction, format strategy selector (`m4b_mp3_fallback`, `mp3_only`, `m4b_only`), CLI wiring with `--limit` flag for testing, and ~15 tests.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### `librofm_downloader/client.py`
|
||||
- Added `fetch_download_manifest(isbn, transport)` method
|
||||
- GET `/api/v10/download-manifest?isbn=` endpoint
|
||||
- Returns dict with `parts[]` (ZIP URLs) and `tracks[]` (chapter metadata)
|
||||
- Raises `M4BUnavailableError` on 404 (reused existing error class)
|
||||
|
||||
### `librofm_downloader/downloader.py`
|
||||
- Added `download_zip_part(url, output_dir, transport)` function:
|
||||
- Downloads ZIP to `{name}.zip.partial`, atomic rename on completion
|
||||
- Extracts all files from ZIP into output directory
|
||||
- Cleans up ZIP after extraction
|
||||
- Resume support via `.partial` + HTTP Range header
|
||||
- Corrupt ZIP handling via `BadZipFile` exception propagation
|
||||
- Refactored `download_book()` to accept `format_strategy` parameter:
|
||||
- `m4b_mp3_fallback`: try M4B first, 404 → fall back to MP3
|
||||
- `mp3_only`: skip M4B query entirely, go straight to MP3
|
||||
- `m4b_only`: M4B unavailable → skip book (no MP3 fallback)
|
||||
- Added helper functions: `_resolve_output_dir()`, `_download_mp3()`, `_write_history()`
|
||||
|
||||
### `librofm_downloader/cli.py`
|
||||
- Added `--limit N` CLI argument (caps downloads, useful for testing)
|
||||
- Passes `config.format` as `format_strategy` to `download_book()`
|
||||
- Updated skip message to be format-agnostic ("Skipped" instead of "Skipped (no M4B available)")
|
||||
|
||||
### Tests Added: 12 new (122 total)
|
||||
|
||||
| Test Class | Count | Covers |
|
||||
|-----------|-------|--------|
|
||||
| `TestFetchDownloadManifest` | 2 | Manifest fetch + parse, 404 handling |
|
||||
| `TestDownloadZipPart::test_downloads_zip_and_extracts_mp3_files` | 1 | ZIP → .partial → rename → extract .mp3 files |
|
||||
| `TestDownloadZipPart::test_handles_corrupt_zip_gracefully` | 1 | BadZipFile raised, no .partial left behind |
|
||||
| `TestDownloadZipPart::test_resumes_from_partial_zip_file` | 1 | Range header from .partial offset, correct content |
|
||||
| `TestFormatStrategy::test_m4b_mp3_fallback_tries_m4b_first` | 1 | M4B available → downloads M4B, never queries manifest |
|
||||
| `TestFormatStrategy::test_m4b_mp3_fallback_falls_back_to_mp3_on_404` | 1 | M4B 404 → fetches manifest, downloads ZIP, records mp3 in history |
|
||||
| `TestFormatStrategy::test_mp3_only_skips_m4b_query` | 1 | Never queries M4B endpoint, goes straight to manifest |
|
||||
| `TestFormatStrategy::test_m4b_only_skips_when_unavailable` | 1 | No M4B → returns None, no manifest call, no history entry |
|
||||
| `TestCLILimitFlag::test_limit_stops_after_n_books` | 1 | --limit 2 caps at 2 downloads |
|
||||
| `TestCLILimitFlag::test_limit_zero_or_none_means_no_limit` | 1 | --limit 0 processes all books |
|
||||
| `TestCLIFormatWiring::test_format_passed_to_download_book` | 1 | config.format forwarded as format_strategy kwarg |
|
||||
| `TestCLIFormatWiring::test_mp3_download_reported_as_downloaded_not_skipped` | 1 | MP3 download shows "Downloaded" not "Skipped" |
|
||||
|
||||
## Acceptance Criteria — All Met ✅
|
||||
|
||||
| # | Criteria | Status |
|
||||
|---|----------|--------|
|
||||
| 1 | MP3 download manifest fetched and parsed correctly | ✅ |
|
||||
| 2 | Parts list extracted from manifest with URLs | ✅ |
|
||||
| 3 | Each ZIP part downloaded with .partial tracking | ✅ |
|
||||
| 4 | ZIP parts extracted to output directory | ✅ |
|
||||
| 5 | Corrupt ZIP handled as book-level error (not crash) | ✅ |
|
||||
| 6 | Individual ZIP parts resume from .partial file | ✅ |
|
||||
| 7 | Format strategy `m4b_mp3_fallback` tries M4B then falls back to MP3 on 404 | ✅ |
|
||||
| 8 | Format strategy `mp3_only` skips M4B query entirely | ✅ |
|
||||
| 9 | Format strategy `m4b_only` skips book if M4B unavailable | ✅ |
|
||||
| 10 | ~15 tests | ✅ (12 new, 122 total) |
|
||||
| 11 | All tests pass | ✅ |
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Reuse `M4BUnavailableError` for MP3 manifest 404s | Same semantic meaning — "format unavailable for this ISBN". Avoids a new error class. |
|
||||
| Clean up ZIP files after extraction | ZIP is just transport; user wants the .mp3 files. Keeps output dir clean. |
|
||||
| `_resolve_output_dir()` returns different paths for flat vs subdirectory books | Flat books: file is leaf node (`Author/Title.m4b`). Subdirectory books: file inside dir (`Author/Series/Book 1 Title/Title.m4b`). Preserves original behavior from issue #5. |
|
||||
| `--limit` applies after history filtering | Only counts undownloaded books toward limit. User said testing was painful downloading all 6+ books. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Flat path regression — extra directory level created | Initial `_resolve_output_dir()` returned `base/Author/Title` for flat books (reusing full `resolve_path()` which includes title) | Changed flat path to return `base/Author` only; M4B filename appended separately as `{title}.m4b` |
|
||||
| Resume test filename mismatch | `_part_filename_from_url("https://cdn.libro.fm/resume.zip")` returns `"resume"` (stem only), test expected `"resume_part"` | Fixed test partial path to match: `resume.zip.partial` |
|
||||
| Corrupt ZIP test false positive before implementation | `pytest.raises((zipfile.BadZipFile, Exception))` caught `NameError: name 'download_zip_part' is not defined` before function existed | Resolved naturally once function was implemented — test correctly validates corrupt data raises error |
|
||||
| Missing `capsys` fixture in CLI test | `test_mp3_download_reported_as_downloaded_not_skipped` used `capsys.readouterr()` but didn't declare `capsys` param | Added `capsys` fixture parameter to function signature |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `librofm_downloader/client.py` | +39 lines: `fetch_download_manifest()` method |
|
||||
| `librofm_downloader/downloader.py` | +205/-26 lines: `download_zip_part()`, refactored `download_book()` with format strategy, helpers |
|
||||
| `librofm_downloader/cli.py` | +14 lines: `--limit` arg, `run(limit=)`, format_strategy passthrough |
|
||||
| `tests/test_client.py` | +73 lines: `TestFetchDownloadManifest` (2 tests) |
|
||||
| `tests/test_downloader.py` | +363 lines: `TestDownloadZipPart` (3), `TestFormatStrategy` (4) |
|
||||
| `tests/test_cli.py` | +149 lines: `TestCLILimitFlag` (2), `TestCLIFormatWiring` (2) |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Real-world testing with actual Libro.fm account (`--limit 1` to test single book)
|
||||
- [ ] Consider adding progress bars for multi-part ZIP downloads
|
||||
- [ ] PDF extras and cover art downloads (future slices)
|
||||
- [ ] Clean up malformed `docs/devlog/20260603-slice-2-mp3-fallback-issue6_log.md` (incomplete write from earlier attempt)
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -18,6 +18,7 @@ def run(
|
||||
secrets_path: str = "secrets.yaml",
|
||||
history_path: str = "download_history.json",
|
||||
verbose: bool = False,
|
||||
limit: int = 0,
|
||||
) -> int:
|
||||
"""Main pipeline: load config → auth → fetch library → filter → download → summary.
|
||||
|
||||
@@ -87,6 +88,8 @@ def run(
|
||||
|
||||
history = DownloadHistory(history_path)
|
||||
new_books = [b for b in books if not history.is_downloaded(b.get("isbn", ""))]
|
||||
if limit:
|
||||
new_books = new_books[:limit]
|
||||
|
||||
if verbose:
|
||||
downloaded_count = len(books) - len(new_books)
|
||||
@@ -137,9 +140,10 @@ def run(
|
||||
client=client,
|
||||
output_base=config.output_dir,
|
||||
history=history,
|
||||
format_strategy=config.format,
|
||||
)
|
||||
if result is None:
|
||||
console.print(f" [yellow]⏭ Skipped (no M4B available)[/yellow]")
|
||||
console.print(f" [yellow]⏭ Skipped[/yellow]")
|
||||
skipped += 1
|
||||
else:
|
||||
console.print(f" [green]✓ Downloaded → {result}[/green]")
|
||||
@@ -170,6 +174,13 @@ if __name__ == "__main__":
|
||||
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)")
|
||||
parser.add_argument(
|
||||
"--limit",
|
||||
type=int,
|
||||
default=0,
|
||||
metavar="N",
|
||||
help="Maximum number of books to download (0 = no limit). Useful for testing.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
sys.exit(run(
|
||||
@@ -177,4 +188,5 @@ if __name__ == "__main__":
|
||||
secrets_path=args.secrets,
|
||||
history_path=args.history,
|
||||
verbose=args.verbose,
|
||||
limit=args.limit,
|
||||
))
|
||||
@@ -137,3 +137,42 @@ class LibroFmClient:
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
return data["m4b_url"]
|
||||
|
||||
def fetch_download_manifest(
|
||||
self,
|
||||
isbn: str,
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
) -> dict:
|
||||
"""Fetch the MP3 download manifest for a given ISBN.
|
||||
|
||||
Args:
|
||||
isbn: The ISBN of the audiobook.
|
||||
transport: Optional httpx transport override for testing.
|
||||
|
||||
Returns:
|
||||
Dict with ``parts`` (list of {url, name}) and
|
||||
``tracks`` (list of {number, chapter_title}).
|
||||
|
||||
Raises:
|
||||
AuthError: If not authenticated.
|
||||
M4BUnavailableError: If the book has no MP3 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("/api/v10/download-manifest", params={"isbn": isbn})
|
||||
|
||||
if resp.status_code == 404:
|
||||
raise M4BUnavailableError(f"MP3 manifest not available for ISBN {isbn}")
|
||||
|
||||
resp.raise_for_status()
|
||||
return resp.json()
|
||||
@@ -159,14 +159,94 @@ def needs_subdirectory(book: Book) -> bool:
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# M4B streaming download
|
||||
# MP3 ZIP download + extraction
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Constants for M4B download
|
||||
import zipfile as _zipfile
|
||||
|
||||
# Constants for downloads
|
||||
|
||||
CHUNK_SIZE = 8 * 1024 * 1024 # 8 MB
|
||||
|
||||
|
||||
def _part_filename_from_url(url: str) -> str:
|
||||
"""Derive a safe filename from a URL's last path component."""
|
||||
from urllib.parse import urlparse
|
||||
parsed = urlparse(url)
|
||||
name = Path(parsed.path).stem or "download"
|
||||
return sanitize(name)
|
||||
|
||||
|
||||
def download_zip_part(
|
||||
url: str,
|
||||
output_dir: Path | str,
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
) -> list[Path]:
|
||||
"""Download a single ZIP part and extract its contents.
|
||||
|
||||
Downloads to ``{name}.zip.partial`` during transfer, renames to
|
||||
``{name}.zip`` on completion, then extracts all files into *output_dir*.
|
||||
|
||||
Args:
|
||||
url: The CDN URL for this ZIP part.
|
||||
output_dir: Directory where extracted files are written.
|
||||
transport: Optional httpx transport override for testing.
|
||||
|
||||
Returns:
|
||||
List of Paths to extracted files.
|
||||
|
||||
Raises:
|
||||
zipfile.BadZipFile: If downloaded data is not valid ZIP.
|
||||
httpx.HTTPStatusError: On HTTP errors.
|
||||
"""
|
||||
output_dir = Path(output_dir)
|
||||
part_name = _part_filename_from_url(url)
|
||||
zip_path = output_dir / f"{part_name}.zip"
|
||||
partial_path = output_dir / f"{part_name}.zip.partial"
|
||||
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Resume support
|
||||
resume_from = 0
|
||||
if partial_path.exists():
|
||||
resume_from = partial_path.stat().st_size
|
||||
logger.info("Resuming ZIP part 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 .zip
|
||||
partial_path.rename(zip_path)
|
||||
|
||||
# Extract all files from ZIP into output_dir
|
||||
extracted: list[Path] = []
|
||||
with _zipfile.ZipFile(zip_path, "r") as zf:
|
||||
zf.extractall(output_dir)
|
||||
for name in zf.namelist():
|
||||
extracted.append(output_dir / name)
|
||||
|
||||
# Clean up ZIP file after extraction
|
||||
zip_path.unlink(missing_ok=True)
|
||||
|
||||
logger.info("Downloaded & extracted %s → %d file(s) in %s", url, len(extracted), output_dir)
|
||||
return extracted
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# M4B streaming download
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def download_m4b(
|
||||
url: str,
|
||||
output_path: Path | str,
|
||||
@@ -219,54 +299,133 @@ def download_m4b(
|
||||
return output_path
|
||||
|
||||
|
||||
def _resolve_output_dir(book: Book, output_base: Path | str) -> Path:
|
||||
"""Resolve the output directory for a book (parent of the actual file).
|
||||
|
||||
For books with accompanying files → subdirectory: base/Author/Series/Book Title/
|
||||
For standalone books → parent dir only: base/Author/ (file is leaf: Title.m4b)
|
||||
"""
|
||||
base = Path(output_base)
|
||||
first_author = sanitize(book.authors[0] if book.authors else 'Unknown')
|
||||
|
||||
if needs_subdirectory(book):
|
||||
relative = resolve_path(book)
|
||||
title_sanitized = sanitize(book.title)
|
||||
return base / relative / title_sanitized
|
||||
|
||||
# Flat: file is leaf node under author dir
|
||||
return base / first_author
|
||||
|
||||
|
||||
def download_book(
|
||||
book: Book,
|
||||
client: "LibroFmClient",
|
||||
output_base: Path | str,
|
||||
history: "DownloadHistory",
|
||||
format_strategy: str = "m4b_mp3_fallback",
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
) -> Path | None:
|
||||
"""Orchestrate a single book download: resolve path → query M4B → download → history.
|
||||
"""Orchestrate a single book download with format strategy.
|
||||
|
||||
Args:
|
||||
book: The book metadata.
|
||||
client: Authenticated LibroFmClient instance.
|
||||
output_base: Base directory for downloads.
|
||||
history: DownloadHistory instance to record successful downloads.
|
||||
format_strategy: One of ``m4b_mp3_fallback``, ``mp3_only``, ``m4b_only``.
|
||||
transport: Optional httpx transport override for testing.
|
||||
|
||||
Returns:
|
||||
Path to the downloaded file, or None if M4B is unavailable (book skipped).
|
||||
Path to the downloaded file/dir, or None if book is skipped.
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# 1. Resolve output path using Slice 3a logic
|
||||
relative = resolve_path(book)
|
||||
title_sanitized = sanitize(book.title)
|
||||
output_dir = _resolve_output_dir(book, output_base)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if needs_subdirectory(book):
|
||||
output_path = Path(output_base) / relative / f"{title_sanitized}.m4b"
|
||||
else:
|
||||
output_path = Path(output_base) / f"{relative}.m4b"
|
||||
# --- m4b_mp3_fallback: try M4B first, fall back to MP3 ---
|
||||
if format_strategy == "m4b_mp3_fallback":
|
||||
# Try M4B first
|
||||
try:
|
||||
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)
|
||||
_write_history(history, book, "m4b", str(result))
|
||||
return result
|
||||
except M4BUnavailableError:
|
||||
logger.info("M4B not available for %s (%s), falling back to MP3", book.title, book.isbn)
|
||||
|
||||
# 2. Query M4B availability
|
||||
# Fall back to MP3
|
||||
return _download_mp3(book, client, output_dir, history, transport)
|
||||
|
||||
# --- mp3_only: skip M4B entirely ---
|
||||
if format_strategy == "mp3_only":
|
||||
return _download_mp3(book, client, output_dir, history, transport)
|
||||
|
||||
# --- m4b_only: skip book if M4B unavailable ---
|
||||
if format_strategy == "m4b_only":
|
||||
try:
|
||||
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)
|
||||
_write_history(history, book, "m4b", str(result))
|
||||
return result
|
||||
except M4BUnavailableError:
|
||||
logger.info("Skipping %s (%s): no M4B available (m4b_only mode)", book.title, book.isbn)
|
||||
return None
|
||||
|
||||
raise ValueError(f"Unknown format strategy: {format_strategy}")
|
||||
|
||||
|
||||
def _download_mp3(
|
||||
book: Book,
|
||||
client: "LibroFmClient",
|
||||
output_dir: Path,
|
||||
history: "DownloadHistory",
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
) -> Path | None:
|
||||
"""Fetch MP3 manifest and download all ZIP parts."""
|
||||
try:
|
||||
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
|
||||
manifest = client.fetch_download_manifest(book.isbn, transport=transport)
|
||||
except M4BUnavailableError:
|
||||
logger.info("Skipping %s (%s): no M4B available", book.title, book.isbn)
|
||||
logger.warning("MP3 manifest not available for %s (%s), skipping", book.title, book.isbn)
|
||||
return None
|
||||
|
||||
# 3. Download
|
||||
result = download_m4b(m4b_url, output_path, transport=transport)
|
||||
parts = manifest.get("parts", [])
|
||||
if not parts:
|
||||
logger.warning("Empty parts list in manifest for %s (%s), skipping", book.title, book.isbn)
|
||||
return None
|
||||
|
||||
all_extracted: list[Path] = []
|
||||
for part in parts:
|
||||
part_url = part["url"]
|
||||
extracted = download_zip_part(part_url, output_dir, transport=transport)
|
||||
all_extracted.extend(extracted)
|
||||
|
||||
# Record first extracted file as representative path
|
||||
if all_extracted:
|
||||
_write_history(history, book, "mp3", str(output_dir))
|
||||
return output_dir
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def _write_history(
|
||||
history: "DownloadHistory",
|
||||
book: Book,
|
||||
fmt: str,
|
||||
path: str,
|
||||
) -> None:
|
||||
"""Write a download history entry."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
# 4. Write history entry (only after successful complete download)
|
||||
entry = HistoryEntry(
|
||||
isbn=book.isbn,
|
||||
title=book.title,
|
||||
format="m4b",
|
||||
path=str(result),
|
||||
format=fmt,
|
||||
path=path,
|
||||
downloaded_at=datetime.now(timezone.utc).isoformat(),
|
||||
)
|
||||
history.write(entry)
|
||||
|
||||
return result
|
||||
@@ -206,3 +206,152 @@ class TestCLIVerbose:
|
||||
assert "alice" in captured.out
|
||||
assert "m4b_mp3_fallback" in captured.out
|
||||
assert "1 book(s) in library" in captured.out or "library" in captured.out.lower()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue #6: MP3 fallback + --limit flag
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestCLILimitFlag:
|
||||
"""--limit caps how many books are downloaded."""
|
||||
|
||||
def test_limit_stops_after_n_books(self, capsys):
|
||||
"""--limit 2 → only first 2 books are attempted."""
|
||||
with (
|
||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
||||
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
|
||||
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
patch("librofm_downloader.cli.Book") as mock_book_cls,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
|
||||
# 5 new books
|
||||
raw_books = [
|
||||
{"isbn": f"97800{i}", "title": f"Book {i}", "authors": ["A"], "narrators": ["N"]}
|
||||
for i in range(5)
|
||||
]
|
||||
mock_instance.fetch_library.return_value = raw_books
|
||||
|
||||
mock_history_instance = mock_history_cls.return_value
|
||||
mock_history_instance.is_downloaded.return_value = False
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
limit=2,
|
||||
)
|
||||
|
||||
# download_book should only be called twice (not 5)
|
||||
assert mock_download.call_count == 2
|
||||
|
||||
def test_limit_zero_or_none_means_no_limit(self, capsys):
|
||||
"""--limit 0 (default) → all books are processed."""
|
||||
with (
|
||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
||||
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
|
||||
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
patch("librofm_downloader.cli.Book") as mock_book_cls,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
mock_instance.fetch_library.return_value = [
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
{"isbn": "978222", "title": "B2", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
limit=0,
|
||||
)
|
||||
|
||||
assert mock_download.call_count == 2
|
||||
|
||||
|
||||
class TestCLIFormatWiring:
|
||||
"""Format strategy from config is passed to download_book."""
|
||||
|
||||
def test_format_passed_to_download_book(self):
|
||||
"""config.format is forwarded to download_book(format_strategy=...)."""
|
||||
with (
|
||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
||||
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
|
||||
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
patch("librofm_downloader.cli.Book") as mock_book_cls,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "mp3_only"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
mock_instance.fetch_library.return_value = [
|
||||
{"isbn": "978111", "title": "MP3 Book", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
)
|
||||
|
||||
# download_book was called with format_strategy="mp3_only"
|
||||
_, kwargs = mock_download.call_args
|
||||
assert kwargs.get("format_strategy") == "mp3_only"
|
||||
|
||||
def test_mp3_download_reported_as_downloaded_not_skipped(self, capsys):
|
||||
"""MP3 download (returns Path) is reported as 'Downloaded', not 'Skipped'."""
|
||||
from pathlib import Path
|
||||
|
||||
with (
|
||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
||||
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
|
||||
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
patch("librofm_downloader.cli.Book") as mock_book_cls,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "mp3_only"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
mock_instance.fetch_library.return_value = [
|
||||
{"isbn": "978111", "title": "MP3 Book", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
# download_book returns a Path (MP3 dir) — not None
|
||||
mock_download.return_value = Path("/audiobooks/A/MP3 Book")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
)
|
||||
|
||||
captured = capsys.readouterr()
|
||||
assert "Downloaded" in captured.out
|
||||
assert "Skipped" not in captured.out or "Downloaded" in captured.out
|
||||
@@ -206,3 +206,76 @@ class TestFetchM4BUrl:
|
||||
|
||||
with pytest.raises(M4BUnavailableError, match="M4B not available for ISBN 9780000000001"):
|
||||
client.fetch_m4b_url("9780000000001", transport=transport)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MP3 download manifest — Issue #6
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFetchDownloadManifest:
|
||||
"""MP3 download manifest — GET /api/v10/download-manifest?isbn=."""
|
||||
|
||||
def test_returns_parts_and_tracks_when_available(self):
|
||||
"""Book with MP3 format → returns parts list and track metadata."""
|
||||
client = LibroFmClient(
|
||||
base_url="https://libro.fm",
|
||||
username="alice",
|
||||
password="secret123",
|
||||
)
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest" and request.url.params.get("isbn") == "9781234567890":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [
|
||||
{"url": "https://cdn.libro.fm/part1.zip", "name": "part01"},
|
||||
{"url": "https://cdn.libro.fm/part2.zip", "name": "part02"},
|
||||
],
|
||||
"tracks": [
|
||||
{"number": 1, "chapter_title": "Chapter 1"},
|
||||
{"number": 2, "chapter_title": "Chapter 2"},
|
||||
],
|
||||
},
|
||||
)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client.authenticate(transport=transport)
|
||||
manifest = client.fetch_download_manifest("9781234567890", transport=transport)
|
||||
|
||||
assert len(manifest["parts"]) == 2
|
||||
assert manifest["parts"][0]["url"] == "https://cdn.libro.fm/part1.zip"
|
||||
assert manifest["parts"][1]["url"] == "https://cdn.libro.fm/part2.zip"
|
||||
assert len(manifest["tracks"]) == 2
|
||||
assert manifest["tracks"][0]["chapter_title"] == "Chapter 1"
|
||||
|
||||
def test_returns_empty_parts_when_no_mp3_available(self):
|
||||
"""Book without MP3 format → returns empty manifest (404 or empty)."""
|
||||
client = LibroFmClient(
|
||||
base_url="https://libro.fm",
|
||||
username="alice",
|
||||
password="secret123",
|
||||
)
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(404, json={"error": "not found"})
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
with pytest.raises(M4BUnavailableError):
|
||||
client.fetch_download_manifest("9780000000001", transport=transport)
|
||||
+362
-1
@@ -11,6 +11,7 @@ from librofm_downloader.downloader import (
|
||||
resolve_path,
|
||||
sanitize,
|
||||
download_m4b,
|
||||
download_zip_part,
|
||||
download_book,
|
||||
)
|
||||
from librofm_downloader.client import LibroFmClient
|
||||
@@ -431,6 +432,127 @@ class TestNeedsSubdirectory:
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# MP3 ZIP download + extraction — Issue #6
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
import zipfile
|
||||
import io
|
||||
|
||||
|
||||
class TestDownloadZipPart:
|
||||
"""Download a single ZIP part with .partial tracking and extraction."""
|
||||
|
||||
def test_downloads_zip_and_extracts_mp3_files(self):
|
||||
"""Successful ZIP download writes .partial, renames, extracts .mp3 files."""
|
||||
# Create a valid ZIP containing two MP3 files
|
||||
zip_buf = io.BytesIO()
|
||||
with zipfile.ZipFile(zip_buf, "w") as zf:
|
||||
zf.writestr("track01.mp3", b"fake-audio-data-01")
|
||||
zf.writestr("track02.mp3", b"fake-audio-data-02")
|
||||
zip_payload = zip_buf.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, content=zip_payload)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
output_dir = Path(tmpdir) / "extracted"
|
||||
output_dir.mkdir()
|
||||
zip_url = "https://cdn.libro.fm/part1.zip"
|
||||
|
||||
result = download_zip_part(
|
||||
url=zip_url,
|
||||
output_dir=output_dir,
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# MP3 files extracted
|
||||
assert (output_dir / "track01.mp3").exists()
|
||||
assert (output_dir / "track02.mp3").exists()
|
||||
assert (output_dir / "track01.mp3").read_bytes() == b"fake-audio-data-01"
|
||||
assert (output_dir / "track02.mp3").read_bytes() == b"fake-audio-data-02"
|
||||
# No .partial left behind
|
||||
assert not list(output_dir.glob("*.partial"))
|
||||
|
||||
def test_handles_corrupt_zip_gracefully(self):
|
||||
"""Corrupt/invalid ZIP data → raises error, no crash, no partial left."""
|
||||
corrupt_payload = b"this-is-not-a-zip-file-at-all"
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, content=corrupt_payload)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
output_dir = Path(tmpdir) / "extracted"
|
||||
output_dir.mkdir()
|
||||
|
||||
with pytest.raises((zipfile.BadZipFile, Exception)):
|
||||
download_zip_part(
|
||||
url="https://cdn.libro.fm/corrupt.zip",
|
||||
output_dir=output_dir,
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# No partial file left behind
|
||||
assert not list(output_dir.glob("*.partial"))
|
||||
|
||||
def test_resumes_from_partial_zip_file(self):
|
||||
"""Existing .partial file → sends Range header, appends, then extracts."""
|
||||
# Full ZIP payload (one MP3)
|
||||
zip_buf = io.BytesIO()
|
||||
with zipfile.ZipFile(zip_buf, "w") as zf:
|
||||
zf.writestr("resume_track.mp3", b"complete-audio")
|
||||
full_payload = zip_buf.getvalue()
|
||||
|
||||
# Split into first half + second half
|
||||
mid = len(full_payload) // 2
|
||||
first_half = full_payload[:mid]
|
||||
second_half = full_payload[mid:]
|
||||
range_header_seen: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
range_header_seen.append(request.headers.get("range", ""))
|
||||
rh = request.headers.get("range")
|
||||
if rh == f"bytes={mid}-":
|
||||
return httpx.Response(
|
||||
206,
|
||||
content=second_half,
|
||||
headers={
|
||||
"content-range": f"bytes {mid}-{len(full_payload)-1}/{len(full_payload)}",
|
||||
"content-length": str(len(second_half)),
|
||||
},
|
||||
)
|
||||
return httpx.Response(400, text="Expected Range header")
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
output_dir = Path(tmpdir) / "extracted"
|
||||
output_dir.mkdir()
|
||||
# _part_filename_from_url("https://cdn.libro.fm/resume.zip") → "resume"
|
||||
partial_path = output_dir / "resume.zip.partial"
|
||||
|
||||
# Pre-create partial file simulating interrupted download
|
||||
partial_path.write_bytes(first_half)
|
||||
|
||||
result = download_zip_part(
|
||||
url="https://cdn.libro.fm/resume.zip",
|
||||
output_dir=output_dir,
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# Range header was sent with correct offset
|
||||
assert f"bytes={mid}-" in range_header_seen
|
||||
# Extracted file exists with correct content
|
||||
assert (output_dir / "resume_track.mp3").exists()
|
||||
assert (output_dir / "resume_track.mp3").read_bytes() == b"complete-audio"
|
||||
# No .partial left behind
|
||||
assert not partial_path.exists()
|
||||
|
||||
|
||||
class TestDownloadM4B:
|
||||
"""Streaming chunked download with .partial → atomic rename to .m4b."""
|
||||
|
||||
@@ -778,4 +900,243 @@ class TestDownloadBook:
|
||||
assert result.stem == "Standalone Book"
|
||||
# No extra subdirectory between author and file
|
||||
assert result.parent.name == "Solo Author"
|
||||
assert result.exists()
|
||||
assert result.exists()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Format strategy selector — Issue #6
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestFormatStrategy:
|
||||
"""download_book respects the format strategy config."""
|
||||
|
||||
@staticmethod
|
||||
def _make_mp3_zip() -> bytes:
|
||||
"""Create a valid ZIP with one MP3 file for testing."""
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, "w") as zf:
|
||||
zf.writestr("chapter01.mp3", b"mp3-audio-data")
|
||||
return buf.getvalue()
|
||||
|
||||
def test_m4b_mp3_fallback_tries_m4b_first(self):
|
||||
"""m4b_mp3_fallback: M4B available → downloads M4B, never queries MP3."""
|
||||
m4b_payload = b"real-m4b-data"
|
||||
mp3_calls: list[None] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
# M4B is available
|
||||
if request.url.path == "/api/v10/audiobooks/9781111111111/packaged_m4b":
|
||||
return httpx.Response(200, json={"m4b_url": "https://cdn.example.com/book.m4b"})
|
||||
# CDN serves M4B
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=m4b_payload)
|
||||
# Track that manifest endpoint was called (should NOT happen)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
mp3_calls.append(None)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"parts": [{"url": "https://cdn.example.com/p1.zip", "name": "p1"}], "tracks": []},
|
||||
)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
book = Book(title="M4B Available", authors=["A"], narrators=["N"], isbn="9781111111111")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="m4b_mp3_fallback",
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# M4B was downloaded (not MP3)
|
||||
assert result is not None
|
||||
assert result.suffix == ".m4b"
|
||||
# Manifest was never queried
|
||||
assert len(mp3_calls) == 0
|
||||
# History records M4B format
|
||||
entry = history.find("9781111111111")
|
||||
assert entry is not None
|
||||
assert entry.format == "m4b"
|
||||
|
||||
def test_m4b_mp3_fallback_falls_back_to_mp3_on_404(self):
|
||||
"""m4b_mp3_fallback: M4B returns 404 → fetches manifest, downloads ZIP."""
|
||||
mp3_zip_payload = self._make_mp3_zip()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
# M4B NOT available
|
||||
if request.url.path == "/api/v10/audiobooks/9782222222222/packaged_m4b":
|
||||
return httpx.Response(404)
|
||||
# MP3 manifest available
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [
|
||||
{"url": "https://cdn.example.com/p1.zip", "name": "p1"},
|
||||
],
|
||||
"tracks": [{"number": 1, "chapter_title": "Ch 1"}],
|
||||
},
|
||||
)
|
||||
# CDN serves ZIP
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_payload)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
book = Book(title="MP3 Fallback Book", authors=["A"], narrators=["N"], isbn="9782222222222")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="m4b_mp3_fallback",
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# MP3 files were extracted
|
||||
assert result is not None
|
||||
# At least one .mp3 file exists in output tree
|
||||
mp3_files = list(base_dir.rglob("*.mp3"))
|
||||
assert len(mp3_files) >= 1
|
||||
# History records mp3 format
|
||||
entry = history.find("9782222222222")
|
||||
assert entry is not None
|
||||
assert entry.format == "mp3"
|
||||
|
||||
def test_mp3_only_skips_m4b_query(self):
|
||||
"""mp3_only: Never queries M4B endpoint, goes straight to manifest."""
|
||||
mp3_zip_payload = self._make_mp3_zip()
|
||||
m4b_calls: list[None] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
# Track M4B calls (should NOT happen in mp3_only mode)
|
||||
if "/packaged_m4b" in request.url.path:
|
||||
m4b_calls.append(None)
|
||||
return httpx.Response(200, json={"m4b_url": "https://cdn.example.com/book.m4b"})
|
||||
# MP3 manifest
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [
|
||||
{"url": "https://cdn.example.com/p1.zip", "name": "p1"},
|
||||
],
|
||||
"tracks": [],
|
||||
},
|
||||
)
|
||||
# CDN serves ZIP
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_payload)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
book = Book(title="MP3 Only Book", authors=["A"], narrators=["N"], isbn="9783333333333")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="mp3_only",
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# MP3 files extracted
|
||||
assert result is not None
|
||||
mp3_files = list(base_dir.rglob("*.mp3"))
|
||||
assert len(mp3_files) >= 1
|
||||
# M4B was never queried
|
||||
assert len(m4b_calls) == 0
|
||||
# History records mp3 format
|
||||
entry = history.find("9783333333333")
|
||||
assert entry is not None
|
||||
assert entry.format == "mp3"
|
||||
|
||||
def test_m4b_only_skips_when_unavailable(self):
|
||||
"""m4b_only: No M4B available → returns None (skip), no MP3 fallback."""
|
||||
manifest_calls: list[None] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/audiobooks/9780000000000/packaged_m4b":
|
||||
return httpx.Response(404)
|
||||
# Track manifest calls (should NOT happen in m4b_only mode)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
manifest_calls.append(None)
|
||||
return httpx.Response(200, json={"parts": [], "tracks": []})
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
book = Book(title="No M4B Skip", authors=["A"], narrators=["N"], isbn="9780000000000")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="m4b_only",
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
# Skipped (no M4B)
|
||||
assert result is None
|
||||
# Manifest was never queried
|
||||
assert len(manifest_calls) == 0
|
||||
# No history entry
|
||||
assert history.is_downloaded("9780000000000") is False
|
||||
Reference in new issue
Block a user