refactor(session): rename LibroFmClient → LibroFmSession

Relocate API client from client.py to session.py with constructor
injection. Transport is now passed once at construction time
instead of per-method, eliminating 5 redundant httpx.Client
creations per session lifecycle.

- New session.py: LibroFmSession with shared _client, transport
  injected at construction, auth headers set once after
  authenticate()
- Old client.py: deprecated re-export shim (LibroFmClient alias)
- All endpoint signatures slimmed to ≤3 params (removed
  transport= from authenticate/fetch_library/fetch_m4b_url/
  fetch_download_manifest/fetch_pdf_extra_url)
- Updated all source imports (cli.py, downloader.py) and test
  files (test_client, test_downloader, test_cli, test_progress)
- 17 new TDD tests in test_session.py

Closes #27
This commit is contained in:
AlexKucera committed 2026-06-04 15:27:11 +02:00
1 parent fb219be248
commit 006a7561ce
11 files changed
+986 -413

No files matched your search

+2 -2
View File
@@ -8,7 +8,7 @@ from pathlib import Path
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.session import LibroFmSession, AuthError
from librofm_downloader.history import DownloadHistory
from librofm_downloader.book import Book
from librofm_downloader.downloader import download_book
@@ -96,7 +96,7 @@ def run(
if verbose:
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
client = LibroFmClient(
client = LibroFmSession(
username=config.username,
password=config.password,
)
+26 -219
View File
@@ -1,225 +1,32 @@
"""HTTP client for Libro.fm API — auth, library fetch, and rate-limited downloads."""
"""Deprecated re-export shim — import from ``librofm_downloader.session`` instead."""
import threading
import warnings
import httpx
from .session import (
API_SEMAPHORE_CAPACITY,
AuthError,
LibroFmSession,
M4BUnavailableError,
)
# Maximum concurrent Libro.fm API calls (not CDN downloads).
# Configurable constant — not user-facing.
API_SEMAPHORE_CAPACITY = 3
warnings.warn(
"Import from 'librofm_downloader.session' instead of 'librofm_downloader.client'. "
"This shim will be removed in a future version.",
DeprecationWarning,
stacklevel=2,
)
# Backward-compatible alias
LibroFmClient = LibroFmSession
class AuthError(Exception):
"""Authentication failed (bad credentials, network error, etc.)."""
# Re-export DEFAULT_HEADERS for code that reads LibroFmClient.DEFAULT_HEADERS
DEFAULT_HEADERS = LibroFmSession.DEFAULT_HEADERS
class M4BUnavailableError(Exception):
"""M4B format is not available for this book (404 from API)."""
class LibroFmClient:
"""Libro.fm API client with OAuth2 password grant and library fetching."""
DEFAULT_HEADERS = {
"X-LibroFm-AppVer": "7.34.8",
"User-Agent": "okhttp/5.3.2",
}
def __init__(
self,
base_url: str = "https://libro.fm",
username: str = "",
password: str = "",
timeout: float = 30.0,
):
self._base_url = base_url.rstrip("/")
self._username = username
self._password = password
self._timeout = timeout
self._access_token: str | None = None
self._api_semaphore = threading.Semaphore(API_SEMAPHORE_CAPACITY)
def authenticate(self, transport: httpx.BaseTransport | None = None) -> str:
"""OAuth2 password grant → returns access_token.
Args:
transport: Optional httpx transport override for testing.
Returns:
The access token string.
Raises:
AuthError: If credentials are invalid or the request fails.
"""
client = httpx.Client(
base_url=self._base_url,
headers=self.DEFAULT_HEADERS,
timeout=self._timeout,
transport=transport,
)
try:
resp = client.post(
"/oauth/token",
data={
"grant_type": "password",
"username": self._username,
"password": self._password,
},
)
resp.raise_for_status()
token_data = resp.json()
self._access_token = token_data["access_token"]
return self._access_token
except httpx.HTTPStatusError as exc:
raise AuthError(f"Auth failed ({exc.response.status_code})") from exc
def fetch_library(self, transport: httpx.BaseTransport | None = None) -> list[dict]:
"""Fetch all books from the user's library, paginating automatically.
Args:
transport: Optional httpx transport override for testing.
Returns:
List of book dicts across all pages.
Raises:
AuthError: If not authenticated.
"""
if not self._access_token:
raise AuthError("Not authenticated. Call authenticate() first.")
headers = {**self.DEFAULT_HEADERS, "Authorization": f"Bearer {self._access_token}"}
all_books: list[dict] = []
client = httpx.Client(
base_url=self._base_url,
headers=headers,
timeout=self._timeout,
transport=transport,
)
next_url = "/api/v10/library"
while next_url:
resp = client.get(next_url)
resp.raise_for_status()
data = resp.json()
all_books.extend(data.get("audiobooks", []))
next_url = data.get("next_page") or None
return all_books
def fetch_m4b_url(self, isbn: str, transport: httpx.BaseTransport | None = None) -> str:
"""Fetch the M4B download URL for a given ISBN.
Args:
isbn: The ISBN of the audiobook.
transport: Optional httpx transport override for testing.
Returns:
The CDN URL string for the M4B file.
Raises:
AuthError: If not authenticated.
M4BUnavailableError: If the book has no M4B 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,
)
with self._api_semaphore:
resp = client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b")
if resp.status_code == 404:
raise M4BUnavailableError(f"M4B not available for ISBN {isbn}")
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,
)
with self._api_semaphore:
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()
def fetch_pdf_extra_url(
self,
isbn: str,
filename: str,
transport: httpx.BaseTransport | None = None,
) -> str:
"""Fetch the PDF extra download URL for a given ISBN and filename.
Args:
isbn: The ISBN of the audiobook.
filename: The name of the PDF file to fetch.
transport: Optional httpx transport override for testing.
Returns:
The CDN URL string for the PDF file.
Raises:
AuthError: If not authenticated.
"""
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,
)
with self._api_semaphore:
resp = client.get(f"/api/v10/library/{isbn}/pdf_extra_url", params={"filename": filename})
resp.raise_for_status()
data = resp.json()
return data["pdf_url"]
__all__ = [
"LibroFmSession",
"LibroFmClient",
"AuthError",
"M4BUnavailableError",
"API_SEMAPHORE_CAPACITY",
"DEFAULT_HEADERS",
]
+13 -13
View File
@@ -12,7 +12,7 @@ from pathlib import Path
import httpx
from librofm_downloader.book import Book
from librofm_downloader.client import M4BUnavailableError
from librofm_downloader.session import M4BUnavailableError
from librofm_downloader.history import HistoryEntry
from librofm_downloader.path import (
_resolve_output_dir,
@@ -215,7 +215,7 @@ def download_m4b(
def download_book(
book: Book,
client: "LibroFmClient",
client: "LibroFmSession",
output_base: Path | str,
history: "DownloadHistory",
format_strategy: str = "m4b_mp3_fallback",
@@ -228,7 +228,7 @@ def download_book(
Args:
book: The book metadata.
client: Authenticated LibroFmClient instance.
client: Authenticated LibroFmSession 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``.
@@ -247,7 +247,7 @@ def download_book(
if format_strategy == "m4b_mp3_fallback":
# Try M4B first
try:
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
m4b_url = client.fetch_m4b_url(book.isbn)
title_sanitized = sanitize(book.title)
m4b_path = output_dir / f"{title_sanitized}.m4b"
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event)
@@ -274,7 +274,7 @@ def download_book(
# --- m4b_only: skip book if M4B unavailable ---
if format_strategy == "m4b_only":
try:
m4b_url = client.fetch_m4b_url(book.isbn, transport=transport)
m4b_url = client.fetch_m4b_url(book.isbn)
title_sanitized = sanitize(book.title)
m4b_path = output_dir / f"{title_sanitized}.m4b"
result = download_m4b(m4b_url, m4b_path, transport=transport, progress=progress, cancel_event=cancel_event)
@@ -291,7 +291,7 @@ def download_book(
def _download_mp3(
book: Book,
client: "LibroFmClient",
client: "LibroFmSession",
output_dir: Path,
history: "DownloadHistory",
transport: httpx.BaseTransport | None = None,
@@ -300,7 +300,7 @@ def _download_mp3(
) -> Path | None:
"""Fetch MP3 manifest and download all ZIP parts."""
try:
manifest = client.fetch_download_manifest(book.isbn, transport=transport)
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
@@ -351,7 +351,7 @@ def _download_cover(
Returns Path on success, None on failure (logs warning).
"""
from librofm_downloader.client import LibroFmClient
from librofm_downloader.session import LibroFmSession
filename = _cover_filename_from_url(url)
@@ -368,7 +368,7 @@ def _download_cover(
client = httpx.Client(
transport=transport,
follow_redirects=True,
headers=LibroFmClient.DEFAULT_HEADERS,
headers=LibroFmSession.DEFAULT_HEADERS,
)
with client.stream("GET", url) as resp:
resp.raise_for_status()
@@ -423,7 +423,7 @@ def download_accompanying_files(
book: Book,
output_dir: Path | str,
config: "Config",
client: "LibroFmClient | None" = None,
client: "LibroFmSession | None" = None,
transport: httpx.BaseTransport | None = None,
progress: "Callable[[int], None] | None" = None,
) -> list[Path]:
@@ -435,13 +435,13 @@ def download_accompanying_files(
book: The book metadata.
output_dir: Directory where accompanying files are placed.
config: Config with download_extras / download_covers toggles.
client: Optional LibroFmClient for fetching PDF URLs.
client: Optional LibroFmSession for fetching PDF URLs.
transport: Optional httpx transport override for testing.
Returns:
List of Paths successfully downloaded.
"""
from librofm_downloader.client import LibroFmClient
from librofm_downloader.session import LibroFmSession
output_dir = Path(output_dir)
downloaded: list[Path] = []
@@ -455,7 +455,7 @@ def download_accompanying_files(
# Download PDF extras if enabled and available
if config.download_extras and book.pdf_extras and client is not None:
try:
pdf_url = client.fetch_pdf_extra_url(book.isbn, "map.pdf", transport=transport)
pdf_url = client.fetch_pdf_extra_url(book.isbn, "map.pdf")
if pdf_url:
result = _download_pdf(pdf_url, "map.pdf", output_dir, transport=transport)
if result:
+199
View File
@@ -0,0 +1,199 @@
"""HTTP session for Libro.fm API — auth, library fetch, and rate-limited downloads."""
from __future__ import annotations
import threading
import httpx
# Maximum concurrent Libro.fm API calls (not CDN downloads).
# Configurable constant — not user-facing.
API_SEMAPHORE_CAPACITY = 3
class AuthError(Exception):
"""Authentication failed (bad credentials, network error, etc.)."""
class M4BUnavailableError(Exception):
"""M4B format is not available for this book (404 from API)."""
class LibroFmSession:
"""Libro.fm API session with OAuth2 password grant and library fetching.
Constructs a single shared ``httpx.Client`` at instantiation time.
All endpoint methods reuse this client, so transport injection (for
testing) happens once via the ``transport`` keyword argument.
"""
DEFAULT_HEADERS = {
"X-LibroFm-AppVer": "7.34.8",
"User-Agent": "okhttp/5.3.2",
}
def __init__(
self,
base_url: str = "https://libro.fm",
username: str = "",
password: str = "",
timeout: float = 30.0,
*,
transport: httpx.BaseTransport | None = None,
):
self._base_url = base_url.rstrip("/")
self._username = username
self._password = password
self._timeout = timeout
self._access_token: str | None = None
self._api_semaphore = threading.Semaphore(API_SEMAPHORE_CAPACITY)
self._client = httpx.Client(
base_url=self._base_url,
headers=self.DEFAULT_HEADERS,
timeout=self._timeout,
transport=transport,
)
def authenticate(self) -> str:
"""OAuth2 password grant → returns access_token.
Uses the shared ``self._client`` (no transport parameter).
After successful auth, stores the Bearer token on the client
headers so all subsequent endpoint calls are authenticated.
Returns:
The access token string.
Raises:
AuthError: If credentials are invalid or the request fails.
"""
try:
resp = self._client.post(
"/oauth/token",
data={
"grant_type": "password",
"username": self._username,
"password": self._password,
},
)
resp.raise_for_status()
token_data = resp.json()
self._access_token = token_data["access_token"]
self._client.headers["Authorization"] = f"Bearer {self._access_token}"
return self._access_token
except httpx.HTTPStatusError as exc:
raise AuthError(f"Auth failed ({exc.response.status_code})") from exc
def fetch_library(self) -> list[dict]:
"""Fetch all books from the user's library, paginating automatically.
Uses the shared ``self._client`` (no transport parameter).
Returns:
List of book dicts across all pages.
Raises:
AuthError: If not authenticated.
"""
if not self._access_token:
raise AuthError("Not authenticated. Call authenticate() first.")
all_books: list[dict] = []
next_url = "/api/v10/library"
while next_url:
resp = self._client.get(next_url)
resp.raise_for_status()
data = resp.json()
all_books.extend(data.get("audiobooks", []))
next_url = data.get("next_page") or None
return all_books
def fetch_m4b_url(self, isbn: str) -> str:
"""Fetch the M4B download URL for a given ISBN.
Uses the shared ``self._client`` (no transport parameter).
Rate-limited by the API semaphore.
Args:
isbn: The ISBN of the audiobook.
Returns:
The CDN URL string for the M4B file.
Raises:
AuthError: If not authenticated.
M4BUnavailableError: If the book has no M4B format available (404).
"""
if not self._access_token:
raise AuthError("Not authenticated. Call authenticate() first.")
with self._api_semaphore:
resp = self._client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b")
if resp.status_code == 404:
raise M4BUnavailableError(f"M4B not available for ISBN {isbn}")
resp.raise_for_status()
data = resp.json()
return data["m4b_url"]
def fetch_download_manifest(self, isbn: str) -> dict:
"""Fetch the MP3 download manifest for a given ISBN.
Uses the shared ``self._client`` (no transport parameter).
Rate-limited by the API semaphore.
Args:
isbn: The ISBN of the audiobook.
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.")
with self._api_semaphore:
resp = self._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()
def fetch_pdf_extra_url(self, isbn: str, filename: str) -> str:
"""Fetch the PDF extra download URL for a given ISBN and filename.
Uses the shared ``self._client`` (no transport parameter).
Rate-limited by the API semaphore.
Args:
isbn: The ISBN of the audiobook.
filename: The name of the PDF file to fetch.
Returns:
The CDN URL string for the PDF file.
Raises:
AuthError: If not authenticated.
"""
if not self._access_token:
raise AuthError("Not authenticated. Call authenticate() first.")
with self._api_semaphore:
resp = self._client.get(
f"/api/v10/library/{isbn}/pdf_extra_url",
params={"filename": filename},
)
resp.raise_for_status()
data = resp.json()
return data["pdf_url"]