Something went wrong. Try again.
A self-hosted custom sync server for kobo devices.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470//! Typed wrappers over the kobo-shelf JSON API.//!//! Every call targets a same-origin `/api/...` route the axum server already//! exposes; the SPA is authenticated by the browser session cookie, so no//! credentials are threaded through here. A `401` surfaces as//! [`ApiError::Unauthorized`] so callers can bounce to the login route.
use serde::{Deserialize, Serialize};use wasm_bindgen::JsValue;use web_sys::FormData;
/// A book in the catalog, as returned by `GET /api/books`.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct Book { pub id: i64, pub uuid: String, pub title: String, pub authors: Vec<String>, /// Series name, if any (editable). #[serde(default)] pub series: Option<String>, /// Position within the series (editable). #[serde(default)] pub series_index: Option<f64>, /// Book description / blurb (editable). #[serde(default)] pub description: Option<String>, pub has_cover: bool, /// `"calibre"` or `"upload"` — only uploads get a delete control. pub source: String, /// Whether this book syncs to the user's devices (per-book toggle state). pub sync_enabled: bool, /// RFC 3339 catalog-entry time; uniform format, sortable as a string. pub timestamp: String, /// Override-cover version (0 = none). Used as `/covers/{id}?v=` to bust the /// browser cache after the cover changes. pub cover_version: i64, /// Whether the book is soft-deleted (shown only in the "Deleted" view). #[serde(default)] pub deleted: bool, /// Whether the current user uploaded this book. #[serde(default)] pub owned: bool, /// Username of the uploader; `None` for the server (Calibre) library. #[serde(default)] pub owner: Option<String>, /// Whether the book is visible to every user (always true for the server /// library; an owner's choice for uploads). #[serde(default)] pub shared: bool, /// Whether the current user may edit, share, or delete this book. #[serde(default)] pub editable: bool,}
/// A candidate cover from `GET /api/books/{id}/cover/search`.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct CoverCandidate { pub thumb_url: String, pub full_url: String, pub source: String, #[serde(default)] pub title: Option<String>,}
/// Global server settings (`GET`/`PUT /api/settings`).#[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq)]pub struct Settings { /// Redirect unimplemented Kobo store endpoints to the real store. pub proxy_unimplemented: bool, /// Newly uploaded books sync to devices by default. pub sync_new_uploads: bool,}
/// A Kobo auth token, as returned by `GET`/`POST /api/tokens`.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct Token { pub id: i64, pub token: String, /// Token-free base to configure as the device `api_endpoint`. pub api_endpoint: String, /// Serial of a device bound to this token, if any. #[serde(default)] pub device_serial: Option<String>,}
/// Outcome of a token deletion request.#[derive(Debug, Clone, PartialEq)]pub enum DeleteOutcome { /// The token was deleted. Deleted, /// The token is bound to the named device; deletion needs `force`. DeviceBound(String),}
/// The current user, as returned by `GET /api/me`.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct User { pub username: String, /// Server administrator: sees every book, edits settings, manages users. #[serde(default)] pub is_admin: bool,}
/// An account as listed to admins by `GET /api/users`.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct AdminUser { pub id: i64, pub username: String, pub is_admin: bool, /// Where the account authenticates: `"local"`, `"oidc"`, or `"ldap"`. #[serde(default)] pub source: String,}
/// Public login-method flags from `GET /api/auth_config`.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct AuthConfig { pub oidc_enabled: bool, /// Show the username/password form (local accounts and/or LDAP). pub local_login: bool, /// The password form is backed by an LDAP directory. #[serde(default)] pub ldap_enabled: bool, pub registration_enabled: bool,}
/// Result of an uploaded-book request (`POST /api/upload`).#[derive(Debug, Clone, Deserialize)]pub struct UploadedBook { pub title: String,}
/// A failed API call: either an unauthenticated response or any other error.#[derive(Debug, Clone, PartialEq)]pub enum ApiError { /// The server returned `401` — the caller should redirect to `/login`. Unauthorized, /// Any other failure, with a human-readable message. Other(String),}
impl std::fmt::Display for ApiError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ApiError::Unauthorized => f.write_str("Not logged in"), ApiError::Other(msg) => f.write_str(msg), } }}
/// Shorthand result type for API calls.pub type ApiResult<T> = Result<T, ApiError>;
impl From<gloo_net::Error> for ApiError { fn from(e: gloo_net::Error) -> Self { ApiError::Other(e.to_string()) }}
/// Map a non-success status to an [`ApiError`], reading the body for context.async fn check(resp: gloo_net::http::Response) -> ApiResult<gloo_net::http::Response> { if resp.ok() { return Ok(resp); } if resp.status() == 401 { return Err(ApiError::Unauthorized); } let body = resp.text().await.unwrap_or_default(); let msg = if body.is_empty() { format!("HTTP {}", resp.status()) } else { body }; Err(ApiError::Other(msg))}
/// `GET /api/auth_config` — which login methods to render.pub async fn auth_config() -> ApiResult<AuthConfig> { let resp = gloo_net::http::Request::get("/api/auth_config") .send() .await?; Ok(check(resp).await?.json().await?)}
/// `GET /api/me` — the current user, or `None` when unauthenticated.pub async fn me() -> ApiResult<Option<User>> { let resp = gloo_net::http::Request::get("/api/me").send().await?; match resp.status() { 401 => Ok(None), _ => Ok(Some(check(resp).await?.json().await?)), }}
/// `GET /api/books` — the full catalog.pub async fn books() -> ApiResult<Vec<Book>> { let resp = gloo_net::http::Request::get("/api/books").send().await?; Ok(check(resp).await?.json().await?)}
/// `GET /api/settings` — the global server settings.pub async fn settings() -> ApiResult<Settings> { let resp = gloo_net::http::Request::get("/api/settings").send().await?; Ok(check(resp).await?.json().await?)}
/// `PUT /api/settings` — persist the global server settings.pub async fn update_settings(s: Settings) -> ApiResult<()> { let resp = gloo_net::http::Request::put("/api/settings") .json(&s)? .send() .await?; check(resp).await.map(|_| ())}
/// `PUT /api/books/{id}/sync` — set this user's per-book sync flag.pub async fn set_book_sync(id: i64, enabled: bool) -> ApiResult<()> { let resp = gloo_net::http::Request::put(&format!("/api/books/{id}/sync")) .json(&serde_json::json!({ "enabled": enabled }))? .send() .await?; check(resp).await.map(|_| ())}
/// `PUT /api/books/{id}/share` — open an upload to every user, or make it/// private again.pub async fn set_book_shared(id: i64, shared: bool) -> ApiResult<()> { let resp = gloo_net::http::Request::put(&format!("/api/books/{id}/share")) .json(&serde_json::json!({ "shared": shared }))? .send() .await?; check(resp).await.map(|_| ())}
/// `GET /api/users` — every account (admin only).pub async fn users() -> ApiResult<Vec<AdminUser>> { let resp = gloo_net::http::Request::get("/api/users").send().await?; Ok(check(resp).await?.json().await?)}
/// `POST /api/users` — create a local account (admin only).pub async fn create_user(username: &str, password: &str, is_admin: bool) -> ApiResult<AdminUser> { let resp = gloo_net::http::Request::post("/api/users") .json(&serde_json::json!({ "username": username, "password": password, "is_admin": is_admin, }))? .send() .await?; Ok(check(resp).await?.json().await?)}
/// `PUT /api/users/{id}/admin` — grant or revoke the admin role (admin only).pub async fn set_user_admin(id: i64, is_admin: bool) -> ApiResult<()> { let resp = gloo_net::http::Request::put(&format!("/api/users/{id}/admin")) .json(&serde_json::json!({ "is_admin": is_admin }))? .send() .await?; check(resp).await.map(|_| ())}
/// `DELETE /api/users/{id}` — delete an account and everything it owns/// (admin only).pub async fn delete_user(id: i64) -> ApiResult<()> { let resp = gloo_net::http::Request::delete(&format!("/api/users/{id}")) .send() .await?; check(resp).await.map(|_| ())}
/// A candidate book record from `GET /api/books/{id}/meta/search`, applied to/// the edit form when picked.#[derive(Debug, Clone, Deserialize, PartialEq)]pub struct MetaCandidate { #[serde(default)] pub title: Option<String>, #[serde(default)] pub authors: Vec<String>, #[serde(default)] pub description: Option<String>, #[serde(default)] pub year: Option<i32>, #[serde(default)] pub cover_thumb_url: Option<String>, #[serde(default)] pub cover_full_url: Option<String>, pub source: String,}
/// `GET /api/books/{id}/meta/search?q=…` — candidate records for a book.pub async fn search_metadata(id: i64, query: &str) -> ApiResult<Vec<MetaCandidate>> { let encoded = String::from(js_sys::encode_uri_component(query)); let url = format!("/api/books/{id}/meta/search?q={encoded}"); let resp = gloo_net::http::Request::get(&url).send().await?; Ok(check(resp).await?.json().await?)}
/// Editable book metadata sent to `PUT /api/books/{id}/meta`. Blank fields/// clear the corresponding override on the server.#[derive(Debug, Clone, Serialize)]pub struct BookMeta { pub title: Option<String>, pub authors: Option<Vec<String>>, pub series: Option<String>, pub series_index: Option<f64>, pub description: Option<String>,}
/// `PUT /api/books/{id}/meta` — update a book's title/authors/series/description.pub async fn set_book_meta(id: i64, meta: &BookMeta) -> ApiResult<()> { let resp = gloo_net::http::Request::put(&format!("/api/books/{id}/meta")) .json(meta)? .send() .await?; check(resp).await.map(|_| ())}
/// `GET /api/books/{id}/cover/search?q=…` — candidate covers for a book.pub async fn search_covers(id: i64, query: &str) -> ApiResult<Vec<CoverCandidate>> { let encoded = String::from(js_sys::encode_uri_component(query)); let url = format!("/api/books/{id}/cover/search?q={encoded}"); let resp = gloo_net::http::Request::get(&url).send().await?; Ok(check(resp).await?.json().await?)}
/// `PUT /api/books/{id}/cover` — set the cover from a chosen candidate URL.pub async fn set_cover_url(id: i64, url: &str) -> ApiResult<()> { let resp = gloo_net::http::Request::put(&format!("/api/books/{id}/cover")) .json(&serde_json::json!({ "url": url }))? .send() .await?; check(resp).await.map(|_| ())}
/// `POST /api/books/{id}/cover` — set the cover from an uploaded image file.pub async fn upload_cover(id: i64, form: FormData) -> ApiResult<()> { let resp = gloo_net::http::Request::post(&format!("/api/books/{id}/cover")) .body(JsValue::from(form))? .send() .await?; check(resp).await.map(|_| ())}
/// `DELETE /api/books/{id}/cover` — drop the custom cover, reverting to the/// book's original Calibre/upload cover.pub async fn reset_cover(id: i64) -> ApiResult<()> { let resp = gloo_net::http::Request::delete(&format!("/api/books/{id}/cover")) .send() .await?; check(resp).await.map(|_| ())}
/// `GET /api/tokens` — the user's Kobo auth tokens.pub async fn tokens() -> ApiResult<Vec<Token>> { let resp = gloo_net::http::Request::get("/api/tokens").send().await?; Ok(check(resp).await?.json().await?)}
/// `POST /api/tokens` — mint a new Kobo auth token.pub async fn create_token() -> ApiResult<Token> { let resp = gloo_net::http::Request::post("/api/tokens").send().await?; Ok(check(resp).await?.json().await?)}
/// `DELETE /api/tokens/{id}` — revoke a token.////// Without `force`, a token bound to a device yields `409` and the bound serial/// ([`DeleteOutcome::DeviceBound`]) instead of being deleted, so the caller can/// confirm before breaking a device's sync.pub async fn delete_token(id: i64, force: bool) -> ApiResult<DeleteOutcome> { let url = if force { format!("/api/tokens/{id}?force=true") } else { format!("/api/tokens/{id}") }; let resp = gloo_net::http::Request::delete(&url).send().await?; match resp.status() { 401 => Err(ApiError::Unauthorized), 409 => { #[derive(Deserialize)] struct Bound { device_serial: String, } let bound: Bound = resp.json().await?; Ok(DeleteOutcome::DeviceBound(bound.device_serial)) } _ => check(resp).await.map(|_| DeleteOutcome::Deleted), }}
/// `POST /api/register-device` — arm a token so the next `device_auth` binds to it.pub async fn register_device(token: &str) -> ApiResult<()> { let resp = gloo_net::http::Request::post("/api/register-device") .header("Content-Type", "application/json") .body(format!( "{{\"token\":{}}}", serde_json::to_string(token).unwrap_or_default() ))? .send() .await?; check(resp).await.map(|_| ())}
/// `DELETE /api/books/{id}` — soft-delete a book (hidden + dropped from sync,/// row and files kept, restorable).pub async fn delete_book(id: i64) -> ApiResult<()> { let resp = gloo_net::http::Request::delete(&format!("/api/books/{id}")) .send() .await?; check(resp).await.map(|_| ())}
/// `POST /api/books/{id}/restore` — undo a soft delete.pub async fn restore_book(id: i64) -> ApiResult<()> { let resp = gloo_net::http::Request::post(&format!("/api/books/{id}/restore")) .send() .await?; check(resp).await.map(|_| ())}
/// `POST /api/upload` — upload an EPUB via multipart form data.pub async fn upload(form: FormData) -> ApiResult<UploadedBook> { let resp = gloo_net::http::Request::post("/api/upload") .body(JsValue::from(form))? .send() .await?; Ok(check(resp).await?.json().await?)}
/// Upload format tally from `GET /api/upload/formats`.#[derive(Debug, Clone, Deserialize)]pub struct FormatCounts { pub epub: i64, pub kepub: i64, pub kepubify_available: bool,}
/// `GET /api/upload/formats` — how many uploads are EPUB versus KEPUB.pub async fn upload_formats() -> ApiResult<FormatCounts> { let resp = gloo_net::http::Request::get("/api/upload/formats") .send() .await?; Ok(check(resp).await?.json().await?)}
/// Counts returned by `POST /api/upload/backfill-kepub`.#[derive(Debug, Clone, Deserialize)]pub struct BackfillResult { pub examined: usize, pub converted: usize, pub failed: usize,}
/// `POST /api/upload/backfill-kepub` — convert stored EPUB uploads to KEPUB.pub async fn backfill_kepub() -> ApiResult<BackfillResult> { let resp = gloo_net::http::Request::post("/api/upload/backfill-kepub") .send() .await?; Ok(check(resp).await?.json().await?)}
/// `DELETE /api/upload/{id}` — remove an uploaded book.pub async fn delete_upload(id: i64) -> ApiResult<()> { let resp = gloo_net::http::Request::delete(&format!("/api/upload/{id}")) .send() .await?; check(resp).await.map(|_| ())}