add OpenAPI/Swagger documentation with utoipa

This commit is contained in:
2026-03-05 21:46:29 +01:00
parent ef8a755a83
commit 40b7200bb3
11 changed files with 450 additions and 72 deletions

194
Cargo.lock generated
View File

@@ -87,8 +87,10 @@ dependencies = [
"tower",
"tracing",
"tracing-subscriber",
"utoipa",
"utoipa-swagger-ui",
"uuid",
"zip",
"zip 2.4.2",
]
[[package]]
@@ -120,7 +122,7 @@ checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -464,7 +466,7 @@ checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -487,7 +489,7 @@ checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -1275,6 +1277,16 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
[[package]]
name = "mime_guess"
version = "2.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e"
dependencies = [
"mime",
"unicase",
]
[[package]]
name = "minimal-lexical"
version = "0.2.1"
@@ -1435,7 +1447,7 @@ version = "0.1.0"
dependencies = [
"anyhow",
"lopdf",
"zip",
"zip 2.4.2",
]
[[package]]
@@ -1553,7 +1565,31 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn",
"syn 2.0.117",
]
[[package]]
name = "proc-macro-error"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
dependencies = [
"proc-macro-error-attr",
"proc-macro2",
"quote",
"syn 1.0.109",
"version_check",
]
[[package]]
name = "proc-macro-error-attr"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
dependencies = [
"proc-macro2",
"quote",
"version_check",
]
[[package]]
@@ -1756,6 +1792,18 @@ dependencies = [
"bitflags",
]
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
@@ -1845,6 +1893,40 @@ dependencies = [
"zeroize",
]
[[package]]
name = "rust-embed"
version = "8.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04113cb9355a377d83f06ef1f0a45b8ab8cd7d8b1288160717d66df5c7988d27"
dependencies = [
"rust-embed-impl",
"rust-embed-utils",
"walkdir",
]
[[package]]
name = "rust-embed-impl"
version = "8.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "da0902e4c7c8e997159ab384e6d0fc91c221375f6894346ae107f47dd0f3ccaa"
dependencies = [
"proc-macro2",
"quote",
"rust-embed-utils",
"syn 2.0.117",
"walkdir",
]
[[package]]
name = "rust-embed-utils"
version = "8.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5bcdef0be6fe7f6fa333b1073c949729274b05f123a0ad7efcb8efd878e5c3b1"
dependencies = [
"sha2",
"walkdir",
]
[[package]]
name = "rustc-hash"
version = "2.1.1"
@@ -1946,7 +2028,7 @@ checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2153,7 +2235,7 @@ dependencies = [
"quote",
"sqlx-core",
"sqlx-macros-core",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2176,7 +2258,7 @@ dependencies = [
"sqlx-mysql",
"sqlx-postgres",
"sqlx-sqlite",
"syn",
"syn 2.0.117",
"tokio",
"url",
]
@@ -2321,6 +2403,16 @@ version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "1.0.109"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
dependencies = [
"proc-macro2",
"unicode-ident",
]
[[package]]
name = "syn"
version = "2.0.117"
@@ -2349,7 +2441,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2369,7 +2461,7 @@ checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2461,7 +2553,7 @@ checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2565,7 +2657,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2619,6 +2711,12 @@ version = "1.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
[[package]]
name = "unicase"
version = "2.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
[[package]]
name = "unicode-bidi"
version = "0.3.18"
@@ -2676,6 +2774,46 @@ version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
[[package]]
name = "utoipa"
version = "4.2.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c5afb1a60e207dca502682537fefcfd9921e71d0b83e9576060f09abc6efab23"
dependencies = [
"indexmap",
"serde",
"serde_json",
"utoipa-gen",
]
[[package]]
name = "utoipa-gen"
version = "4.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "20c24e8ab68ff9ee746aad22d39b5535601e6416d1b0feeabf78be986a5c4392"
dependencies = [
"proc-macro-error",
"proc-macro2",
"quote",
"syn 2.0.117",
]
[[package]]
name = "utoipa-swagger-ui"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b39868d43c011961e04b41623e050aedf2cc93652562ff7935ce0f819aaf2da"
dependencies = [
"axum",
"mime_guess",
"regex",
"rust-embed",
"serde",
"serde_json",
"utoipa",
"zip 0.6.6",
]
[[package]]
name = "uuid"
version = "1.21.0"
@@ -2801,7 +2939,7 @@ dependencies = [
"bumpalo",
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
"wasm-bindgen-shared",
]
@@ -2932,7 +3070,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -2943,7 +3081,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -3222,7 +3360,7 @@ dependencies = [
"heck",
"indexmap",
"prettyplease",
"syn",
"syn 2.0.117",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
@@ -3238,7 +3376,7 @@ dependencies = [
"prettyplease",
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
"wit-bindgen-core",
"wit-bindgen-rust",
]
@@ -3305,7 +3443,7 @@ checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
"synstructure",
]
@@ -3326,7 +3464,7 @@ checksum = "f65c489a7071a749c849713807783f70672b28094011623e200cb86dcb835953"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
@@ -3346,7 +3484,7 @@ checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
"synstructure",
]
@@ -3386,7 +3524,19 @@ checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3"
dependencies = [
"proc-macro2",
"quote",
"syn",
"syn 2.0.117",
]
[[package]]
name = "zip"
version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"
dependencies = [
"byteorder",
"crc32fast",
"crossbeam-utils",
"flate2",
]
[[package]]

View File

@@ -33,3 +33,5 @@ tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter", "fmt"] }
uuid = { version = "1.12", features = ["serde", "v4"] }
walkdir = "2.5"
utoipa = "4.0"
utoipa-swagger-ui = "6.0"

View File

@@ -25,3 +25,5 @@ tracing.workspace = true
tracing-subscriber.workspace = true
uuid.workspace = true
zip = { version = "2.2", default-features = false, features = ["deflate"] }
utoipa.workspace = true
utoipa-swagger-ui = { workspace = true, features = ["axum"] }

View File

@@ -3,18 +3,22 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use uuid::Uuid;
use utoipa::ToSchema;
use crate::{error::ApiError, AppState};
#[derive(Deserialize)]
#[derive(Deserialize, ToSchema)]
pub struct ListBooksQuery {
#[schema(value_type = Option<String>)]
pub library_id: Option<Uuid>,
#[schema(value_type = Option<String>)]
pub kind: Option<String>,
pub cursor: Option<Uuid>,
#[schema(value_type = Option<i64>, example = 50)]
pub limit: Option<i64>,
}
#[derive(Serialize)]
#[derive(Serialize, ToSchema)]
pub struct BookItem {
pub id: Uuid,
pub library_id: Uuid,
@@ -28,13 +32,13 @@ pub struct BookItem {
pub updated_at: DateTime<Utc>,
}
#[derive(Serialize)]
#[derive(Serialize, ToSchema)]
pub struct BooksPage {
pub items: Vec<BookItem>,
pub next_cursor: Option<Uuid>,
}
#[derive(Serialize)]
#[derive(Serialize, ToSchema)]
pub struct BookDetails {
pub id: Uuid,
pub library_id: Uuid,
@@ -50,6 +54,20 @@ pub struct BookDetails {
pub file_parse_status: Option<String>,
}
#[utoipa::path(
get,
path = "/books",
tag = "books",
params(
("library_id" = Option<Uuid>, Query, description = "Filter by library ID"),
("kind" = Option<String>, Query, description = "Filter by book kind (cbz, cbr, pdf)"),
("cursor" = Option<Uuid>, Query, description = "Cursor for pagination"),
("limit" = Option<i64>, Query, description = "Max items to return (max 200)"),
),
responses(
(status = 200, body = BooksPage),
)
)]
pub async fn list_books(
State(state): State<AppState>,
Query(query): Query<ListBooksQuery>,
@@ -102,6 +120,15 @@ pub async fn list_books(
}))
}
#[utoipa::path(
get,
path = "/books/{id}",
tag = "books",
responses(
(status = 200, body = BookDetails),
(status = 404, description = "Book not found"),
)
)]
pub async fn get_book(
State(state): State<AppState>,
Path(id): Path<Uuid>,

View File

@@ -3,31 +3,51 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use uuid::Uuid;
use utoipa::ToSchema;
use crate::{error::ApiError, AppState};
#[derive(Deserialize)]
#[derive(Deserialize, ToSchema)]
pub struct RebuildRequest {
#[schema(value_type = Option<String>)]
pub library_id: Option<Uuid>,
}
#[derive(Serialize)]
pub struct IndexJobItem {
#[derive(Serialize, ToSchema)]
pub struct IndexJobResponse {
pub id: Uuid,
#[schema(value_type = Option<String>)]
pub library_id: Option<Uuid>,
pub r#type: String,
pub status: String,
#[schema(value_type = Option<String>)]
pub started_at: Option<DateTime<Utc>>,
#[schema(value_type = Option<String>)]
pub finished_at: Option<DateTime<Utc>>,
pub stats_json: Option<serde_json::Value>,
pub error_opt: Option<String>,
pub created_at: DateTime<Utc>,
}
#[derive(Serialize, ToSchema)]
pub struct FolderItem {
pub name: String,
pub path: String,
}
#[utoipa::path(
post,
path = "/index/rebuild",
tag = "admin",
request_body = Option<RebuildRequest>,
responses(
(status = 200, body = IndexJobResponse),
)
)]
pub async fn enqueue_rebuild(
State(state): State<AppState>,
payload: Option<Json<RebuildRequest>>,
) -> Result<Json<IndexJobItem>, ApiError> {
) -> Result<Json<IndexJobResponse>, ApiError> {
let library_id = payload.and_then(|p| p.0.library_id);
let id = Uuid::new_v4();
@@ -49,7 +69,15 @@ pub async fn enqueue_rebuild(
Ok(Json(map_row(row)))
}
pub async fn list_index_jobs(State(state): State<AppState>) -> Result<Json<Vec<IndexJobItem>>, ApiError> {
#[utoipa::path(
get,
path = "/index/status",
tag = "admin",
responses(
(status = 200, body = Vec<IndexJobResponse>),
)
)]
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 FROM index_jobs ORDER BY created_at DESC LIMIT 100",
)
@@ -59,10 +87,19 @@ pub async fn list_index_jobs(State(state): State<AppState>) -> Result<Json<Vec<I
Ok(Json(rows.into_iter().map(map_row).collect()))
}
#[utoipa::path(
post,
path = "/index/cancel/{id}",
tag = "admin",
responses(
(status = 200, body = IndexJobResponse),
(status = 404, description = "Job not found or already finished"),
)
)]
pub async fn cancel_job(
State(state): State<AppState>,
id: axum::extract::Path<Uuid>,
) -> Result<Json<IndexJobItem>, ApiError> {
) -> Result<Json<IndexJobResponse>, ApiError> {
let rows_affected = sqlx::query(
"UPDATE index_jobs SET status = 'cancelled' WHERE id = $1 AND status IN ('pending', 'running')",
)
@@ -84,12 +121,14 @@ pub async fn cancel_job(
Ok(Json(map_row(row)))
}
#[derive(Serialize)]
pub struct FolderItem {
pub name: String,
pub path: String,
}
#[utoipa::path(
get,
path = "/folders",
tag = "admin",
responses(
(status = 200, body = Vec<FolderItem>),
)
)]
pub async fn list_folders(State(_state): State<AppState>) -> Result<Json<Vec<FolderItem>>, ApiError> {
let libraries_path = std::path::Path::new("/libraries");
let mut folders = Vec::new();
@@ -110,8 +149,8 @@ pub async fn list_folders(State(_state): State<AppState>) -> Result<Json<Vec<Fol
Ok(Json(folders))
}
fn map_row(row: sqlx::postgres::PgRow) -> IndexJobItem {
IndexJobItem {
fn map_row(row: sqlx::postgres::PgRow) -> IndexJobResponse {
IndexJobResponse {
id: row.get("id"),
library_id: row.get("library_id"),
r#type: row.get("type"),

View File

@@ -4,11 +4,12 @@ use axum::{extract::{Path as AxumPath, State}, Json};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use uuid::Uuid;
use utoipa::ToSchema;
use crate::{error::ApiError, AppState};
#[derive(Serialize)]
pub struct LibraryDto {
#[derive(Serialize, ToSchema)]
pub struct LibraryResponse {
pub id: Uuid,
pub name: String,
pub root_path: String,
@@ -16,13 +17,23 @@ pub struct LibraryDto {
pub book_count: i64,
}
#[derive(Deserialize)]
pub struct CreateLibraryInput {
#[derive(Deserialize, ToSchema)]
pub struct CreateLibraryRequest {
#[schema(value_type = String, example = "Comics")]
pub name: String,
#[schema(value_type = String, example = "/data/comics")]
pub root_path: String,
}
pub async fn list_libraries(State(state): State<AppState>) -> Result<Json<Vec<LibraryDto>>, ApiError> {
#[utoipa::path(
get,
path = "/libraries",
tag = "admin",
responses(
(status = 200, body = Vec<LibraryResponse>),
)
)]
pub async fn list_libraries(State(state): State<AppState>) -> Result<Json<Vec<LibraryResponse>>, ApiError> {
let rows = sqlx::query(
"SELECT l.id, l.name, l.root_path, l.enabled,
(SELECT COUNT(*) FROM books b WHERE b.library_id = l.id) as book_count
@@ -33,7 +44,7 @@ pub async fn list_libraries(State(state): State<AppState>) -> Result<Json<Vec<Li
let items = rows
.into_iter()
.map(|row| LibraryDto {
.map(|row| LibraryResponse {
id: row.get("id"),
name: row.get("name"),
root_path: row.get("root_path"),
@@ -45,10 +56,20 @@ pub async fn list_libraries(State(state): State<AppState>) -> Result<Json<Vec<Li
Ok(Json(items))
}
#[utoipa::path(
post,
path = "/libraries",
tag = "admin",
request_body = CreateLibraryRequest,
responses(
(status = 200, body = LibraryResponse),
(status = 400, description = "Invalid input"),
)
)]
pub async fn create_library(
State(state): State<AppState>,
Json(input): Json<CreateLibraryInput>,
) -> Result<Json<LibraryDto>, ApiError> {
Json(input): Json<CreateLibraryRequest>,
) -> Result<Json<LibraryResponse>, ApiError> {
if input.name.trim().is_empty() {
return Err(ApiError::bad_request("name is required"));
}
@@ -66,7 +87,7 @@ pub async fn create_library(
.execute(&state.pool)
.await?;
Ok(Json(LibraryDto {
Ok(Json(LibraryResponse {
id,
name: input.name.trim().to_string(),
root_path,
@@ -75,6 +96,15 @@ pub async fn create_library(
}))
}
#[utoipa::path(
delete,
path = "/libraries/{id}",
tag = "admin",
responses(
(status = 200, description = "Library deleted"),
(status = 404, description = "Library not found"),
)
)]
pub async fn delete_library(
State(state): State<AppState>,
AxumPath(id): AxumPath<Uuid>,

View File

@@ -3,6 +3,7 @@ mod books;
mod error;
mod index_jobs;
mod libraries;
mod openapi;
mod pages;
mod search;
mod tokens;
@@ -22,6 +23,8 @@ use axum::{
routing::{delete, get},
Json, Router,
};
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
use lru::LruCache;
use stripstream_core::config::ApiConfig;
use sqlx::postgres::PgPoolOptions;
@@ -118,6 +121,8 @@ async fn main() -> anyhow::Result<()> {
.route("/health", get(health))
.route("/ready", get(ready))
.route("/metrics", get(metrics))
.route("/docs", get(docs_redirect))
.merge(SwaggerUi::new("/swagger-ui").url("/openapi.json", openapi::ApiDoc::openapi()))
.merge(admin_routes)
.merge(read_routes)
.layer(middleware::from_fn_with_state(state.clone(), request_counter))
@@ -133,6 +138,10 @@ async fn health() -> &'static str {
"ok"
}
async fn docs_redirect() -> impl axum::response::IntoResponse {
axum::response::Redirect::to("/swagger-ui/")
}
async fn ready(axum::extract::State(state): axum::extract::State<AppState>) -> Result<Json<serde_json::Value>, error::ApiError> {
sqlx::query("SELECT 1").execute(&state.pool).await?;
Ok(Json(serde_json::json!({"status": "ready"})))

45
apps/api/src/openapi.rs Normal file
View File

@@ -0,0 +1,45 @@
use utoipa::OpenApi;
#[derive(OpenApi)]
#[openapi(
paths(
crate::books::list_books,
crate::books::get_book,
crate::pages::get_page,
crate::search::search_books,
crate::index_jobs::enqueue_rebuild,
crate::index_jobs::list_index_jobs,
crate::index_jobs::cancel_job,
crate::index_jobs::list_folders,
crate::libraries::list_libraries,
crate::libraries::create_library,
crate::libraries::delete_library,
crate::tokens::list_tokens,
crate::tokens::create_token,
crate::tokens::revoke_token,
),
components(
schemas(
crate::books::ListBooksQuery,
crate::books::BookItem,
crate::books::BooksPage,
crate::books::BookDetails,
crate::pages::PageQuery,
crate::search::SearchQuery,
crate::search::SearchResponse,
crate::index_jobs::RebuildRequest,
crate::index_jobs::IndexJobResponse,
crate::index_jobs::FolderItem,
crate::libraries::LibraryResponse,
crate::libraries::CreateLibraryRequest,
crate::tokens::CreateTokenRequest,
crate::tokens::TokenResponse,
crate::tokens::CreatedTokenResponse,
)
),
tags(
(name = "books", description = "Books management endpoints"),
(name = "admin", description = "Admin management endpoints"),
)
)]
pub struct ApiDoc;

View File

@@ -13,16 +13,20 @@ use axum::{
};
use image::{codecs::jpeg::JpegEncoder, codecs::png::PngEncoder, codecs::webp::WebPEncoder, ColorType, ImageEncoder};
use serde::Deserialize;
use utoipa::ToSchema;
use sha2::{Digest, Sha256};
use sqlx::Row;
use uuid::Uuid;
use crate::{error::ApiError, AppState};
#[derive(Deserialize)]
#[derive(Deserialize, ToSchema)]
pub struct PageQuery {
#[schema(value_type = Option<String>, example = "webp")]
pub format: Option<String>,
#[schema(value_type = Option<u8>, example = 80)]
pub quality: Option<u8>,
#[schema(value_type = Option<u32>, example = 1200)]
pub width: Option<u32>,
}
@@ -60,6 +64,23 @@ impl OutputFormat {
}
}
#[utoipa::path(
get,
path = "/books/{book_id}/pages/{n}",
tag = "books",
params(
("book_id" = Uuid, description = "Book UUID"),
("n" = u32, description = "Page number (starts at 1)"),
("format" = Option<String>, Query, description = "Output format: webp, jpeg, png"),
("quality" = Option<u8>, Query, description = "JPEG quality 1-100"),
("width" = Option<u32>, Query, description = "Max width (max 2160)"),
),
responses(
(status = 200, description = "Page image", content_type = "image/webp"),
(status = 400, description = "Invalid parameters"),
(status = 404, description = "Book or page not found"),
)
)]
pub async fn get_page(
State(state): State<AppState>,
AxumPath((book_id, n)): AxumPath<(Uuid, u32)>,

View File

@@ -1,24 +1,45 @@
use axum::{extract::{Query, State}, Json};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{error::ApiError, AppState};
#[derive(Deserialize)]
#[derive(Deserialize, ToSchema)]
pub struct SearchQuery {
#[schema(value_type = String, example = "batman")]
pub q: String,
#[schema(value_type = Option<String>)]
pub library_id: Option<String>,
#[schema(value_type = Option<String>, example = "cbz")]
pub r#type: Option<String>,
#[schema(value_type = Option<String>, example = "cbz")]
pub kind: Option<String>,
#[schema(value_type = Option<usize>, example = 20)]
pub limit: Option<usize>,
}
#[derive(Serialize)]
#[derive(Serialize, ToSchema)]
pub struct SearchResponse {
pub hits: serde_json::Value,
pub estimated_total_hits: Option<u64>,
pub processing_time_ms: Option<u64>,
}
#[utoipa::path(
get,
path = "/search",
tag = "books",
params(
("q" = String, description = "Search query"),
("library_id" = Option<String>, Query, description = "Filter by library ID"),
("type" = Option<String>, Query, description = "Filter by type (cbz, cbr, pdf)"),
("kind" = Option<String>, Query, description = "Filter by kind (alias for type)"),
("limit" = Option<usize>, Query, description = "Max results (max 100)"),
),
responses(
(status = 200, body = SearchResponse),
)
)]
pub async fn search_books(
State(state): State<AppState>,
Query(query): Query<SearchQuery>,

View File

@@ -6,17 +6,33 @@ use rand::{rngs::OsRng, RngCore};
use serde::{Deserialize, Serialize};
use sqlx::Row;
use uuid::Uuid;
use utoipa::ToSchema;
use crate::{error::ApiError, AppState};
#[derive(Deserialize)]
pub struct CreateTokenInput {
#[derive(Deserialize, ToSchema)]
pub struct CreateTokenRequest {
#[schema(value_type = String, example = "My API Token")]
pub name: String,
#[schema(value_type = Option<String>, example = "read")]
pub scope: Option<String>,
}
#[derive(Serialize)]
pub struct CreatedToken {
#[derive(Serialize, ToSchema)]
pub struct TokenResponse {
pub id: Uuid,
pub name: String,
pub scope: String,
pub prefix: String,
#[schema(value_type = Option<String>)]
pub last_used_at: Option<DateTime<Utc>>,
#[schema(value_type = Option<String>)]
pub revoked_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
#[derive(Serialize, ToSchema)]
pub struct CreatedTokenResponse {
pub id: Uuid,
pub name: String,
pub scope: String,
@@ -24,21 +40,20 @@ pub struct CreatedToken {
pub prefix: String,
}
#[derive(Serialize)]
pub struct TokenItem {
pub id: Uuid,
pub name: String,
pub scope: String,
pub prefix: String,
pub last_used_at: Option<DateTime<Utc>>,
pub revoked_at: Option<DateTime<Utc>>,
pub created_at: DateTime<Utc>,
}
#[utoipa::path(
post,
path = "/admin/tokens",
tag = "admin",
request_body = CreateTokenRequest,
responses(
(status = 200, body = CreatedTokenResponse, description = "Token created - token is only shown once"),
(status = 400, description = "Invalid input"),
)
)]
pub async fn create_token(
State(state): State<AppState>,
Json(input): Json<CreateTokenInput>,
) -> Result<Json<CreatedToken>, ApiError> {
Json(input): Json<CreateTokenRequest>,
) -> Result<Json<CreatedTokenResponse>, ApiError> {
if input.name.trim().is_empty() {
return Err(ApiError::bad_request("name is required"));
}
@@ -73,7 +88,7 @@ pub async fn create_token(
.execute(&state.pool)
.await?;
Ok(Json(CreatedToken {
Ok(Json(CreatedTokenResponse {
id,
name: input.name.trim().to_string(),
scope: scope.to_string(),
@@ -82,7 +97,15 @@ pub async fn create_token(
}))
}
pub async fn list_tokens(State(state): State<AppState>) -> Result<Json<Vec<TokenItem>>, ApiError> {
#[utoipa::path(
get,
path = "/admin/tokens",
tag = "admin",
responses(
(status = 200, body = Vec<TokenResponse>),
)
)]
pub async fn list_tokens(State(state): State<AppState>) -> Result<Json<Vec<TokenResponse>>, ApiError> {
let rows = sqlx::query(
"SELECT id, name, scope, prefix, last_used_at, revoked_at, created_at FROM api_tokens ORDER BY created_at DESC",
)
@@ -91,7 +114,7 @@ pub async fn list_tokens(State(state): State<AppState>) -> Result<Json<Vec<Token
let items = rows
.into_iter()
.map(|row| TokenItem {
.map(|row| TokenResponse {
id: row.get("id"),
name: row.get("name"),
scope: row.get("scope"),
@@ -105,6 +128,15 @@ pub async fn list_tokens(State(state): State<AppState>) -> Result<Json<Vec<Token
Ok(Json(items))
}
#[utoipa::path(
delete,
path = "/admin/tokens/{id}",
tag = "admin",
responses(
(status = 200, description = "Token revoked"),
(status = 404, description = "Token not found"),
)
)]
pub async fn revoke_token(
State(state): State<AppState>,
Path(id): Path<Uuid>,