refactor: extract book.py and path.py from downloader monolith

Move Book dataclass + from_library_row() into dedicated book.py.
Extract sanitize/resolve_path/needs_subdirectory into path.py.
Hard-cut import migration across 7 source+test files. 79 new tests.

Closes #26
This commit is contained in:
AlexKucera committed 2026-06-04 14:18:40 +02:00
1 parent 323fbf76fd
commit fb219be248
13 files changed
+1268 -309

No files matched your search

+53
View File
@@ -0,0 +1,53 @@
"""Book domain model and API-shape intake for librofm-downloader.
Owns the Book dataclass and the from_library_row() intake function that
converts raw Libro.fm API dicts into Book objects. No knowledge of raw
API dict shape should exist outside this module.
"""
from dataclasses import dataclass
@dataclass(frozen=True)
class Book:
"""Immutable book metadata record from Libro.fm."""
title: str
authors: list[str]
narrators: list[str]
isbn: str
series: str = ""
series_num: int | None = None
cover_url: str = ""
pdf_extras: bool = False
publication_year: int | None = None
publication_month: int | None = None
publication_day: int | None = None
def from_library_row(raw: dict) -> Book:
"""Convert a Libro.fm API dict to a Book object.
Handles ISBN str coercion (API sometimes returns int),
nested narrator resolution, PDF extras bool coercion,
and default values for missing fields.
"""
audiobook_info = raw.get("audiobook_info", {}) or {}
narrators = audiobook_info.get("narrators", []) or raw.get("narrators", [])
raw_isbn = raw.get("isbn", "?")
isbn = str(raw_isbn) if raw_isbn is not None else "?"
return Book(
title=raw.get("title", "Unknown"),
authors=raw.get("authors", []),
narrators=narrators,
isbn=isbn,
series=raw.get("series", ""),
series_num=raw.get("series_num"),
cover_url=raw.get("cover_url", ""),
pdf_extras=bool(audiobook_info.get("pdf_extras")) if audiobook_info else False,
publication_year=raw.get("publication_year"),
publication_month=raw.get("publication_month"),
publication_day=raw.get("publication_day"),
)
+2 -1
View File
@@ -10,7 +10,8 @@ from rich.console import Console
from librofm_downloader.config import load_config, ConfigError, _resolve_config_file
from librofm_downloader.client import LibroFmClient, AuthError
from librofm_downloader.history import DownloadHistory
from librofm_downloader.downloader import Book, download_book
from librofm_downloader.book import Book
from librofm_downloader.downloader import download_book
from librofm_downloader.orchestrator import download_all_books
from librofm_downloader.progress import DownloadReporter
+21 -187
View File
@@ -1,10 +1,27 @@
"""Path resolution and sanitization for librofm-downloader.
"""Download engine for librofm-downloader.
Pure logic module — no I/O, no network. All deterministic string manipulation.
Streaming downloads (M4B, ZIP parts), accompanying files (covers, PDFs),
and download orchestration. Path logic lives in ``path.py``; Book domain
object lives in ``book.py``.
"""
import logging
import threading
from pathlib import Path
import httpx
from librofm_downloader.book import Book
from librofm_downloader.client import M4BUnavailableError
from librofm_downloader.history import HistoryEntry
from librofm_downloader.path import (
_resolve_output_dir,
needs_subdirectory,
resolve_path,
sanitize,
)
logger = logging.getLogger(__name__)
class InterruptedDownload(Exception):
@@ -15,161 +32,6 @@ class InterruptedDownload(Exception):
callers can distinguish "user hit Ctrl+C" from "download was cancelled
cooperatively during drain."
"""
import re
from dataclasses import dataclass
from pathlib import Path
import httpx
from librofm_downloader.client import M4BUnavailableError
from librofm_downloader.history import HistoryEntry
logger = logging.getLogger(__name__)
# Characters that are unsafe in filesystem path components
_ILLEGAL_CHARS = str.maketrans("", "", "<>/\\|?*")
# Control characters U+0000–U+001F
_CONTROL_CHARS = {chr(i) for i in range(0x00, 0x20)}
@dataclass(frozen=True)
class Book:
"""Immutable book metadata record from Libro.fm."""
title: str
authors: list[str]
narrators: list[str]
isbn: str
series: str = ""
series_num: int | None = None
cover_url: str = ""
pdf_extras: bool = False
publication_year: int | None = None
publication_month: int | None = None
publication_day: int | None = None
def sanitize(component: str) -> str:
"""Sanitize a single path component for filesystem safety.
Rules applied in order:
1. Replace ``:`` with `` -``
2. Strip ``< > / \\ | ? *`` and control characters (U+0000–U+001F)
3. Remove trailing dots
4. Trim whitespace
5. Cap at 255 characters
Preserves: dashes, commas, apostrophes, parentheses, periods (non-trailing).
"""
# 1. Replace colons
result = component.replace(":", " -")
# 2. Strip illegal chars and control characters
result = result.translate(_ILLEGAL_CHARS)
result = "".join(ch for ch in result if ch not in _CONTROL_CHARS)
# 3. Trim whitespace (before dot removal so exposed dots are caught)
result = result.strip()
# 4. Remove trailing dots
result = result.rstrip(".")
# 5. Cap at 255 characters
return result[:255]
# Token name → (attribute_path, formatter)
# attribute_path is a space-separated chain of attr lookups;
# formatter converts the raw value to string.
_TOKEN_REGISTRY: dict[str, tuple[str, str]] = {
"FIRST_AUTHOR": ("authors", "first"),
"ALL_AUTHORS": ("authors", "join"),
"SERIES_NAME": ("series", "raw"),
"SERIES_NUM": ("series_num", "raw"),
"BOOK_TITLE": ("title", "raw"),
"ISBN": ("isbn", "raw"),
"FIRST_NARRATOR":("narrators", "first"),
"ALL_NARRATORS": ("narrators", "join"),
"PUBLICATION_YEAR": ("publication_year", "raw"),
"PUBLICATION_MONTH": ("publication_month", "raw"),
"PUBLICATION_DAY": ("publication_day", "raw"),
}
def _token_value(book: Book, token: str) -> str:
"""Resolve a single token to its string value from the book."""
if token not in _TOKEN_REGISTRY:
return ""
attr, fmt = _TOKEN_REGISTRY[token]
# Get the attribute value
val = getattr(book, attr)
# Format based on formatter type
if fmt == "first":
if isinstance(val, list) and val:
return str(val[0])
return ""
if fmt == "join":
if isinstance(val, list):
return ", ".join(str(v) for v in val)
return str(val) if val is not None else ""
# fmt == "raw"
return str(val) if val is not None else ""
def resolve_path(book: Book, pattern: str | None = None) -> str:
"""Resolve the relative output path for a book.
Args:
book: The book metadata.
pattern: Optional custom path pattern with token placeholders.
When set, overrides default conditional logic.
Tokens: FIRST_AUTHOR, ALL_AUTHORS, SERIES_NAME, SERIES_NUM,
BOOK_TITLE, ISBN, FIRST_NARRATOR, ALL_NARRATORS,
PUBLICATION_YEAR, PUBLICATION_MONTH, PUBLICATION_DAY.
Returns:
Sanitized relative path string.
"""
if pattern:
return _resolve_custom_pattern(book, pattern)
return _resolve_default_path(book)
def _resolve_default_path(book: Book) -> str:
"""Default conditional path logic."""
first_author = sanitize(book.authors[0] if book.authors else "Unknown")
title = sanitize(book.title)
if book.series and book.series_num is not None:
series_name = sanitize(book.series)
return f"{first_author}/{series_name}/Book {book.series_num} {title}"
if book.series:
series_name = sanitize(book.series)
return f"{first_author}/{series_name}/{title}"
return f"{first_author}/{title}"
def _resolve_custom_pattern(book: Book, pattern: str) -> str:
"""Resolve path using custom pattern with token substitution."""
def replacer(match: re.Match) -> str:
token = match.group(1)
raw = _token_value(book, token)
return sanitize(raw)
# Replace {TOKEN} patterns
result = re.sub(r"\{([A-Z_]+)\}", replacer, pattern)
return result
def needs_subdirectory(book: Book) -> bool:
"""Check whether a book needs a subdirectory for accompanying files.
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)
# ---------------------------------------------------------------------------
@@ -186,6 +48,7 @@ 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)
@@ -290,7 +153,7 @@ def download_m4b(
"""Download an M4B file via streaming chunks.
Writes to ``{output_path}.partial`` during transfer, then atomically
renames to the final ``{output_path}`` on completion.
renames to the final ``output_path`` on completion.
Args:
url: The CDN URL for the M4B file.
@@ -350,35 +213,6 @@ def download_m4b(
raise
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/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')
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
def download_book(
book: Book,
client: "LibroFmClient",
+2 -23
View File
@@ -18,7 +18,7 @@ from typing import Any, Callable
from rich.console import Console
from librofm_downloader.downloader import Book
from librofm_downloader.book import Book, from_library_row
def _hard_exit(code: int) -> None:
@@ -54,27 +54,6 @@ class OrchestratorResult:
interrupted: bool = False
def _raw_to_book(raw: dict) -> Book:
"""Convert a Libro.fm API dict to a Book object.
Mirrors the Book-building logic previously in cli.py's download loop.
"""
audiobook_info = raw.get("audiobook_info", {}) or {}
narrators = audiobook_info.get("narrators", []) or raw.get("narrators", [])
return Book(
title=raw.get("title", "Unknown"),
authors=raw.get("authors", []),
narrators=narrators,
isbn=raw.get("isbn", "?"),
series=raw.get("series", ""),
series_num=raw.get("series_num"),
cover_url=raw.get("cover_url", ""),
pdf_extras=bool(audiobook_info.get("pdf_extras")) if audiobook_info else False,
publication_year=raw.get("publication_year"),
publication_month=raw.get("publication_month"),
publication_day=raw.get("publication_day"),
)
def _download_one(
@@ -140,7 +119,7 @@ def download_all_books(
# Convert raw dicts to Book objects, preserving order and index
books_with_index: list[tuple[int, Book]] = [
(i, _raw_to_book(raw)) for i, raw in enumerate(raw_books)
(i, from_library_row(raw)) for i, raw in enumerate(raw_books)
]
downloaded_count = 0
+158
View File
@@ -0,0 +1,158 @@
"""Path resolution and sanitization for librofm-downloader.
Pure logic module — no I/O, no network. All deterministic string manipulation.
"""
import re
from pathlib import Path
from librofm_downloader.book import Book
# Characters that are unsafe in filesystem path components
_ILLEGAL_CHARS = str.maketrans("", "", "<>/\\|?*")
# Control characters U+0000–U+001F
_CONTROL_CHARS = {chr(i) for i in range(0x00, 0x20)}
def sanitize(component: str) -> str:
"""Sanitize a single path component for filesystem safety.
Rules applied in order:
1. Replace ``:`` with `` -``
2. Strip ``< > / \\ | ? *`` and control characters (U+0000–U+001F)
3. Remove trailing dots
4. Trim whitespace
5. Cap at 255 characters
Preserves: dashes, commas, apostrophes, parentheses, periods (non-trailing).
"""
result = component.replace(":", " -")
result = result.translate(_ILLEGAL_CHARS)
result = "".join(ch for ch in result if ch not in _CONTROL_CHARS)
result = result.strip()
result = result.rstrip(".")
return result[:255]
# Token name → (attribute_path, formatter)
_TOKEN_REGISTRY: dict[str, tuple[str, str]] = {
"FIRST_AUTHOR": ("authors", "first"),
"ALL_AUTHORS": ("authors", "join"),
"SERIES_NAME": ("series", "raw"),
"SERIES_NUM": ("series_num", "raw"),
"BOOK_TITLE": ("title", "raw"),
"ISBN": ("isbn", "raw"),
"FIRST_NARRATOR":("narrators", "first"),
"ALL_NARRATORS": ("narrators", "join"),
"PUBLICATION_YEAR": ("publication_year", "raw"),
"PUBLICATION_MONTH": ("publication_month", "raw"),
"PUBLICATION_DAY": ("publication_day", "raw"),
}
def _token_value(book: Book, token: str) -> str:
"""Resolve a single token to its string value from the book."""
if token not in _TOKEN_REGISTRY:
return ""
attr, fmt = _TOKEN_REGISTRY[token]
val = getattr(book, attr)
if fmt == "first":
if isinstance(val, list) and val:
return str(val[0])
return ""
if fmt == "join":
if isinstance(val, list):
return ", ".join(str(v) for v in val)
return str(val) if val is not None else ""
# fmt == "raw"
return str(val) if val is not None else ""
def resolve_path(book: Book, pattern: str | None = None) -> str:
"""Resolve the relative output path for a book.
Args:
book: The book metadata.
pattern: Optional custom path pattern with token placeholders.
When set, overrides default conditional logic.
Tokens: FIRST_AUTHOR, ALL_AUTHORS, SERIES_NAME, SERIES_NUM,
BOOK_TITLE, ISBN, FIRST_NARRATOR, ALL_NARRATORS,
PUBLICATION_YEAR, PUBLICATION_MONTH, PUBLICATION_DAY.
Returns:
Sanitized relative path string.
"""
if pattern:
return _resolve_custom_pattern(book, pattern)
return _resolve_default_path(book)
def _resolve_default_path(book: Book) -> str:
"""Default conditional path logic."""
first_author = sanitize(book.authors[0] if book.authors else "Unknown")
title = sanitize(book.title)
if book.series and book.series_num is not None:
series_name = sanitize(book.series)
return f"{first_author}/{series_name}/Book {book.series_num} {title}"
if book.series:
series_name = sanitize(book.series)
return f"{first_author}/{series_name}/{title}"
return f"{first_author}/{title}"
def _resolve_custom_pattern(book: Book, pattern: str) -> str:
"""Resolve path using custom pattern with token substitution."""
def replacer(match: re.Match) -> str:
token = match.group(1)
raw = _token_value(book, token)
return sanitize(raw)
# Replace {TOKEN} patterns
result = re.sub(r"\{([A-Z_]+)\}", replacer, pattern)
return result
def needs_subdirectory(book: Book) -> bool:
"""Check whether a book needs a subdirectory for accompanying files.
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)
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/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')
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