bookclerk_plugin_source_libro
Libro.fm content source: auth, library sync, and DRM-free download.
Uses the unofficial mobile API documented by community clients (see
client module). Audible ASIN enrichment (metadata confidence matching)
lives in bookclerk-enrich / CLI — this crate must not depend on
bookclerk-audible or bookclerk-enrich. Public explore catalog helpers
live in catalog (SDK HTTP, no enrich).
| Item | Kind | Summary |
|---|---|---|
LibroAuthFile |
struct | Credential envelope for one Libro.fm account. |
Audiobook |
struct | Audiobook. |
DownloadManifest |
struct | Download manifest. |
DownloadPart |
struct | Download part. |
LibraryPage |
struct | Library page. |
LibroClient |
struct | Authenticated Libro.fm HTTP helper. |
ManifestTrack |
struct | Manifest track. |
PackagedM4b |
struct | Packaged m4b. |
TokenResponse |
struct | Token response. |
LibroSource |
struct | Libro.fm catalog client used by the guest's discovery entrypoints. |
ManifestFormat |
enum | Android MediaFormat id for download-manifest?format=…. |
LibroContainer |
enum | Preferred Libro.fm download packaging. |
LibroError |
enum | Failures from Libro.fm OAuth, library listing, or DRM-free download. |
chapters_from_tracks |
function | Chapters from tracks. |
fetch_title_materials |
function | Fetch one ISBN into cache_dir, preferring M4B when available. |
audiobook_to_scan_book |
function | Map a Libro.fm audiobook JSON object to a structured scan row. |
collect_account_books |
function | Fetch all library pages for one client and collect books (no DB writes). |
fetch_account_page |
function | Fetch one Libro.fm library page as scan rows (no DB writes). |
Result |
type alias | Result alias for Libro.fm auth, sync, and download operations. |
APP_VER |
constant | Android app version header (X-LibroFm-AppVer). |
CLIENT_ID |
constant | Optional OAuth client_id. |
DEFAULT_BASE_URL |
constant | Default API origin. |
DOWNLOAD_MANIFEST_PATH |
constant | Download manifest (parts + chapter tracks). |
LIBRARY_PATH |
constant | Paginated library listing (/api/vN/library from the Android app prefix). |
OAUTH_TOKEN_PATH |
constant | OAuth password-grant path. |
PACKAGED_M4B_PATH |
constant | Packaged single-file M4B when Libro.fm offers it. |
USER_AGENT_VALUE |
constant | User-Agent matching the official Android HTTP stack. |
LIBRO_SOURCE_ID |
constant | Describe / config id for this store (libro). |
catalog::catalog_detailcatalog::expand_candidatesascatalog_expand_candidatescatalog::explore_search_pathcatalog::parse_detailsasparse_catalog_detailscatalog::parse_search_pageasparse_catalog_search_pagecatalog::purchase_hintascatalog_purchase_hintcatalog::search_catalogascatalog_searchcatalog::LibroDetailscatalog::CATALOG_USER_AGENTguest::guest_fetch_titleguest::guest_fetch_title_rpcguest::guest_loginguest::guest_login_rpcguest::guest_scan_pageguest::resolve_base_urlguest::resolve_container
catalog: Libro.fm catalog search, detail, related titles and purchase links.guest: Guest-process helpers for the external Libro.fm source plugin.
pub struct LibroAuthFile {
pub access_token: String,
pub token_type: String,
pub expires_at: Option<DateTime<Utc>>,
pub email: String,
pub user_id: Option<String>,
pub marketplace: String,
pub label: Option<String>,
}
Credential envelope for one Libro.fm account.
The guest returns it from login; the host seals it into encrypted_secrets
and passes it back on scan and fetch. Never written
to disk under Accounts/.
Fields
access_token: Bearer token from Libro.fm OAuth (access_token).token_type: OAuth token type (almost alwaysBearer).expires_at: Absolute expiry when known (RFC3339 when serialized).email: Sign-in email used as fallback account id.user_id: Libro.fm user id when the token response includes one.marketplace: Marketplace / locale hint (not part of the mobile API; stored for Bookclerk).label: Optional operator-facing account label in Accounts UI.
pub fn account_id(&self) -> &str
Stable account id for library rows: prefer user id, else email.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct Audiobook {
pub isbn: String,
pub title: String,
pub authors: Option<Vec<String>>,
pub cover_url: Option<String>,
pub subtitle: Option<String>,
pub publisher: Option<String>,
pub publication_date: Option<String>,
pub abridged: Option<bool>,
pub series: Option<String>,
pub series_num: Option<Value>,
pub genres: Option<Vec<Genre>>,
pub audiobook_info: Option<AudiobookInfo>,
pub user_metadata: Option<UserMetadata>,
pub id: Option<Value>,
}
Audiobook.
Fields
isbn: ISBN may arrive as string or number in JSON.title: Title.authors: Authors.cover_url: Cover URL.subtitle: Subtitle.publisher: Publisher.publication_date: Publication date.abridged: Abridged.series: Series.series_num: Series num.genres: Genres.audiobook_info: Audiobook info.user_metadata: User metadata.id: Identifier.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct DownloadManifest {
pub isbn: Option<String>,
pub parts: Vec<DownloadPart>,
pub tracks: Vec<ManifestTrack>,
pub expires_at: Option<String>,
pub size_bytes: Option<u64>,
}
Download manifest.
Fields
isbn: ISBN identifier.parts: Parts.tracks: Tracks.expires_at: Expires at.size_bytes: Size bytes.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct DownloadPart {
pub url: String,
pub size_bytes: Option<u64>,
}
Download part.
Fields
url: URL.size_bytes: Size bytes.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct LibraryPage {
pub page: u32,
pub total_pages: u32,
pub audiobooks: Vec<Audiobook>,
pub tags: Vec<String>,
pub error: Option<String>,
}
Library page.
Fields
page: Page.total_pages: Total pages.audiobooks: Audiobooks.tags: Tags.error: Error.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct LibroClient {
/* private fields */
}
Authenticated Libro.fm HTTP helper.
pub fn new(base_url: impl Into<String>) -> Self
Build a client pointed at base_url (no trailing slash).
pub fn with_http(self, http: HttpClient) -> Self
Override the HTTP client (tests / custom timeouts).
pub fn with_token(self, token: impl Into<String>) -> Self
Attach a bearer token for subsequent requests.
pub fn access_token(&self) -> Option<&str>
Current bearer token, if any.
pub fn base_url(&self) -> &str
Base URL in use.
pub async fn login(&mut self, email: &str, password: &str) -> Result<TokenResponse>
Password-grant login. Returns token metadata and stores the access token.
Returns an error when the operation fails.
pub async fn library_page(&self, page: u32) -> Result<LibraryPage>
Fetch one library page (page is 1-based).
Returns an error when the operation fails.
pub async fn download_manifest(
&self,
isbn: &str,
format: ManifestFormat,
) -> Result<DownloadManifest>
Download-manifest for parts + chapter tracks.
Pass ManifestFormat::M4b to request a single .m4b part (same asset as
Self::packaged_m4b) plus tracks in one response. ManifestFormat::Zip
(or omitting format) returns multi-part .zip URLs.
Returns an error when the operation fails.
pub async fn packaged_m4b(&self, isbn: &str) -> Result<Option<PackagedM4b>>
Packaged M4B metadata when available (None on 404 / missing URL).
Returns an error when the operation fails.
pub async fn download_to_file(&self, url: &str, dest: &Path) -> Result<u64>
Downloads a URL (CDN part or M4B) to dest, resuming dropped
transfers. Sends auth headers for libro.fm hosts.
The body streams to disk through the SDK's resumable download
(bookclerk_plugin_sdk::download), so a multi-gigabyte M4B is
never held in memory and a dropped connection asks only for the
missing bytes.
The file's length in bytes.
Returns LibroError::Download when the store refuses the file or
the transfer keeps failing, and LibroError::Api when the auth
headers cannot be built.
Implements: Clone, Debug, Default
pub struct ManifestTrack {
pub number: Option<u32>,
pub length_msec: Option<u64>,
pub length_sec: Option<u64>,
pub chapter_title: Option<String>,
}
Manifest track.
Fields
number: Number.length_msec: APKApiTrackuseslength_msec(Gson@SerializedName).length_sec: Legacy / fixture-only key; preferlength_msecwhen both are present.chapter_title: Chapter title.
pub fn duration_ms(&self) -> u64
Duration in milliseconds (APK wire format), falling back to length_sec.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct PackagedM4b {
pub m4b_url: String,
}
Packaged m4b.
Fields
m4b_url: M4b URL.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub created_at: Option<i64>,
pub expires_in: Option<i64>,
pub error: Option<String>,
}
Token response.
Fields
access_token: Access token.token_type: Token type.created_at: Unix seconds when the token was issued (mobile API).expires_in: Expires in.error: Error.
Implements: Clone, Debug, Deserialize<'de>, Serialize
pub struct LibroSource {
/* private fields */
}
Libro.fm catalog client used by the guest's discovery entrypoints.
Construct with LibroSource::new; use LibroSource::with_base_url
for wiremock / staging.
pub fn new() -> Self
Production Libro.fm API origin.
pub fn with_base_url(base_url: impl Into<String>) -> Self
Override API base (wiremock / staging).
pub fn from_config(config: &Value) -> Self
Catalog client for the instance settings document config.
Uses the document's base_url override when it has one, the same
origin crate::guest::resolve_base_url gives sign-in, scans and
fetches, so a staging or mock origin reaches every entrypoint.
pub async fn search_catalog(&self, opts: &CatalogSearchOpts) -> Result<Vec<CatalogHit>>
Searches the public catalog.
Returns an error when the storefront request or its parse fails.
pub async fn catalog_detail(&self, product_id: &str) -> Result<Option<CatalogHit>>
Loads one catalog title by product id (ISBN); None when it is unknown.
Returns an error when the storefront request or its parse fails.
pub async fn expand_candidates(
&self,
seed: &ExpandSeed,
limit: usize,
) -> Result<Vec<CatalogHit>>
Finds up to limit titles related to seed (same author, series, …).
Returns an error when the storefront request or its parse fails.
pub async fn purchase_hint(
&self,
opts: &PurchaseHintOpts,
) -> Result<Option<SourcePurchaseHint>>
Resolves the storefront price and link for a title; None when not sold.
Currently never: a failed lookup is treated as no match, so Ok(None)
can also mean the store could not be reached.
pub async fn purchase_answer(&self, opts: &PurchaseHintOpts) -> Result<PricedAnswer>
Resolves the storefront price and link for a title, with every
for-sale listing a title search found (see
crate::catalog::purchase_answer).
Only when Libro.fm asks to slow down; other failed lookups are treated as no match, so an empty answer can also mean the store could not be reached.
Implements: Clone, Debug, Default
pub enum ManifestFormat {
M4b,
Zip,
}
Android MediaFormat id for download-manifest?format=….
ManifestFormat::M4b→format=m4b(must be lowercase;M4Bis ignored)ManifestFormat::Zip→ omitformat(APKMediaFormat.ZIPid is null)
Variants
M4b: Single-file M4B CDN URL inpartswhen the title supports it.Zip: Multi-part ZIP of MP3s (API default whenformatis omitted).
pub const fn query_value(self) -> Option<&'static str>
Wire value for the format query, if any.
Implements: Clone, Copy, Debug, Default, Eq, PartialEq
pub enum LibroContainer {
M4b,
Zip,
}
Preferred Libro.fm download packaging.
Variants
M4b: Single M4B when the store offers it (default).Zip: Multi-part ZIP of MP3s.
pub fn parse(raw: &str) -> Option<Self>
Parse.
Implements: Clone, Copy, Debug, Default, Deserialize<'de>, Eq, PartialEq, Serialize
pub enum LibroError {
Auth(String),
NoAccounts(String),
AccountNotFound(String),
Api(String),
Download(String),
Io(Error),
Other(Error),
}
Failures from Libro.fm OAuth, library listing, or DRM-free download.
Variants
Auth: Password/token login or refresh failed.NoAccounts: No Libro.fm accounts are configured (safe to skip in multi-source scan).AccountNotFound: Requested account id is not present inencrypted_secrets.Api: Upstream mobile API or JSON payload error.Download: Title download or packaging into the preferred container failed.Io: Local filesystem I/O while reading or writing cache files.Other: Unexpected failure wrapped fromanyhow.
pub fn auth(msg: impl Into<String>) -> Self
Builds an Self::Auth error from a displayable message.
pub fn no_accounts(msg: impl Into<String>) -> Self
Builds a Self::NoAccounts error (multi-source scan may skip this store).
pub fn api(msg: impl Into<String>) -> Self
Builds an Self::Api error from a displayable message.
pub fn download(msg: impl Into<String>) -> Self
Builds a Self::Download error from a displayable message.
Implements: Debug, Display, Error, From<Error>, From<LibroError>
pub fn chapters_from_tracks(tracks: &[ManifestTrack]) -> Vec<(String, u64)>
Chapters from tracks.
pub async fn fetch_title_materials(
client: &LibroClient,
isbn: &str,
cache_dir: &Path,
) -> Result<PlainFetch>
Fetch one ISBN into cache_dir, preferring M4B when available.
Returns an error when the operation fails.
pub fn audiobook_to_scan_book(
book: &Audiobook,
account_id: &str,
marketplace: &str,
) -> ScanBook
Map a Libro.fm audiobook JSON object to a structured scan row.
pub async fn collect_account_books(
client: &LibroClient,
account_id: &str,
marketplace: &str,
) -> Result<(Vec<ScanBook>, u32)>
Fetch all library pages for one client and collect books (no DB writes).
Returns an error when the operation fails.
pub async fn fetch_account_page(
client: &LibroClient,
account_id: &str,
marketplace: &str,
page: u32,
) -> Result<(Vec<ScanBook>, Option<u32>)>
Fetch one Libro.fm library page as scan rows (no DB writes).
client- Authenticated Libro.fm client.account_id- Account the rows belong to.marketplace- Marketplace stamped on every row.page- 1-based library page.
The page's visible titles and the next page number, None on the last
page.
Returns an error when the request fails or the API reports one.
pub type Result<T> = Result<T, LibroError>;
Result alias for Libro.fm auth, sync, and download operations.
pub const APP_VER: &str = "7.37.4";
Android app version header (X-LibroFm-AppVer).
Keep in sync via scripts/librofm-apk-probe/ / workflow librofm-apk-probe.yml.
pub const CLIENT_ID: &str = "";
Optional OAuth client_id.
TODO: Historical / reverse-engineered clients sometimes sent a mobile
client_id with form-encoded password grants. Current community tools
(libro-client, librofm-downloader, bfordham/librofm) omit it and POST JSON.
Set a non-empty value here if Libro.fm starts requiring it again.
pub const DEFAULT_BASE_URL: &str = "https://libro.fm";
Default API origin.
TODO: Confirm if regional mirrors exist; community tools all use this host.
pub const DOWNLOAD_MANIFEST_PATH: &str = "/api/v12/download-manifest";
Download manifest (parts + chapter tracks).
Android DownloadApi.getDownloadManifest sends isbn, client_version, and
optional format (MediaFormat.M4B → "m4b"; ZIP → omit / null).
pub const LIBRARY_PATH: &str = "/api/v12/library";
Paginated library listing (/api/vN/library from the Android app prefix).
pub const OAUTH_TOKEN_PATH: &str = "/oauth/token";
OAuth password-grant path.
pub const PACKAGED_M4B_PATH: &str = "/api/v12/audiobooks/{isbn}/packaged_m4b";
Packaged single-file M4B when Libro.fm offers it.
pub const USER_AGENT_VALUE: &str = "okhttp/4.12.0";
User-Agent matching the official Android HTTP stack.
pub const LIBRO_SOURCE_ID: &str = "libro";
Describe / config id for this store (libro).
Generated from crates/bookclerk-plugins/optional/source-libro at main · View as Markdown