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:
AlexKucera committed 2026-06-03 13:22:45 +02:00
1 parent 8d6cf021c7
commit 455d3dd172
10 files changed
+932 -23

No files matched your search

+149
View File
@@ -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
+73
View File
@@ -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
View File
@@ -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