feat: conversion CBR → CBZ via job asynchrone

Ajoute la possibilité de convertir un livre CBR en CBZ depuis le backoffice.
La conversion est sécurisée : le CBR original n'est supprimé qu'après vérification
du CBZ généré et mise à jour de la base de données.

- parsers: nouvelle fn `convert_cbr_to_cbz` (unar extract → zip pack → vérification → rename atomique)
- api: `POST /books/:id/convert` crée un job `cbr_to_cbz` (vérifie format CBR, détecte collision)
- indexer: nouveau `converter.rs` dispatché depuis `job.rs`
- backoffice: bouton "Convert to CBZ" sur la page détail (visible si CBR), label dans JobRow
- migrations: colonne `book_id` sur `index_jobs` + type `cbr_to_cbz` dans le check constraint

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-03-09 23:02:08 +01:00
parent e8bb014874
commit e0b80cae38
21 changed files with 821 additions and 16 deletions

View File

@@ -5,7 +5,7 @@ use sqlx::Row;
use uuid::Uuid;
use utoipa::ToSchema;
use crate::{error::ApiError, state::AppState};
use crate::{error::ApiError, index_jobs::IndexJobResponse, state::AppState};
#[derive(Deserialize, ToSchema)]
pub struct ListBooksQuery {
@@ -341,6 +341,113 @@ pub async fn list_series(
}))
}
fn remap_libraries_path(path: &str) -> String {
if let Ok(root) = std::env::var("LIBRARIES_ROOT_PATH") {
if path.starts_with("/libraries/") {
return path.replacen("/libraries", &root, 1);
}
}
path.to_string()
}
fn unmap_libraries_path(path: &str) -> String {
if let Ok(root) = std::env::var("LIBRARIES_ROOT_PATH") {
if path.starts_with(&root) {
return path.replacen(&root, "/libraries", 1);
}
}
path.to_string()
}
/// Enqueue a CBR → CBZ conversion job for a single book
#[utoipa::path(
post,
path = "/books/{id}/convert",
tag = "books",
params(
("id" = String, Path, description = "Book UUID"),
),
responses(
(status = 200, body = IndexJobResponse),
(status = 404, description = "Book not found"),
(status = 409, description = "Book is not CBR, or target CBZ already exists"),
(status = 401, description = "Unauthorized"),
(status = 403, description = "Forbidden - Admin scope required"),
),
security(("Bearer" = []))
)]
pub async fn convert_book(
State(state): State<AppState>,
Path(book_id): Path<Uuid>,
) -> Result<Json<IndexJobResponse>, ApiError> {
// Fetch book file info
let row = sqlx::query(
r#"
SELECT b.id, bf.abs_path, bf.format
FROM books b
LEFT JOIN LATERAL (
SELECT abs_path, format
FROM book_files
WHERE book_id = b.id
ORDER BY updated_at DESC
LIMIT 1
) bf ON TRUE
WHERE b.id = $1
"#,
)
.bind(book_id)
.fetch_optional(&state.pool)
.await?;
let row = row.ok_or_else(|| ApiError::not_found("book not found"))?;
let abs_path: Option<String> = row.get("abs_path");
let format: Option<String> = row.get("format");
if format.as_deref() != Some("cbr") {
return Err(ApiError {
status: axum::http::StatusCode::CONFLICT,
message: "book is not in CBR format".to_string(),
});
}
let abs_path = abs_path.ok_or_else(|| ApiError::not_found("book file path not found"))?;
// Check for existing CBZ with same stem
let physical_path = remap_libraries_path(&abs_path);
let cbr_path = std::path::Path::new(&physical_path);
if let (Some(parent), Some(stem)) = (cbr_path.parent(), cbr_path.file_stem()) {
let cbz_path = parent.join(format!("{}.cbz", stem.to_string_lossy()));
if cbz_path.exists() {
return Err(ApiError {
status: axum::http::StatusCode::CONFLICT,
message: format!(
"CBZ file already exists: {}",
unmap_libraries_path(&cbz_path.to_string_lossy())
),
});
}
}
// Create the conversion job
let job_id = Uuid::new_v4();
sqlx::query(
"INSERT INTO index_jobs (id, book_id, type, status) VALUES ($1, $2, 'cbr_to_cbz', 'pending')",
)
.bind(job_id)
.bind(book_id)
.execute(&state.pool)
.await?;
let job_row = sqlx::query(
"SELECT id, library_id, book_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files FROM index_jobs WHERE id = $1",
)
.bind(job_id)
.fetch_one(&state.pool)
.await?;
Ok(Json(crate::index_jobs::map_row(job_row)))
}
use axum::{
body::Body,
http::{header, HeaderMap, HeaderValue, StatusCode},

View File

@@ -24,6 +24,8 @@ pub struct IndexJobResponse {
pub id: Uuid,
#[schema(value_type = Option<String>)]
pub library_id: Option<Uuid>,
#[schema(value_type = Option<String>)]
pub book_id: Option<Uuid>,
pub r#type: String,
pub status: String,
#[schema(value_type = Option<String>)]
@@ -122,7 +124,7 @@ pub async fn enqueue_rebuild(
.await?;
let row = sqlx::query(
"SELECT id, library_id, type, status, started_at, finished_at, stats_json, error_opt, created_at FROM index_jobs WHERE id = $1",
"SELECT id, library_id, book_id, type, status, started_at, finished_at, stats_json, error_opt, created_at FROM index_jobs WHERE id = $1",
)
.bind(id)
.fetch_one(&state.pool)
@@ -145,7 +147,7 @@ pub async fn enqueue_rebuild(
)]
pub async fn list_index_jobs(State(state): State<AppState>) -> Result<Json<Vec<IndexJobResponse>>, ApiError> {
let rows = sqlx::query(
"SELECT id, library_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files FROM index_jobs ORDER BY created_at DESC LIMIT 100",
"SELECT id, library_id, book_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files FROM index_jobs ORDER BY created_at DESC LIMIT 100",
)
.fetch_all(&state.pool)
.await?;
@@ -185,7 +187,7 @@ pub async fn cancel_job(
}
let row = sqlx::query(
"SELECT id, library_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files FROM index_jobs WHERE id = $1",
"SELECT id, library_id, book_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files FROM index_jobs WHERE id = $1",
)
.bind(id.0)
.fetch_one(&state.pool)
@@ -294,6 +296,7 @@ pub fn map_row(row: sqlx::postgres::PgRow) -> IndexJobResponse {
IndexJobResponse {
id: row.get("id"),
library_id: row.get("library_id"),
book_id: row.try_get("book_id").ok().flatten(),
r#type: row.get("type"),
status: row.get("status"),
started_at: row.get("started_at"),
@@ -339,9 +342,9 @@ fn map_row_detail(row: sqlx::postgres::PgRow) -> IndexJobDetailResponse {
)]
pub async fn get_active_jobs(State(state): State<AppState>) -> Result<Json<Vec<IndexJobResponse>>, ApiError> {
let rows = sqlx::query(
"SELECT id, library_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files
FROM index_jobs
WHERE status IN ('pending', 'running', 'generating_thumbnails')
"SELECT id, library_id, book_id, type, status, started_at, finished_at, stats_json, error_opt, created_at, progress_percent, processed_files, total_files
FROM index_jobs
WHERE status IN ('pending', 'running', 'generating_thumbnails')
ORDER BY created_at ASC"
)
.fetch_all(&state.pool)

View File

@@ -69,6 +69,7 @@ async fn main() -> anyhow::Result<()> {
.route("/libraries/:id", delete(libraries::delete_library))
.route("/libraries/:id/scan", axum::routing::post(libraries::scan_library))
.route("/libraries/:id/monitoring", axum::routing::patch(libraries::update_monitoring))
.route("/books/:id/convert", axum::routing::post(books::convert_book))
.route("/index/rebuild", axum::routing::post(index_jobs::enqueue_rebuild))
.route("/index/thumbnails/rebuild", axum::routing::post(thumbnails::start_thumbnails_rebuild))
.route("/index/thumbnails/regenerate", axum::routing::post(thumbnails::start_thumbnails_regenerate))

View File

@@ -8,6 +8,7 @@ use utoipa::OpenApi;
crate::books::get_book,
crate::books::get_thumbnail,
crate::books::list_series,
crate::books::convert_book,
crate::pages::get_page,
crate::search::search_books,
crate::index_jobs::enqueue_rebuild,