use std::path::PathBuf; use axum::extract::{Multipart, Path, State}; use axum::http::StatusCode; use axum::Json; use chrono::Utc; use serde::{Deserialize, Serialize}; use sha2::{Digest, Sha256}; use tracing::error; use uuid::Uuid; use crate::auth::ApiUser; use crate::db::book_store::{BookSource, NewBook, UploadFinalize}; use crate::kobo::auth::AppState; use crate::upload::enrich::Enriched; use crate::upload::epub::{parse_epub, EpubMeta}; use crate::upload::{convert, cover, enrich}; /// EPUB files are zip archives; every one starts with this local-file signature. const ZIP_MAGIC: &[u8; 4] = b"PK\x03\x04"; /// JSON returned by `POST /api/upload/backfill-kepub`. #[derive(Serialize)] pub struct BackfillResp { pub examined: usize, pub converted: usize, pub failed: usize, } /// JSON returned by `GET /api/upload/formats`. #[derive(Serialize)] pub struct FormatCounts { pub epub: i64, pub kepub: i64, pub kepubify_available: bool, } /// JSON returned after a successful upload. #[derive(Serialize)] pub struct UploadedJson { pub id: i64, pub uuid: String, pub title: String, } /// Body of `POST /api/upload/check` — the book UUIDs the client is about to /// upload (Calibre's per-book uuid, the same value embedded in each OPF). #[derive(Deserialize)] pub struct UploadCheckReq { pub uuids: Vec, } /// JSON returned by `POST /api/upload/check` — the subset of the requested /// UUIDs already present for this owner (i.e. the ones that would 409). #[derive(Serialize)] pub struct UploadCheckResp { pub known: Vec, } /// POST /api/upload/check — Report which of the given book UUIDs this owner has /// already uploaded, so the Calibre plugin can skip re-sending them. `/api/upload` /// must receive the whole file before it can 409 a duplicate, so a re-sync of an /// already-uploaded library wastes bandwidth on every book; this cheap pre-check /// avoids the transfer. UUIDs are matched case-insensitively, matching the /// normalization the EPUB parser applies to `source_uuid`. pub async fn api_upload_check( user: ApiUser, State(state): State, Json(req): Json, ) -> Result, (StatusCode, String)> { let owned = state .books .known_source_uuids(user.id) .await .map_err(internal)?; let known = req .uuids .into_iter() .filter(|u| owned.contains(u.trim().to_ascii_lowercase().as_str())) .collect(); Ok(Json(UploadCheckResp { known })) } /// GET /api/upload/formats — How many uploads are served as plain EPUB versus /// KEPUB, so the web UI can show what the KEPUB backfill has left to do. pub async fn api_upload_formats( _user: ApiUser, State(state): State, ) -> Result, (StatusCode, String)> { let (epub, kepub) = state.books.upload_format_counts().await.map_err(internal)?; Ok(Json(FormatCounts { epub, kepub, kepubify_available: state.config.kepubify_path.is_some(), })) } /// POST /api/upload/backfill-kepub — Convert every upload still stored as plain /// EPUB to KEPUB in place. Conversion normally runs once at upload time, so /// books that arrived before kepubify was configured keep reporting position as /// a bare percentage and reopen at page 1; `KoboSpan` locations exist only in /// KEPUB. Books already converted, or whose conversion fails, are left alone. /// Rewrites every user's uploads, so admin only. pub async fn api_backfill_kepub( user: ApiUser, State(state): State, ) -> Result, (StatusCode, String)> { user.require_admin() .map_err(|(status, msg)| (status, msg.to_string()))?; let Some(bin) = state.config.kepubify_path.clone() else { return Err(( StatusCode::CONFLICT, "kepubify is not configured".to_string(), )); }; let ids = state .books .unconverted_upload_ids() .await .map_err(internal)?; let mut converted = 0; let mut failed = 0; for id in &ids { match convert_in_place(&state, &bin, *id).await { Ok(true) => converted += 1, Ok(false) => failed += 1, Err(e) => { error!("KEPUB backfill failed for book {id}: {e:?}"); failed += 1; } } } Ok(Json(BackfillResp { examined: ids.len(), converted, failed, })) } /// Convert one stored EPUB to KEPUB and record the new format. `Ok(false)` when /// kepubify declines the file — the EPUB stays in place and keeps being served. async fn convert_in_place( state: &AppState, bin: &std::path::Path, id: i64, ) -> crate::errors::Result { let Some(epub_path) = state.books.book_file_path(id, "EPUB").await? else { return Ok(false); }; let Some(dir) = epub_path.parent() else { return Ok(false); }; let Some(kepub) = convert::kepubify(bin, &epub_path, dir).await? else { return Ok(false); }; let size = tokio::fs::metadata(&kepub) .await .map(|m| m.len() as i64) .unwrap_or(0); state.books.set_book_format(id, "KEPUB", size).await?; Ok(true) } /// POST /api/upload — Accept an EPUB upload, extract metadata + cover, and add /// it to the catalog. `multipart/form-data` with a single `file` field. pub async fn api_upload( user: ApiUser, State(state): State, mut multipart: Multipart, ) -> Result, (StatusCode, String)> { // Read the `file` part and an optional `book_uuid` text part. The Calibre // plugin sends `book_uuid` (its library uuid) so dedup keys off a value the // plugin also knows — the EPUB's own OPF identifier differs from it, so // parsing the file alone would give the plugin's pre-check nothing to match. let mut bytes: Option> = None; let mut filename = String::from("book.epub"); let mut declared_uuid: Option = None; while let Some(field) = multipart .next_field() .await .map_err(|e| (StatusCode::BAD_REQUEST, format!("Malformed upload: {e}")))? { let name = field.name().map(str::to_string); let is_file = name.as_deref() == Some("file") || field.file_name().is_some(); if is_file { if bytes.is_some() { continue; } if let Some(fname) = field.file_name() { filename = fname.to_string(); } let data = field.bytes().await.map_err(|e| { ( StatusCode::BAD_REQUEST, format!("Failed to read upload: {e}"), ) })?; bytes = Some(data.to_vec()); } else if name.as_deref() == Some("book_uuid") { let text = field.text().await.map_err(|e| { ( StatusCode::BAD_REQUEST, format!("Failed to read field: {e}"), ) })?; let normalized = text.trim().to_ascii_lowercase(); if !normalized.is_empty() { declared_uuid = Some(normalized); } } } let bytes = bytes.ok_or((StatusCode::BAD_REQUEST, "No file uploaded".to_string()))?; // Validate it is a zip (EPUB) by magic bytes, not extension. if bytes.len() < 4 || &bytes[0..4] != ZIP_MAGIC { return Err(( StatusCode::BAD_REQUEST, "Not an EPUB file (bad signature)".to_string(), )); } // Dedupe by content hash for this owner (fast path for byte-identical // re-sends). Reconcile the matched row's source_uuid to the plugin's // declared uuid so the pre-check can skip it next time. let hash = sha256_hex(&bytes); if let Some(existing) = state .books .find_by_hash(user.id, &hash) .await .map_err(internal)? { if let Some(decl) = declared_uuid.as_deref() { state .books .set_source_uuid(existing, decl) .await .map_err(internal)?; } return Err(( StatusCode::CONFLICT, format!("This book was already uploaded (id {existing})"), )); } // Parse the EPUB off the async runtime. let parse_bytes = bytes.clone(); let parsed = tokio::task::spawn_blocking(move || parse_epub(&parse_bytes)) .await .map_err(|e| { error!("EPUB parse task panicked: {e}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Failed to parse EPUB".to_string(), ) })? .map_err(|e| { error!("EPUB parse failed: {e:?}"); (StatusCode::BAD_REQUEST, format!("Invalid EPUB: {e}")) })?; // Stable-UUID dedup. Calibre re-exports the same book with different bytes // each send (re-zip, refreshed metadata), so the content hash above misses // re-uploads; a stable UUID does not. Match on the plugin's declared uuid or // the EPUB's own OPF uuid, so a book first stored under either identifier is // still recognized, and reconcile the matched row to the declared uuid (the // value the pre-check queries) so it skips next time. let opf_uuid = parsed.meta.book_uuid.clone(); for candidate in [declared_uuid.as_deref(), opf_uuid.as_deref()] .into_iter() .flatten() { if let Some(existing) = state .books .find_by_source_uuid(user.id, candidate) .await .map_err(internal)? { if let Some(decl) = declared_uuid.as_deref() { state .books .set_source_uuid(existing, decl) .await .map_err(internal)?; } return Err(( StatusCode::CONFLICT, format!("This book was already uploaded (id {existing})"), )); } } // Store the declared (canonical) uuid when present, else the OPF uuid. let source_uuid = declared_uuid.or(opf_uuid); // Persist the file under upload_dir/{uuid}/ before responding. The heavy, // multi-second work (online enrichment, cover transcode, kepubify) is // deferred to a background task so the upload request returns immediately — // the Calibre plugin blocks its GUI thread on this response, so a slow reply // freezes the app ("Application Not Responding"). let embedded_cover = parsed.cover; let meta = parsed.meta; let uuid = Uuid::new_v4().to_string(); let dir = state.config.upload_dir.join(&uuid); tokio::fs::create_dir_all(&dir).await.map_err(|e| { error!("Failed to create upload dir: {e}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Failed to store upload".to_string(), ) })?; tokio::fs::write(dir.join("book.epub"), &bytes) .await .map_err(|e| { error!("Failed to write book file: {e}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Failed to store upload".to_string(), ) })?; // Insert the catalog row with a freshly allocated upload id. The row starts // as an EPUB with no cover; the background task settles the final format, // size, cover, and any enriched metadata via `finalize_upload`. let id = state.books.next_upload_id().await.map_err(internal)?; // New uploads sync by default unless the server setting says otherwise. let default_sync = state .app_db .get_bool_setting("sync_new_uploads", true) .await .map_err(internal)?; let now = Utc::now(); let title = meta .title .clone() .filter(|t| !t.trim().is_empty()) .unwrap_or_else(|| strip_extension(&filename)); let book = NewBook { id, uuid: uuid.clone(), title: title.clone(), authors: meta.authors.clone(), publisher: meta.publisher.clone(), language: meta.language.clone(), description: meta.description.clone(), series_name: meta.series_name.clone(), series_index: meta.series_index, pubdate: meta.pubdate, file_format: "EPUB".to_string(), file_size: bytes.len() as i64, source: BookSource::Upload, locator: uuid.clone(), file_basename: "book".to_string(), content_hash: Some(hash), source_uuid, has_cover: false, owner_user_id: Some(user.id), default_sync, timestamp: now, last_modified: now, }; if let Err(e) = state.books.insert_book(&book).await { error!("Failed to insert uploaded book: {e:?}"); // Best-effort cleanup of the orphaned files. let _ = tokio::fs::remove_dir_all(&dir).await; return Err(( StatusCode::INTERNAL_SERVER_ERROR, "Failed to save book".to_string(), )); } // Fire-and-forget the slow enhancement so the response returns now. tokio::spawn(finalize_upload( state, id, dir, meta, title.clone(), embedded_cover, )); Ok(Json(UploadedJson { id, uuid, title })) } /// Background post-processing for a freshly stored upload: online enrichment, /// cover resolution + transcode, and optional kepubify conversion. Runs after /// the upload response has been sent; every step is best-effort, and the final /// state is written back with [`BookStore::finalize_upload`]. On any failure the /// book simply keeps its tentative EPUB/no-cover state (still fully usable). async fn finalize_upload( state: AppState, id: i64, dir: PathBuf, meta: EpubMeta, initial_title: String, embedded_cover: Option>, ) { // Enrich metadata online (best-effort, config-gated). Fills only gaps and // may supply a cover URL when the EPUB carried none. let Enriched { meta, cover_url } = enrich::enrich(state.config.enrichment, meta).await; // Resolve cover bytes: embedded first, else fetched from enrichment. let raw_cover = match embedded_cover { Some(c) => Some(c), None => match cover_url { Some(url) => enrich::fetch_cover(&url).await, None => None, }, }; // Always transcode to JPEG so the stored cover.jpg is a real JPEG. let cover_dir = dir.clone(); let has_cover = match raw_cover { Some(raw) => match tokio::task::spawn_blocking(move || cover::to_jpeg(&raw)).await { Ok(Some(jpeg)) => tokio::fs::write(cover_dir.join("cover.jpg"), &jpeg) .await .is_ok(), _ => false, }, None => false, }; // Convert to KEPUB for native per-page progress when kepubify is configured. // Soft dependency: on any failure we keep serving the EPUB. let epub_path = dir.join("book.epub"); let epub_size = tokio::fs::metadata(&epub_path) .await .map(|m| m.len() as i64) .unwrap_or(0); let (file_format, file_size) = match &state.config.kepubify_path { Some(bin) => match convert::kepubify(bin, &epub_path, &dir).await { Ok(Some(kepub)) => { let size = tokio::fs::metadata(&kepub) .await .map(|m| m.len() as i64) .unwrap_or(epub_size); ("KEPUB".to_string(), size) } Ok(None) => ("EPUB".to_string(), epub_size), Err(e) => { error!("kepubify errored: {e:?}"); ("EPUB".to_string(), epub_size) } }, None => ("EPUB".to_string(), epub_size), }; let title = meta .title .clone() .filter(|t| !t.trim().is_empty()) .unwrap_or(initial_title); let finalized = UploadFinalize { id, title, authors: meta.authors, publisher: meta.publisher, language: meta.language, description: meta.description, series_name: meta.series_name, series_index: meta.series_index, pubdate: meta.pubdate, file_format, file_size, has_cover, last_modified: Utc::now(), }; if let Err(e) = state.books.finalize_upload(&finalized).await { error!("Failed to finalize upload {id}: {e:?}"); } } /// DELETE /api/upload/{id} — Remove an uploaded book owned by the current user /// (admins may remove anyone's upload). pub async fn api_delete_upload( user: ApiUser, State(state): State, Path(id): Path, ) -> Result { let locator = state .books .delete_upload_owned(id, user.id) .await .map_err(internal)? .ok_or((StatusCode::NOT_FOUND, "Upload not found".to_string()))?; let dir = state.config.upload_dir.join(&locator); if let Err(e) = tokio::fs::remove_dir_all(&dir).await { error!("Failed to remove upload files for {id}: {e}"); } Ok(StatusCode::NO_CONTENT) } /// Lowercase hex SHA-256 of the given bytes. fn sha256_hex(bytes: &[u8]) -> String { let digest = Sha256::digest(bytes); digest.iter().map(|b| format!("{b:02x}")).collect() } /// Strip a trailing file extension from a filename for use as a fallback title. fn strip_extension(filename: &str) -> String { filename .rsplit_once('.') .map(|(stem, _)| stem) .unwrap_or(filename) .to_string() } /// Map an error-stack report to a 500 response. fn internal(e: E) -> (StatusCode, String) { error!("Upload error: {e:?}"); ( StatusCode::INTERNAL_SERVER_ERROR, "Internal server error".to_string(), ) }