fix(downloader): resolve path doubling and cover download failures
needs_subdirectory() treated always-present cover_url as a subdirectory trigger, and _resolve_output_dir() double-appended the title from resolve_path(), producing Author/Title/Title/Title.m4b paths. Cover downloads also failed silently: _download_cover() used a naked httpx.Client without Libro.fm headers (CDN rejection), and protocol-relative URLs (//cdn.libro.fm/...) caused httpx errors.
This commit is contained in:
1 parent
4aaae68a2e
commit
e2da04ad92
5 files changed
+219
-19
No files matched your search
@@ -15,4 +15,5 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
|
||||
| 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** |
|
||||
| 2026-06-03 | issue | [20260603-fix-path-doubling-and-cover-download-issue_log.md](docs/devlog/20260603-fix-path-doubling-and-cover-download-issue_log.md) | **Path doubling fix:** `needs_subdirectory()` no longer triggered by always-present `cover_url`, title no longer double-appended in `_resolve_output_dir()`, cover download fixed (headers + protocol-relative URLs). **172/172 tests** |
|
||||
| 2026-06-03 | issue | [20260603-project-scaffolding-and-config-module-issue2_log.md](docs/devlog/20260603-project-scaffolding-and-config-module-issue2_log.md) | **Issue #2 Complete:** pyproject.toml + venv + config module (load/merge/validate) + 25 tests. 11/11 AC met |
|
||||
@@ -46,6 +46,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
graceful shutdown, and integration scenarios (168 total)
|
||||
|
||||
### Fixed
|
||||
- **downloader:** Path doubling: `resolve_path()` returns Author/Title but code
|
||||
appended title again, producing nested folders like Title/Title/Title.m4b.
|
||||
Also fix cover download: add Libro.fm headers to httpx client, normalize
|
||||
protocol-relative URLs (//cdn → https://cdn)
|
||||
- Library endpoint key mismatch: API returns "audiobooks" not "books"
|
||||
- M4B endpoint key mismatch: API returns "m4b_url" not "url"
|
||||
- Narrators nested under `audiobook_info.narrators` in API response
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
# Fix Path Doubling & Cover Download
|
||||
|
||||
> **Date:** 2026-06-03
|
||||
> **Type:** issue
|
||||
> **Reference:** Untracked bug (user-reported path doubling)
|
||||
|
||||
## Goal
|
||||
|
||||
Fix a path resolution bug where audiobook downloads produced doubled folder structures like:
|
||||
```
|
||||
audiobooks/Tiffany Crum/This Story Might Save Your Life/This Story Might Save Your Life.m4b
|
||||
```
|
||||
Instead of the correct flat or single-subfolder path. Also fix cover art downloads that were silently failing.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### Bug 1: `needs_subdirectory()` treated `cover_url` as a subdirectory trigger
|
||||
- **File:** `librofm_downloader/downloader.py`
|
||||
- **Function:** `needs_subdirectory()`
|
||||
- **Before:** `return bool(book.pdf_extras) or bool(book.cover_url)` — since Libro.fm always returns a `cover_url`, this was effectively always `True`
|
||||
- **After:** `return bool(book.pdf_extras)` — only PDF extras trigger subdirectory at this level; covers are handled in `_resolve_output_dir()` with config awareness
|
||||
|
||||
### Bug 2: `_resolve_output_dir()` double-appended the title
|
||||
- **File:** `librofm_downloader/downloader.py`
|
||||
- **Function:** `_resolve_output_dir()`
|
||||
- **Before:** Called `resolve_path(book)` which returns `"Author/Title"`, then appended `title_sanitized` again → `"Author/Title/Title"`
|
||||
- **After:** Uses `resolve_path(book)` directly as the relative path — no extra title append
|
||||
- **Also added:** Optional `config` parameter so that `download_covers=True` + `book.cover_url` can trigger subdirectory when covers will actually be downloaded
|
||||
|
||||
### Bug 3: Cover download used naked httpx client (no headers)
|
||||
- **File:** `librofm_downloader/downloader.py`
|
||||
- **Function:** `_download_cover()`
|
||||
- **Before:** `httpx.Client(transport=transport, follow_redirects=True)` — no headers
|
||||
- **After:** Adds `headers=LibroFmClient.DEFAULT_HEADERS` (`X-LibroFm-AppVer`, `User-Agent`) so CDN accepts requests
|
||||
|
||||
### Bug 4: Protocol-relative cover URLs rejected by httpx
|
||||
- **File:** `librofm_downloader/downloader.py`
|
||||
- **Function:** `_download_cover()`
|
||||
- **Problem:** Libro.fm returns `//covers.libro.fm/978...jpg` — httpx raises "Request URL is missing an 'http://' or 'https://' protocol"
|
||||
- **Fix:** Added normalization: `if url.startswith("//"): url = "https:" + url`
|
||||
|
||||
### Tests updated
|
||||
- **File:** `tests/test_downloader.py`
|
||||
- Renamed `test_true_when_cover_url_present` → `test_false_when_cover_url_only`
|
||||
- Added `test_book_with_only_cover_does_not_create_subdirectory`
|
||||
- Replaced config-gated cover tests with: `test_resolve_output_dir_flat_for_cover_only_without_config`, `test_resolve_output_dir_flat_for_cover_regardless_of_config`, `test_resolve_output_dir_subdir_no_title_doubling`
|
||||
- Updated comments to reflect new semantics
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Covers should trigger subdirectory when `download_covers=True` + `cover_url` exists | User explicitly wants this behavior — cover sits alongside .m4b in a titled folder |
|
||||
| Covers do NOT trigger subdirectory when `download_covers=False` | No extra files to store, so flat author-dir layout |
|
||||
| `resolve_path()` already includes title — don't double it | `resolve_path()` returns `"Author/Series/Title"` or `"Author/Title"`; appending title again created the doubling |
|
||||
| Keep `config` param on `_resolve_output_dir` rather than `needs_subdirectory` | Subdirectory decision needs both book data AND user config — cleaner to resolve at call site |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Path doubling: `Author/Title/Title.m4b` | `resolve_path()` returns `Author/Title`, then code appended `title_sanitized` again | Removed extra append; use `resolve_path()` result directly |
|
||||
| Every book got a subfolder | `needs_subdirectory()` checked `bool(cover_url)` — Libro.fm always returns one | Changed to only check `pdf_extras`; moved cover logic to `_resolve_output_dir` with config gating |
|
||||
| Cover never downloaded (silent failure) | `_download_cover()` used bare `httpx.Client` without `X-LibroFm-AppVer` / `User-Agent` headers — CDN rejected request | Added `LibroFmClient.DEFAULT_HEADERS` to the client |
|
||||
| `Failed to download cover from //covers.libro.fm/...` | Protocol-relative URL (`//host/path`) not accepted by httpx | Prepend `https:` when URL starts with `//` |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `librofm_downloader/downloader.py` | Fixed `needs_subdirectory()`, `_resolve_output_dir()` (no title doubling + config-aware cover gating), `_download_cover()` (headers + protocol-relative URL fix) |
|
||||
| `tests/test_downloader.py` | Updated 6 tests for new semantics; added 2 new tests for title-doubling and flat-cover behavior |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] Re-run download for "This Story Might Save Your Life" to verify cover image appears in the subfolder
|
||||
- [ ] Consider adding a test for protocol-relative URL normalization in `_download_cover`
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
@@ -153,9 +153,12 @@ def _resolve_custom_pattern(book: Book, pattern: str) -> str:
|
||||
def needs_subdirectory(book: Book) -> bool:
|
||||
"""Check whether a book needs a subdirectory for accompanying files.
|
||||
|
||||
Returns True when PDF extras or cover art are present.
|
||||
Returns True when PDF extras are present.
|
||||
Cover art does NOT trigger a subdirectory here — cover downloads are
|
||||
config-gated (``config.download_covers``) and considered separately
|
||||
in ``_resolve_output_dir``.
|
||||
"""
|
||||
return bool(book.pdf_extras) or bool(book.cover_url)
|
||||
return bool(book.pdf_extras)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -323,19 +326,30 @@ def download_m4b(
|
||||
return output_path
|
||||
|
||||
|
||||
def _resolve_output_dir(book: Book, output_base: Path | str) -> Path:
|
||||
def _resolve_output_dir(
|
||||
book: Book,
|
||||
output_base: Path | str,
|
||||
config: "Config | None" = None,
|
||||
) -> 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 books with accompanying files → subdirectory: base/Author/Title/
|
||||
For standalone books → parent dir only: base/Author/ (file is leaf: Title.m4b)
|
||||
|
||||
Subdirectory is needed when:
|
||||
- PDF extras exist (multi-file output), OR
|
||||
- Cover art will be downloaded (``config.download_covers`` + ``book.cover_url``)
|
||||
"""
|
||||
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
|
||||
needs_subdir = needs_subdirectory(book) # pdf_extras
|
||||
if not needs_subdir and config is not None:
|
||||
needs_subdir = bool(config.download_covers and book.cover_url)
|
||||
|
||||
if needs_subdir:
|
||||
relative = resolve_path(book) # e.g. "Author/Title" — already includes title
|
||||
return base / relative
|
||||
|
||||
# Flat: file is leaf node under author dir
|
||||
return base / first_author
|
||||
@@ -367,7 +381,7 @@ def download_book(
|
||||
"""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
output_dir = _resolve_output_dir(book, output_base)
|
||||
output_dir = _resolve_output_dir(book, output_base, config=config)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# --- m4b_mp3_fallback: try M4B first, fall back to MP3 ---
|
||||
@@ -472,16 +486,30 @@ def _download_cover(
|
||||
) -> Path | None:
|
||||
"""Download a cover art file via streaming .partial → atomic rename.
|
||||
|
||||
Sends the same User-Agent/AppVer headers as the main client so the
|
||||
Libro.fm CDN accepts the request.
|
||||
|
||||
Returns Path on success, None on failure (logs warning).
|
||||
"""
|
||||
from librofm_downloader.client import LibroFmClient
|
||||
|
||||
filename = _cover_filename_from_url(url)
|
||||
|
||||
# Normalize protocol-relative URLs (//covers.libro.fm/... → https://covers.libro.fm/...)
|
||||
if url.startswith("//"):
|
||||
url = "https:" + url
|
||||
|
||||
output_path = output_dir / filename
|
||||
partial_path = output_path.with_suffix(output_path.suffix + ".partial")
|
||||
|
||||
try:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
client = httpx.Client(transport=transport, follow_redirects=True)
|
||||
client = httpx.Client(
|
||||
transport=transport,
|
||||
follow_redirects=True,
|
||||
headers=LibroFmClient.DEFAULT_HEADERS,
|
||||
)
|
||||
with client.stream("GET", url) as resp:
|
||||
resp.raise_for_status()
|
||||
with open(partial_path, "wb") as f:
|
||||
|
||||
@@ -386,7 +386,8 @@ class TestNeedsSubdirectory:
|
||||
)
|
||||
assert needs_subdirectory(book) is True
|
||||
|
||||
def test_true_when_cover_url_present(self):
|
||||
def test_false_when_cover_url_only(self):
|
||||
"""cover_url alone does NOT trigger subdirectory — config-gated."""
|
||||
book = Book(
|
||||
title="Some Book",
|
||||
authors=["Author"],
|
||||
@@ -395,7 +396,7 @@ class TestNeedsSubdirectory:
|
||||
pdf_extras=False,
|
||||
cover_url="https://example.com/cover.jpg",
|
||||
)
|
||||
assert needs_subdirectory(book) is True
|
||||
assert needs_subdirectory(book) is False
|
||||
|
||||
def test_true_when_both_present(self):
|
||||
book = Book(
|
||||
@@ -1368,18 +1369,33 @@ class TestDownloadAccompanyingFiles:
|
||||
class TestOutputStructure:
|
||||
"""Integration tests for output directory structure with/without extras."""
|
||||
|
||||
def test_book_with_extras_creates_subdirectory(self):
|
||||
"""Book with cover_url → needs_subdirectory=True, output is a folder."""
|
||||
def test_book_with_pdf_extras_creates_subdirectory(self):
|
||||
"""Book with pdf_extras → needs_subdirectory=True."""
|
||||
book = Book(
|
||||
title="Book With Extras",
|
||||
authors=["Author Name"],
|
||||
narrators=["Narrator"],
|
||||
isbn="9785555555555",
|
||||
pdf_extras=True,
|
||||
cover_url="",
|
||||
)
|
||||
|
||||
# Only pdf_extras triggers subdirectory (not cover_url)
|
||||
assert needs_subdirectory(book) is True
|
||||
|
||||
def test_book_with_only_cover_does_not_create_subdirectory(self):
|
||||
"""Book with only cover_url → needs_subdirectory=False (config-gated)."""
|
||||
book = Book(
|
||||
title="Book With Cover Only",
|
||||
authors=["Author Name"],
|
||||
narrators=["Narrator"],
|
||||
isbn="9785555555556",
|
||||
pdf_extras=False,
|
||||
cover_url="https://cdn.example.com/cover.jpg",
|
||||
)
|
||||
|
||||
# Book with accompanying files should need subdirectory
|
||||
assert needs_subdirectory(book) is True
|
||||
# cover_url alone doesn't trigger — needs config.download_covers too
|
||||
assert needs_subdirectory(book) is False
|
||||
|
||||
def test_book_without_extras_is_flat(self):
|
||||
"""Book without cover or PDF → needs_subdirectory=False, output is leaf file."""
|
||||
@@ -1393,14 +1409,15 @@ class TestOutputStructure:
|
||||
# Book without accompanying files should be flat
|
||||
assert needs_subdirectory(book) is False
|
||||
|
||||
def test_resolve_output_dir_creates_subdir_for_extras(self):
|
||||
"""_resolve_output_dir creates subdirectory when book has extras."""
|
||||
def test_resolve_output_dir_creates_subdir_for_pdf_extras(self):
|
||||
"""_resolve_output_dir creates subdirectory when book has pdf_extras."""
|
||||
book = Book(
|
||||
title="Subdir Book",
|
||||
authors=["Author Name"],
|
||||
narrators=["Narrator"],
|
||||
isbn="9787777777777",
|
||||
cover_url="https://cdn.example.com/cover.jpg",
|
||||
pdf_extras=True,
|
||||
cover_url="",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
@@ -1415,6 +1432,75 @@ class TestOutputStructure:
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
assert output_dir.is_dir()
|
||||
|
||||
def test_resolve_output_dir_flat_for_cover_only_without_config(self):
|
||||
"""cover_url without config → flat path (no subdirectory)."""
|
||||
book = Book(
|
||||
title="Cover Only Flat",
|
||||
authors=["Author Name"],
|
||||
narrators=["Narrator"],
|
||||
isbn="9787777777778",
|
||||
pdf_extras=False,
|
||||
cover_url="https://cdn.example.com/cover.jpg",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base = Path(tmpdir) / "audiobooks"
|
||||
output_dir = _resolve_output_dir(book, base)
|
||||
|
||||
# cover_url doesn't create subdirectory (covers sit alongside .m4b)
|
||||
assert output_dir == base / "Author Name"
|
||||
|
||||
def test_resolve_output_dir_flat_for_cover_regardless_of_config(self):
|
||||
"""cover_url never creates subdirectory — cover sits alongside .m4b.
|
||||
|
||||
Even with download_covers=True in config, the cover is a single file that
|
||||
lives next to the audiobook file. No folder needed.
|
||||
"""
|
||||
book = Book(
|
||||
title="Cover Flat Book",
|
||||
authors=["Author Name"],
|
||||
narrators=["Narrator"],
|
||||
isbn="9787777777779",
|
||||
pdf_extras=False,
|
||||
cover_url="https://cdn.example.com/cover.jpg",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base = Path(tmpdir) / "audiobooks"
|
||||
output_dir = _resolve_output_dir(book, base)
|
||||
|
||||
# Cover URL alone → flat path, no subdirectory
|
||||
assert output_dir == base / "Author Name"
|
||||
|
||||
def test_resolve_output_dir_subdir_no_title_doubling(self):
|
||||
"""When pdf_extras creates a subdir, title is NOT doubled.
|
||||
|
||||
resolve_path() returns 'Author/Title'. The subdir should be exactly that,
|
||||
not 'Author/Title/Title'.
|
||||
"""
|
||||
book = Book(
|
||||
title="Subdir No Double",
|
||||
authors=["Author Name"],
|
||||
narrators=["Narrator"],
|
||||
isbn="9787777777780",
|
||||
pdf_extras=True,
|
||||
cover_url="",
|
||||
)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base = Path(tmpdir) / "audiobooks"
|
||||
output_dir = _resolve_output_dir(book, base)
|
||||
|
||||
# Should be base/Author/Subdir No Double — title appears once
|
||||
expected = base / "Author Name" / "Subdir No Double"
|
||||
assert output_dir == expected, f"Expected {expected}, got {output_dir}"
|
||||
|
||||
# Verify no doubled title component
|
||||
parts = output_dir.parts
|
||||
# Count how many times the sanitized title appears
|
||||
title_parts = [p for p in parts if p == "Subdir No Double"]
|
||||
assert len(title_parts) == 1, f"Title doubled in path: {output_dir}"
|
||||
|
||||
def test_resolve_output_dir_flat_for_no_extras(self):
|
||||
"""_resolve_output_dir returns flat path when no extras (audio is leaf file)."""
|
||||
book = Book(
|
||||
|
||||
Reference in new issue
Block a user