feat(downloader): wire rename_chapters into download pipeline
_download_mp3() returns (output_dir, tracks) tuple so manifest track data flows to callers. download_book() accepts rename_chapters kwarg; after MP3 extraction succeeds, calls rename_chapters() via _rename_and_log() helper which also reports to user via reporter. Both PlainTextReporter and RichProgressReporter show visible feedback: 'Renamed N chapter(s) for Book → example.mp3'. sync_run.py closure threads resolved_rename_chapters flag through to download_book(). 6 new integration tests covering all format strategies and edge cases. ~229 total tests. Closes #34.
This commit is contained in:
7 files changed
+489
-16
No files matched your search
@@ -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-05 | issue | [20260605-issue34-wire-rename-chapters-into-download-pipeline_log.md](docs/devlog/20260605-issue34-wire-rename-chapters-into-download-pipeline_log.md) | **Issue #34 Complete (Slice 3):** Wired `rename_chapters()` into download pipeline. `_download_mp3()` returns tuple with tracks, `download_book()` accepts `rename_chapters` kwarg, `_rename_and_log()` helper + user-visible reporter feedback. **6 new tests, ~229 total** · **All pass** · **8/8 AC** |
|
||||
| 2026-06-05 | issue | [20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md](docs/devlog/20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md) | **Issue #33 Complete (Slice 2):** `rename_chapters` config field + `--rename-chapters` CLI flag. 2-layer resolution (CLI > config), defaults True. **5 new tests, 223 total** · **All pass** · **6/7 AC** (env var skipped per user choice) |
|
||||
| 2026-06-05 | issue | [20260605-issue32-rename-chapters-function-and-unit-tests_log.md](docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md) | **Issue #32 Complete:** `rename_chapters()` function in `downloader.py`. Natural sort, zero-padding, null-title fallback, sanitization via existing `sanitize()`. **11 new tests, 106 in downloader** · **All pass** · **12/12 AC** |
|
||||
| 2026-06-05 | issue | [20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md](docs/devlog/20260605-issue31-sync-run-pipeline-and-cli-slimming_log.md) | **Issue #31 Complete:** Extracted `sync_run()` pipeline from `cli.run()` into standalone module. `SyncRunResult` frozen dataclass. `cli.py` slimmed 252→65 lines. **43 sync_run tests + 10 CLI tests, 374 total** · **All pass** · **7/8 AC (HITL pending)** |
|
||||
|
||||
+9
-1
@@ -5,7 +5,7 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
8:6af|## [Unreleased]
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
|
||||
@@ -19,6 +19,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
and `sync_run()` resolution (CLI True → config value). 5 new tests, 223 total.
|
||||
Closes #33.
|
||||
|
||||
- **downloader:** Wire `rename_chapters()` into download pipeline.
|
||||
`_download_mp3()` returns `(output_dir, tracks)` tuple; `download_book()`
|
||||
accepts `rename_chapters` kwarg; new `_rename_and_log()` helper calls rename
|
||||
and reports via `reporter.chapter_renamed()`. Both reporters show visible
|
||||
feedback: "Renamed N chapter(s) for 'Book' → 'example.mp3'".
|
||||
`sync_run.py` closure threads resolved flag through to `download_book()`.
|
||||
6 new integration tests, ~229 total. Closes #34.
|
||||
|
||||
### Refactored
|
||||
|
||||
- **session:** Rename LibroFmClient → LibroFmSession, relocate to
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
# Wire rename_chapters() into Download Pipeline
|
||||
|
||||
> **Date:** 2026-06-05
|
||||
> **Type:** issue
|
||||
> **Reference:** [Issue #34](https://github.com/AlexKucera/librofm-downloader/issues/34)
|
||||
|
||||
## Goal
|
||||
|
||||
Wire the `rename_chapters()` function (built in Issue #32) into the download pipeline so it runs automatically after MP3 extraction when `config.rename_chapters` is enabled (Issue #33). End-to-end: MP3 downloads → chapters renamed to `{num} - {book} - {chapter}.mp3` with visible user feedback.
|
||||
|
||||
## What Was Done
|
||||
|
||||
- **`_download_mp3()` return type changed** from `Path | None` to `tuple[Path | None, list[dict]]` — now returns `(output_dir, tracks)` on success, `(None, [])` on failure. The `manifest["tracks"]` data was already fetched but previously discarded.
|
||||
- **`download_book()` gained `rename_chapters: bool = False` kwarg** — optional, keyword-only, defaults to `False` for backward compatibility.
|
||||
- **New `_rename_and_log()` helper** in `downloader.py` — calls `rename_chapters()`, checks count mismatch before renaming, logs via `logger.info/warning`, and calls `reporter.chapter_renamed()` with an example filename for user-visible output.
|
||||
- **Both MP3 success paths wired** — `m4b_mp3_fallback` fallback path (line ~282) and `mp3_only` path (line ~293) both unpack the tuple and call `_rename_and_log(result_path, mp3_tracks, book.title, reporter)`.
|
||||
- **`sync_run.py` closure updated** — `_make_download_fn()` now captures `resolved_rename_chapters` as `_rc` and passes it to `download_book(..., rename_chapters=_rc)`. This completes the wiring chain: CLI flag → `sync_run()` resolution → closure → `download_book()` → `_rename_and_log()` → `rename_chapters()`.
|
||||
- **User-visible rename feedback added** — new `chapter_renamed(count, book_title, example_name)` method on both `PlainTextReporter` and `ProgressReporter` in `progress.py`. Shows output like: `Renamed 14 chapter(s) for 'The River Has Roots' → '01 - The River Has Roots - Chapter 1.mp3'`
|
||||
- **6 TDD integration tests** added in `TestRenameChaptersWiring` class covering all acceptance criteria.
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Return tracks tuple from `_download_mp3()` rather than re-fetching manifest | Avoids a second API call; manifest is already in memory. Tuple is simple, no new dataclass needed for internal use |
|
||||
| Call rename in `download_book()` not inside `_download_mp3()` | Separation of concerns: `_download_mp3` downloads, `download_book` orchestrates (including post-processing like renaming). Keeps `_download_mp3` testable in isolation |
|
||||
| Add `reporter` param to `_rename_and_log()` instead of importing console/rich | Keeps downloader module decoupled from output mechanism; reporter is injected by caller, testable with mock reporters |
|
||||
| Check count mismatch BEFORE calling `rename_chapters()` | After `zip()` truncation, a 3-file/2-track scenario renames 2 files and returns 2 — looks like success. Pre-check catches the mismatch regardless |
|
||||
| Default `rename_chapters=False` on `download_book()` | Backward compatible; existing callers don't need changes. Only the sync_run closure passes the resolved value |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Test expected `01 - ...` zero-padding but got `1 - ...` | Zero-padding width = `len(str(track_count))`. With 2 tracks, width=1 (single digit). Test assumed 2-digit padding | Fixed test expectations to match actual zero-padding logic |
|
||||
| Count mismatch warning never fired for 3 MP3s + 2 tracks | Original code only warned when `rename_chapters()` returned 0 AND tracks existed. But `zip(3_files, 2_tracks)` renames 2 files → returns 2 → info log fires, no warning | Moved mismatch check BEFORE calling `rename_chapters()`, comparing `len(mp3_files) != len(tracks)` directly |
|
||||
| User couldn't tell if renaming ran — files looked same as unzipped | `_rename_and_log()` only called `logger.info()` which goes to logging ether, not terminal. No user-facing output at all | Added `chapter_renamed()` method to both reporter classes; `_rename_and_log()` calls it with first renamed filename as example |
|
||||
| Libro.fm manifest returned null/empty `chapter_title` values | API data quality issue — some books have no chapter title metadata | `rename_chapters()` falls back to `"Chapter {num}"` pattern (built in Issue #32). Not a bug, just data-dependent behavior |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `librofm_downloader/downloader.py` | `_download_mp3()` returns tuple; `download_book()` accepts `rename_chapters` kwarg; new `_rename_and_log()` helper with reporter feedback; both MP3 paths wired |
|
||||
| `librofm_downloader/sync_run.py` | Closure captures `resolved_rename_chapters`, passes to `download_book(rename_chapters=_rc)` |
|
||||
| `librofm_downloader/progress.py` | `chapter_renamed(count, title, example)` on PlainTextReporter + ProgressReporter |
|
||||
| `tests/test_downloader.py` | 6 new tests in `TestRenameChaptersWiring` class (mp3_only rename, m4b-only skip, fallback rename, false-skip, count-mismatch warning, verbose logging) |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Consider adding per-file rename logging in verbose mode (`-v`) — currently only shows summary line with one example filename
|
||||
- [ ] Libro.fm chapter title quality varies widely; some books get generic "Chapter N" names. Future enhancement could scrape chapter titles from alternate sources (Audible API, etc.)
|
||||
- [ ] ID3 tag writing not in scope (issue mentions this explicitly as out of scope)
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -239,6 +239,7 @@ def download_book(
|
||||
reporter: "DownloadReporter",
|
||||
*,
|
||||
progress: "Callable[[int], None] | None" = None,
|
||||
rename_chapters: bool = False,
|
||||
) -> DownloadResult:
|
||||
"""Orchestrate a single book download with format strategy.
|
||||
|
||||
@@ -275,19 +276,23 @@ def download_book(
|
||||
logger.info("M4B not available for %s (%s), falling back to MP3", book.title, book.isbn)
|
||||
|
||||
# Fall back to MP3
|
||||
result_path = _download_mp3(book, session, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||
if result_path and (plan.cover_path is not None or plan.pdf_path is not None):
|
||||
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||
result_path, mp3_tracks = _download_mp3(book, session, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||
if result_path:
|
||||
if rename_chapters:
|
||||
_rename_and_log(result_path, mp3_tracks, book.title, reporter)
|
||||
if plan.cover_path is not None or plan.pdf_path is not None:
|
||||
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||
return DownloadResult(status="downloaded", path=result_path, format="mp3")
|
||||
return DownloadResult(status="skipped")
|
||||
|
||||
# --- mp3_only: skip M4B entirely ---
|
||||
if format_strategy == "mp3_only":
|
||||
result_path = _download_mp3(book, session, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||
if result_path and (plan.cover_path is not None or plan.pdf_path is not None):
|
||||
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||
result_path, mp3_tracks = _download_mp3(book, session, output_dir, transport=transport, progress=progress, cancel_event=cancel_event)
|
||||
if result_path:
|
||||
if rename_chapters:
|
||||
_rename_and_log(result_path, mp3_tracks, book.title, reporter)
|
||||
if plan.cover_path is not None or plan.pdf_path is not None:
|
||||
download_accompanying_files(book, plan, client=session, transport=transport)
|
||||
return DownloadResult(status="downloaded", path=result_path, format="mp3")
|
||||
return DownloadResult(status="skipped")
|
||||
|
||||
@@ -306,6 +311,26 @@ def download_book(
|
||||
raise ValueError(f"Unknown format strategy: {format_strategy}")
|
||||
|
||||
|
||||
|
||||
def _rename_and_log(output_dir: Path, tracks: list[dict], book_title: str, reporter=None) -> None:
|
||||
"""Call rename_chapters() and log each rename operation."""
|
||||
mp3_files = list(output_dir.glob("*.mp3"))
|
||||
if len(mp3_files) != len(tracks) and tracks:
|
||||
logger.warning(
|
||||
"Chapter rename: %d MP3 file(s) vs %d track(s) — count mismatch for '%s'",
|
||||
len(mp3_files), len(tracks), book_title,
|
||||
)
|
||||
|
||||
count = rename_chapters(output_dir, tracks, book_title)
|
||||
if count > 0:
|
||||
logger.info("Renamed %d chapter file(s) for '%s'", count, book_title)
|
||||
# Show user-visible feedback with an example filename
|
||||
if reporter is not None:
|
||||
renamed_examples = sorted(output_dir.glob("*.mp3"))
|
||||
example = renamed_examples[0].name if renamed_examples else "(unknown)"
|
||||
reporter.chapter_renamed(count, book_title, example)
|
||||
|
||||
|
||||
def _download_mp3(
|
||||
book: Book,
|
||||
client: "LibroFmSession",
|
||||
@@ -313,18 +338,24 @@ def _download_mp3(
|
||||
transport: httpx.BaseTransport | None = None,
|
||||
progress: "Callable[[int], None] | None" = None,
|
||||
cancel_event: threading.Event | None = None,
|
||||
) -> Path | None:
|
||||
"""Fetch MP3 manifest and download all ZIP parts."""
|
||||
) -> tuple[Path | None, list[dict]]:
|
||||
"""Fetch MP3 manifest and download all ZIP parts.
|
||||
|
||||
Returns:
|
||||
Tuple of (output_dir on success / None on failure, tracks list from manifest).
|
||||
"""
|
||||
tracks: list[dict] = []
|
||||
try:
|
||||
manifest = client.fetch_download_manifest(book.isbn)
|
||||
except M4BUnavailableError:
|
||||
logger.warning("MP3 manifest not available for %s (%s), skipping", book.title, book.isbn)
|
||||
return None
|
||||
return None, tracks
|
||||
|
||||
parts = manifest.get("parts", [])
|
||||
tracks = manifest.get("tracks", [])
|
||||
if not parts:
|
||||
logger.warning("Empty parts list in manifest for %s (%s), skipping", book.title, book.isbn)
|
||||
return None
|
||||
return None, tracks
|
||||
|
||||
all_extracted: list[Path] = []
|
||||
for part in parts:
|
||||
@@ -334,9 +365,9 @@ def _download_mp3(
|
||||
|
||||
# Return output directory as representative path
|
||||
if all_extracted:
|
||||
return output_dir
|
||||
return output_dir, tracks
|
||||
|
||||
return None
|
||||
return None, tracks
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@@ -76,6 +76,10 @@ class PlainTextReporter:
|
||||
authors = ", ".join(book.authors) if book.authors else "Unknown"
|
||||
self._print(f" ⏭ {authors} - {book.title} [{book.isbn}]")
|
||||
|
||||
def chapter_renamed(self, count: int, book_title: str, example_name: str) -> None:
|
||||
"""Log chapter rename result with example filename."""
|
||||
self._print(f" Renamed {count} chapter(s) for '{book_title}' → '{example_name}'")
|
||||
|
||||
def _print(self, message: str) -> None:
|
||||
self._out.write(message + "\n")
|
||||
self._out.flush()
|
||||
@@ -216,6 +220,12 @@ class ProgressReporter:
|
||||
authors = ", ".join(book.authors) if book.authors else "Unknown"
|
||||
self._console.print(f" ⏭ {authors} - {book.title} [{book.isbn}]")
|
||||
|
||||
def chapter_renamed(self, count: int, book_title: str, example_name: str) -> None:
|
||||
"""Log chapter rename result with example filename."""
|
||||
self._console.print(
|
||||
f" [dim]Renamed[/dim] {count} chapter(s) for "
|
||||
f"'[italic]{book_title}[/italic]' → [cyan]{example_name}[/cyan]"
|
||||
)
|
||||
|
||||
def _fmt_size(bytes_val: int) -> str:
|
||||
"""Format byte count as human-readable size string."""
|
||||
|
||||
@@ -197,7 +197,7 @@ def sync_run(
|
||||
# --- Download loop (parallel via orchestrator — Issue #16) ---
|
||||
|
||||
def _make_download_fn():
|
||||
"""Closure capturing session, config, history, reporter for each book."""
|
||||
_rc = resolved_rename_chapters # capture resolved value
|
||||
|
||||
def _download_fn(
|
||||
book: Book, *, progress: Callable[[int], None] | None = None
|
||||
@@ -209,8 +209,7 @@ def sync_run(
|
||||
config=config,
|
||||
format_strategy=config.format,
|
||||
)
|
||||
|
||||
result = download_book(book, client, plan, reporter, progress=progress)
|
||||
result = download_book(book, client, plan, reporter, progress=progress, rename_chapters=_rc)
|
||||
|
||||
# Write history as caller (no longer inside download_book)
|
||||
if result.status == "downloaded":
|
||||
|
||||
@@ -2101,3 +2101,370 @@ class TestRenameChapters:
|
||||
assert Path(tmpdir, "1 - No Titles Book - Chapter 1.mp3").exists()
|
||||
assert Path(tmpdir, "2 - No Titles Book - Chapter 2.mp3").exists()
|
||||
assert Path(tmpdir, "3 - No Titles Book - Chapter 3.mp3").exists()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue #34: Wire rename_chapters() into download pipeline
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestRenameChaptersWiring:
|
||||
"""Integration tests: rename_chapters wired into download pipeline."""
|
||||
|
||||
def test_mp3_only_rename_chapters_true_renames_files(self):
|
||||
"""mp3_only + rename_chapters=True → MP3 files renamed after extraction."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
# Create ZIP with 2 MP3 files
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-1")
|
||||
zf.writestr("2.mp3", b"audio-2")
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
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": "Prologue"},
|
||||
{"number": 2, "chapter_title": "The Start"},
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="Rename Test Book", authors=["Author"], narrators=["N"], isbn="9789900000001")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True, # ← THE KEY PARAMETER (doesn't exist yet — test will fail)
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "mp3"
|
||||
|
||||
# Files should be renamed with chapter titles
|
||||
output_dir = result.path
|
||||
assert (output_dir / "1 - Rename Test Book - Prologue.mp3").exists()
|
||||
assert (output_dir / "2 - Rename Test Book - The Start.mp3").exists()
|
||||
# Original numeric names should be gone
|
||||
assert not (output_dir / "1.mp3").exists()
|
||||
assert not (output_dir / "2.mp3").exists()
|
||||
|
||||
def test_m4b_only_rename_chapters_not_called(self):
|
||||
"""m4b_only + rename_chapters=True → no rename (no MP3s)."""
|
||||
m4b_content = b"fake-m4b-data"
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [],
|
||||
"tracks": [{"number": 1, "chapter_title": "Ch1"}],
|
||||
},
|
||||
)
|
||||
if "/packaged_m4b" in request.url.path:
|
||||
return httpx.Response(200, json={"m4b_url": "https://cdn.example.com/book.m4b"})
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=m4b_content)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="M4B Only Book", authors=["Author"], narrators=["N"], isbn="9789900000002")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True, # even with True, M4B should not trigger rename
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "m4b"
|
||||
# No MP3 files should exist at all
|
||||
mp3_files = list(result.path.glob("*.mp3"))
|
||||
assert len(mp3_files) == 0
|
||||
|
||||
def test_rename_chapters_false_skips_rename(self):
|
||||
"""mp3_only + rename_chapters=False (default) → files NOT renamed."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-1")
|
||||
zf.writestr("2.mp3", b"audio-2")
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
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": "Prologue"},
|
||||
{"number": 2, "chapter_title": "The Start"},
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="No Rename Book", authors=["Author"], narrators=["N"], isbn="9789900000004")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
# rename_chapters defaults to False
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=False,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "mp3"
|
||||
|
||||
output_dir = result.path
|
||||
# Original numeric names should still exist (not renamed)
|
||||
assert (output_dir / "1.mp3").exists()
|
||||
assert (output_dir / "2.mp3").exists()
|
||||
# Renamed versions should NOT exist
|
||||
assert not (output_dir / "1 - No Rename Book - Prologue.mp3").exists()
|
||||
|
||||
def test_m4b_mp3_fallback_renames_on_fallback(self):
|
||||
"""m4b_mp3_fallback: M4B fails, MP3 fallback + rename_chapters=True → renamed."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-1")
|
||||
zf.writestr("2.mp3", b"audio-2")
|
||||
zf.writestr("3.mp3", b"audio-3")
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
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": "Opening"},
|
||||
{"number": 2, "chapter_title": "Middle"},
|
||||
{"number": 3, "chapter_title": "Closing"},
|
||||
],
|
||||
},
|
||||
)
|
||||
# M4B endpoint returns error → triggers fallback
|
||||
if request.url.path == "/api/v10/m4b":
|
||||
return httpx.Response(404)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="Fallback Book", authors=["Author"], narrators=["N"], isbn="9789900000003")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "mp3"
|
||||
|
||||
output_dir = result.path
|
||||
assert (output_dir / "1 - Fallback Book - Opening.mp3").exists()
|
||||
assert (output_dir / "2 - Fallback Book - Middle.mp3").exists()
|
||||
assert (output_dir / "3 - Fallback Book - Closing.mp3").exists()
|
||||
|
||||
def test_count_mismatch_produces_warning(self, caplog):
|
||||
"""MP3 file count != track count → warning logged (no crash)."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-1")
|
||||
zf.writestr("2.mp3", b"audio-2")
|
||||
zf.writestr("3.mp3", b"audio-3") # 3 files but only 2 tracks
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
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": "Ch1"},
|
||||
{"number": 2, "chapter_title": "Ch2"},
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="Mismatch Book", authors=["Author"], narrators=["N"], isbn="9789900000005")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
caplog.set_level("WARNING", logger="librofm_downloader.downloader")
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
messages = [r.message for r in caplog.records]
|
||||
assert any("mismatch" in m.lower() for m in messages), \
|
||||
f"Expected count-mismatch warning, got: {messages}"
|
||||
|
||||
def test_rename_logs_each_operation(self, caplog):
|
||||
"""rename_chapters=True → info log shows renamed file count."""
|
||||
import io
|
||||
import zipfile
|
||||
import logging
|
||||
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-1")
|
||||
zf.writestr("2.mp3", b"audio-2")
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
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": "Alpha"},
|
||||
{"number": 2, "chapter_title": "Beta"},
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="Log Test Book", authors=["Author"], narrators=["N"], isbn="9789900000006")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
with caplog.at_level(logging.INFO, logger="librofm_downloader.downloader"):
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
|
||||
# Should have an INFO log about renaming
|
||||
info_messages = [r.message for r in caplog.records if r.levelno == logging.INFO]
|
||||
assert any("renamed" in m.lower() for m in info_messages), \
|
||||
f"Expected 'renamed' info message, got: {info_messages}"
|
||||
assert any("log test book" in m.lower() for m in info_messages), \
|
||||
f"Expected book title in log, got: {info_messages}"
|
||||
Reference in new issue
Block a user