bookclerk_plugin_source_libro

Development These docs follow the development version and change with every merge.

Last updated View as Markdown

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).

Re-exports

Modules

  • catalog: Libro.fm catalog search, detail, related titles and purchase links.
  • guest: Guest-process helpers for the external Libro.fm source plugin.

Structs

LibroAuthFile

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 always Bearer).
  • 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.

LibroAuthFile::account_id

pub fn account_id(&self) -> &str

Stable account id for library rows: prefer user id, else email.

Implements: Clone, Debug, Deserialize<'de>, Serialize

Audiobook

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

DownloadManifest

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

DownloadPart

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

LibraryPage

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

LibroClient

pub struct LibroClient {
    /* private fields */
}

Authenticated Libro.fm HTTP helper.

LibroClient::new

pub fn new(base_url: impl Into<String>) -> Self

Build a client pointed at base_url (no trailing slash).

LibroClient::with_http

pub fn with_http(self, http: HttpClient) -> Self

Override the HTTP client (tests / custom timeouts).

LibroClient::with_token

pub fn with_token(self, token: impl Into<String>) -> Self

Attach a bearer token for subsequent requests.

LibroClient::access_token

pub fn access_token(&self) -> Option<&str>

Current bearer token, if any.

LibroClient::base_url

pub fn base_url(&self) -> &str

Base URL in use.

LibroClient::login

pub async fn login(&mut self, email: &str, password: &str) -> Result<TokenResponse>

Password-grant login. Returns token metadata and stores the access token.

Errors

Returns an error when the operation fails.

LibroClient::library_page

pub async fn library_page(&self, page: u32) -> Result<LibraryPage>

Fetch one library page (page is 1-based).

Errors

Returns an error when the operation fails.

LibroClient::download_manifest

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.

Errors

Returns an error when the operation fails.

LibroClient::packaged_m4b

pub async fn packaged_m4b(&self, isbn: &str) -> Result<Option<PackagedM4b>>

Packaged M4B metadata when available (None on 404 / missing URL).

Errors

Returns an error when the operation fails.

LibroClient::download_to_file

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.

Returns

The file's length in bytes.

Errors

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

ManifestTrack

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: APK ApiTrack uses length_msec (Gson @SerializedName).
  • length_sec: Legacy / fixture-only key; prefer length_msec when both are present.
  • chapter_title: Chapter title.

ManifestTrack::duration_ms

pub fn duration_ms(&self) -> u64

Duration in milliseconds (APK wire format), falling back to length_sec.

Implements: Clone, Debug, Deserialize<'de>, Serialize

PackagedM4b

pub struct PackagedM4b {
    pub m4b_url: String,
}

Packaged m4b.

Fields

  • m4b_url: M4b URL.

Implements: Clone, Debug, Deserialize<'de>, Serialize

TokenResponse

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

LibroSource

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.

LibroSource::new

pub fn new() -> Self

Production Libro.fm API origin.

LibroSource::with_base_url

pub fn with_base_url(base_url: impl Into<String>) -> Self

Override API base (wiremock / staging).

LibroSource::from_config

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.

LibroSource::search_catalog

pub async fn search_catalog(&self, opts: &CatalogSearchOpts) -> Result<Vec<CatalogHit>>

Searches the public catalog.

Errors

Returns an error when the storefront request or its parse fails.

LibroSource::catalog_detail

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.

Errors

Returns an error when the storefront request or its parse fails.

LibroSource::expand_candidates

pub async fn expand_candidates(
    &self,
    seed: &ExpandSeed,
    limit: usize,
) -> Result<Vec<CatalogHit>>

Finds up to limit titles related to seed (same author, series, …).

Errors

Returns an error when the storefront request or its parse fails.

LibroSource::purchase_hint

pub async fn purchase_hint(
    &self,
    opts: &PurchaseHintOpts,
) -> Result<Option<SourcePurchaseHint>>

Resolves the storefront price and link for a title; None when not sold.

Errors

Currently never: a failed lookup is treated as no match, so Ok(None) can also mean the store could not be reached.

LibroSource::purchase_answer

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).

Errors

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

Enums

ManifestFormat

pub enum ManifestFormat {
    M4b,
    Zip,
}

Android MediaFormat id for download-manifest?format=….

Variants

  • M4b: Single-file M4B CDN URL in parts when the title supports it.
  • Zip: Multi-part ZIP of MP3s (API default when format is omitted).

ManifestFormat::query_value

pub const fn query_value(self) -> Option<&'static str>

Wire value for the format query, if any.

Implements: Clone, Copy, Debug, Default, Eq, PartialEq

LibroContainer

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.

LibroContainer::parse

pub fn parse(raw: &str) -> Option<Self>

Parse.

Implements: Clone, Copy, Debug, Default, Deserialize<'de>, Eq, PartialEq, Serialize

LibroError

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 in encrypted_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 from anyhow.

LibroError::auth

pub fn auth(msg: impl Into<String>) -> Self

Builds an Self::Auth error from a displayable message.

LibroError::no_accounts

pub fn no_accounts(msg: impl Into<String>) -> Self

Builds a Self::NoAccounts error (multi-source scan may skip this store).

LibroError::api

pub fn api(msg: impl Into<String>) -> Self

Builds an Self::Api error from a displayable message.

LibroError::download

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>

Functions

chapters_from_tracks

pub fn chapters_from_tracks(tracks: &[ManifestTrack]) -> Vec<(String, u64)>

Chapters from tracks.

fetch_title_materials

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.

Errors

Returns an error when the operation fails.

audiobook_to_scan_book

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.

collect_account_books

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).

Errors

Returns an error when the operation fails.

fetch_account_page

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).

Arguments

  • client - Authenticated Libro.fm client.
  • account_id - Account the rows belong to.
  • marketplace - Marketplace stamped on every row.
  • page - 1-based library page.

Returns

The page's visible titles and the next page number, None on the last page.

Errors

Returns an error when the request fails or the API reports one.

Type aliases

Result

pub type Result<T> = Result<T, LibroError>;

Result alias for Libro.fm auth, sync, and download operations.

Constants

APP_VER

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.

CLIENT_ID

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.

DEFAULT_BASE_URL

pub const DEFAULT_BASE_URL: &str = "https://libro.fm";

Default API origin.

TODO: Confirm if regional mirrors exist; community tools all use this host.

DOWNLOAD_MANIFEST_PATH

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).

LIBRARY_PATH

pub const LIBRARY_PATH: &str = "/api/v12/library";

Paginated library listing (/api/vN/library from the Android app prefix).

OAUTH_TOKEN_PATH

pub const OAUTH_TOKEN_PATH: &str = "/oauth/token";

OAuth password-grant path.

PACKAGED_M4B_PATH

pub const PACKAGED_M4B_PATH: &str = "/api/v12/audiobooks/{isbn}/packaged_m4b";

Packaged single-file M4B when Libro.fm offers it.

USER_AGENT_VALUE

pub const USER_AGENT_VALUE: &str = "okhttp/4.12.0";

User-Agent matching the official Android HTTP stack.

LIBRO_SOURCE_ID

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