754 lines
28 KiB
Rust
754 lines
28 KiB
Rust
use axum::extract::{Path, Query, State};
|
|
use axum::http::StatusCode;
|
|
use axum::response::{IntoResponse, Response};
|
|
use axum::Json;
|
|
use serde::{Deserialize, Serialize};
|
|
use utoipa::{IntoParams, ToSchema};
|
|
|
|
use crate::owners::Owner;
|
|
use crate::state::{AppState, MovieCommand};
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct Movie {
|
|
pub id: i64,
|
|
pub tmdb_id: i64,
|
|
pub title: String,
|
|
pub year: Option<i64>,
|
|
pub original_language: Option<String>,
|
|
pub root_id: i64,
|
|
pub wanted: bool,
|
|
pub overrides: serde_json::Value,
|
|
pub state: String,
|
|
pub blocked: bool,
|
|
pub search_attempts: i64,
|
|
pub last_searched_at: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize, ToSchema)]
|
|
pub struct CreateMovie {
|
|
pub tmdb_id: i64,
|
|
pub title: String,
|
|
pub year: Option<i64>,
|
|
pub original_language: Option<String>,
|
|
pub root_id: i64,
|
|
#[serde(default = "default_true")]
|
|
pub wanted: bool,
|
|
#[serde(default)]
|
|
pub blocked: bool,
|
|
#[serde(default = "empty_overrides")]
|
|
pub overrides: serde_json::Value,
|
|
}
|
|
|
|
#[derive(Debug, Deserialize, ToSchema)]
|
|
pub struct UpdateMovie {
|
|
pub title: Option<String>,
|
|
pub year: Option<Option<i64>>,
|
|
pub original_language: Option<Option<String>>,
|
|
pub root_id: Option<i64>,
|
|
pub wanted: Option<bool>,
|
|
pub blocked: Option<bool>,
|
|
pub overrides: Option<serde_json::Value>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct Release {
|
|
pub id: i64,
|
|
pub indexer_id: i64,
|
|
pub guid: String,
|
|
pub name: String,
|
|
pub size: i64,
|
|
pub seeders: Option<i64>,
|
|
pub publish_date: Option<String>,
|
|
pub download_url: String,
|
|
pub parsed: serde_json::Value,
|
|
pub score: Option<f64>,
|
|
pub verdict: Option<String>,
|
|
pub rejected_rule: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct AttentionQueues {
|
|
pub no_pt_source: Vec<Movie>,
|
|
pub needs_decision: Vec<Movie>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct Accepted {
|
|
pub accepted: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Serialize, ToSchema)]
|
|
pub struct ErrorBody {
|
|
pub error: String,
|
|
}
|
|
|
|
#[derive(Debug)]
|
|
pub enum ApiError {
|
|
NotFound,
|
|
OwnerNotFound,
|
|
Conflict(String),
|
|
Invalid(String),
|
|
Unavailable,
|
|
Database(String),
|
|
}
|
|
|
|
impl IntoResponse for ApiError {
|
|
fn into_response(self) -> Response {
|
|
let (status, error) = match self {
|
|
Self::NotFound => (StatusCode::NOT_FOUND, "movie not found".to_string()),
|
|
Self::OwnerNotFound => (StatusCode::NOT_FOUND, "owner not found".to_string()),
|
|
Self::Conflict(error) => (StatusCode::CONFLICT, error),
|
|
Self::Invalid(error) => (StatusCode::UNPROCESSABLE_ENTITY, error),
|
|
Self::Unavailable => (
|
|
StatusCode::SERVICE_UNAVAILABLE,
|
|
"database unavailable".into(),
|
|
),
|
|
Self::Database(error) => {
|
|
tracing::error!(%error, "movie API database error");
|
|
(StatusCode::INTERNAL_SERVER_ERROR, "database error".into())
|
|
}
|
|
};
|
|
(status, Json(ErrorBody { error })).into_response()
|
|
}
|
|
}
|
|
|
|
impl From<sqlx::Error> for ApiError {
|
|
fn from(error: sqlx::Error) -> Self {
|
|
if matches!(error, sqlx::Error::RowNotFound) {
|
|
Self::NotFound
|
|
} else if let sqlx::Error::Database(database) = &error {
|
|
if database.is_unique_violation() || database.is_foreign_key_violation() {
|
|
return Self::Conflict(database.message().to_string());
|
|
}
|
|
Self::Database(error.to_string())
|
|
} else {
|
|
Self::Database(error.to_string())
|
|
}
|
|
}
|
|
}
|
|
|
|
fn default_true() -> bool {
|
|
true
|
|
}
|
|
|
|
fn empty_overrides() -> serde_json::Value {
|
|
serde_json::json!({})
|
|
}
|
|
|
|
fn validate_overrides(value: &serde_json::Value) -> Result<(), ApiError> {
|
|
let Some(object) = value.as_object() else {
|
|
return Err(ApiError::Invalid("overrides must be an object".into()));
|
|
};
|
|
if object
|
|
.keys()
|
|
.any(|key| key != "only_4k" && key != "allow_english_audio")
|
|
{
|
|
return Err(ApiError::Invalid(
|
|
"overrides supports only only_4k and allow_english_audio".into(),
|
|
));
|
|
}
|
|
if object.values().any(|value| !value.is_boolean()) {
|
|
return Err(ApiError::Invalid("override values must be booleans".into()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) fn pool(state: &AppState) -> Result<&sqlx::SqlitePool, ApiError> {
|
|
state
|
|
.database()
|
|
.map(arr_db::Db::pool)
|
|
.ok_or(ApiError::Unavailable)
|
|
}
|
|
|
|
async fn load_movie(state: &AppState, id: i64) -> Result<Movie, ApiError> {
|
|
Ok(sqlx::query_as!(Movie, r#"SELECT id AS "id!: i64", tmdb_id AS "tmdb_id!: i64", title AS "title!: String", year, original_language, root_id AS "root_id!: i64", wanted AS "wanted!: bool", overrides AS "overrides!: serde_json::Value", state AS "state!: String", blocked AS "blocked!: bool", search_attempts AS "search_attempts!: i64", last_searched_at FROM movies WHERE id = ?"#, id)
|
|
.fetch_one(pool(state)?)
|
|
.await?)
|
|
}
|
|
|
|
#[derive(Debug, Deserialize, IntoParams)]
|
|
pub struct ListMoviesQuery {
|
|
/// Restrict to movies tagged with this owner (DESIGN.md §4.3).
|
|
pub owner_id: Option<i64>,
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get, path = "/api/movies", tag = "movies",
|
|
params(ListMoviesQuery),
|
|
responses(
|
|
(status = 200, body = [Movie]),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn list(
|
|
State(state): State<AppState>,
|
|
Query(query): Query<ListMoviesQuery>,
|
|
) -> Result<Json<Vec<Movie>>, ApiError> {
|
|
let movies = if let Some(owner_id) = query.owner_id {
|
|
sqlx::query_as!(Movie, r#"SELECT m.id AS "id!: i64", m.tmdb_id AS "tmdb_id!: i64", m.title AS "title!: String", m.year, m.original_language, m.root_id AS "root_id!: i64", m.wanted AS "wanted!: bool", m.overrides AS "overrides!: serde_json::Value", m.state AS "state!: String", m.blocked AS "blocked!: bool", m.search_attempts AS "search_attempts!: i64", m.last_searched_at FROM movies m JOIN title_owners t ON t.title_kind = 'movie' AND t.title_id = m.id WHERE t.owner_id = ? ORDER BY m.title, m.year, m.id"#, owner_id)
|
|
.fetch_all(pool(&state)?)
|
|
.await?
|
|
} else {
|
|
sqlx::query_as!(Movie, r#"SELECT id AS "id!: i64", tmdb_id AS "tmdb_id!: i64", title AS "title!: String", year, original_language, root_id AS "root_id!: i64", wanted AS "wanted!: bool", overrides AS "overrides!: serde_json::Value", state AS "state!: String", blocked AS "blocked!: bool", search_attempts AS "search_attempts!: i64", last_searched_at FROM movies ORDER BY title, year, id"#)
|
|
.fetch_all(pool(&state)?)
|
|
.await?
|
|
};
|
|
Ok(Json(movies))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
post, path = "/api/movies", tag = "movies", request_body = CreateMovie,
|
|
responses(
|
|
(status = 201, body = Movie),
|
|
(status = 409, body = ErrorBody),
|
|
(status = 422, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn create(
|
|
State(state): State<AppState>,
|
|
Json(input): Json<CreateMovie>,
|
|
) -> Result<(StatusCode, Json<Movie>), ApiError> {
|
|
if input.title.trim().is_empty() || input.tmdb_id <= 0 {
|
|
return Err(ApiError::Invalid("tmdb_id and title are required".into()));
|
|
}
|
|
validate_overrides(&input.overrides)?;
|
|
let movie_root = sqlx::query_scalar!(
|
|
"SELECT EXISTS(SELECT 1 FROM roots WHERE id = ? AND kind = 'movie') AS 'exists!: bool'",
|
|
input.root_id
|
|
)
|
|
.fetch_one(pool(&state)?)
|
|
.await?;
|
|
if !movie_root {
|
|
return Err(ApiError::Invalid("root_id must name a movie root".into()));
|
|
}
|
|
let overrides = serde_json::to_string(&input.overrides)
|
|
.map_err(|error| ApiError::Invalid(error.to_string()))?;
|
|
let title = input.title.trim();
|
|
let result = sqlx::query!(
|
|
"INSERT INTO movies (tmdb_id, title, year, original_language, root_id, wanted, blocked, overrides) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
|
|
input.tmdb_id, title, input.year, input.original_language, input.root_id,
|
|
input.wanted, input.blocked, overrides
|
|
)
|
|
.execute(pool(&state)?)
|
|
.await?;
|
|
Ok((
|
|
StatusCode::CREATED,
|
|
Json(load_movie(&state, result.last_insert_rowid()).await?),
|
|
))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get, path = "/api/movies/{movie_id}", tag = "movies",
|
|
params(("movie_id" = i64, Path, description = "Movie row id")),
|
|
responses(
|
|
(status = 200, body = Movie),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn get(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<i64>,
|
|
) -> Result<Json<Movie>, ApiError> {
|
|
Ok(Json(load_movie(&state, id).await?))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
patch, path = "/api/movies/{movie_id}", tag = "movies", request_body = UpdateMovie,
|
|
params(("movie_id" = i64, Path, description = "Movie row id")),
|
|
responses(
|
|
(status = 200, body = Movie),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 409, body = ErrorBody),
|
|
(status = 422, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn update(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<i64>,
|
|
Json(input): Json<UpdateMovie>,
|
|
) -> Result<Json<Movie>, ApiError> {
|
|
let current = load_movie(&state, id).await?;
|
|
let title = input.title.unwrap_or(current.title);
|
|
if title.trim().is_empty() {
|
|
return Err(ApiError::Invalid("title cannot be empty".into()));
|
|
}
|
|
let overrides = input.overrides.unwrap_or(current.overrides);
|
|
validate_overrides(&overrides)?;
|
|
let overrides =
|
|
serde_json::to_string(&overrides).map_err(|error| ApiError::Invalid(error.to_string()))?;
|
|
let title = title.trim();
|
|
let year = input.year.unwrap_or(current.year);
|
|
let original_language = input.original_language.unwrap_or(current.original_language);
|
|
let root_id = input.root_id.unwrap_or(current.root_id);
|
|
if input.root_id.is_some() {
|
|
let movie_root = sqlx::query_scalar!(
|
|
"SELECT EXISTS(SELECT 1 FROM roots WHERE id = ? AND kind = 'movie') AS 'exists!: bool'",
|
|
root_id
|
|
)
|
|
.fetch_one(pool(&state)?)
|
|
.await?;
|
|
if !movie_root {
|
|
return Err(ApiError::Invalid("root_id must name a movie root".into()));
|
|
}
|
|
}
|
|
let wanted = input.wanted.unwrap_or(current.wanted);
|
|
let blocked = input.blocked.unwrap_or(current.blocked);
|
|
sqlx::query!("UPDATE movies SET title = ?, year = ?, original_language = ?, root_id = ?, wanted = ?, blocked = ?, overrides = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?", title, year, original_language, root_id, wanted, blocked, overrides, id)
|
|
.execute(pool(&state)?)
|
|
.await?;
|
|
Ok(Json(load_movie(&state, id).await?))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
delete, path = "/api/movies/{movie_id}", tag = "movies",
|
|
params(("movie_id" = i64, Path, description = "Movie row id")),
|
|
responses(
|
|
(status = 204),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 409, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn delete(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<i64>,
|
|
) -> Result<StatusCode, ApiError> {
|
|
let result = sqlx::query!("DELETE FROM movies WHERE id = ?", id)
|
|
.execute(pool(&state)?)
|
|
.await?;
|
|
if result.rows_affected() == 0 {
|
|
return Err(ApiError::NotFound);
|
|
}
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
#[utoipa::path(
|
|
post, path = "/api/movies/{movie_id}/search", tag = "movies",
|
|
params(("movie_id" = i64, Path, description = "Movie row id")),
|
|
responses(
|
|
(status = 202, body = Accepted),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 409, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn search(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<i64>,
|
|
) -> Result<(StatusCode, Json<Accepted>), ApiError> {
|
|
let movie = load_movie(&state, id).await?;
|
|
if movie.blocked {
|
|
return Err(ApiError::Conflict("movie is blocked".into()));
|
|
}
|
|
state
|
|
.send_movie_command(MovieCommand::Search { movie_id: id })
|
|
.map_err(|_| ApiError::Unavailable)?;
|
|
Ok((StatusCode::ACCEPTED, Json(Accepted { accepted: true })))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get, path = "/api/movies/{movie_id}/releases", tag = "movies",
|
|
params(("movie_id" = i64, Path, description = "Movie row id")),
|
|
responses(
|
|
(status = 200, body = [Release]),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn releases(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<i64>,
|
|
) -> Result<Json<Vec<Release>>, ApiError> {
|
|
load_movie(&state, id).await?;
|
|
let releases = sqlx::query_as!(Release, r#"SELECT r.id AS "id!: i64", r.indexer_id AS "indexer_id!: i64", r.guid AS "guid!: String", r.name AS "name!: String", r.size AS "size!: i64", r.seeders, r.publish_date, r.download_url AS "download_url!: String", r.parsed AS "parsed!: serde_json::Value", r.score, r.verdict, r.rejected_rule FROM releases r JOIN movie_releases mr ON mr.release_id = r.id WHERE mr.movie_id = ? ORDER BY CASE r.verdict WHEN 'eligible' THEN 0 WHEN 'waived' THEN 1 ELSE 2 END, r.score DESC, r.id"#, id)
|
|
.fetch_all(pool(&state)?)
|
|
.await?;
|
|
Ok(Json(releases))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
post, path = "/api/movies/{movie_id}/releases/{release_id}/grab", tag = "movies",
|
|
params(("movie_id" = i64, Path), ("release_id" = i64, Path)),
|
|
responses(
|
|
(status = 202, body = Accepted),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn grab(
|
|
State(state): State<AppState>,
|
|
Path((movie_id, release_id)): Path<(i64, i64)>,
|
|
) -> Result<(StatusCode, Json<Accepted>), ApiError> {
|
|
let exists = sqlx::query_scalar!("SELECT EXISTS(SELECT 1 FROM movie_releases WHERE movie_id = ? AND release_id = ?) AS 'exists!: bool'", movie_id, release_id)
|
|
.fetch_one(pool(&state)?)
|
|
.await?;
|
|
if !exists {
|
|
return Err(ApiError::NotFound);
|
|
}
|
|
state
|
|
.send_movie_command(MovieCommand::Grab {
|
|
movie_id,
|
|
release_id,
|
|
})
|
|
.map_err(|_| ApiError::Unavailable)?;
|
|
Ok((StatusCode::ACCEPTED, Json(Accepted { accepted: true })))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get, path = "/api/queues/attention", tag = "movies",
|
|
responses(
|
|
(status = 200, body = AttentionQueues),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn attention(State(state): State<AppState>) -> Result<Json<AttentionQueues>, ApiError> {
|
|
let no_pt_source = sqlx::query_as!(Movie, r#"SELECT id AS "id!: i64", tmdb_id AS "tmdb_id!: i64", title AS "title!: String", year, original_language, root_id AS "root_id!: i64", wanted AS "wanted!: bool", overrides AS "overrides!: serde_json::Value", state AS "state!: String", blocked AS "blocked!: bool", search_attempts AS "search_attempts!: i64", last_searched_at FROM movies WHERE id IN (SELECT m.id FROM movies m JOIN roots root ON root.id = m.root_id WHERE root.audience = 'kids' AND m.wanted = 1 AND m.blocked = 0 AND m.state = 'missing' AND m.search_attempts > 0 AND NOT EXISTS (SELECT 1 FROM movie_releases mr JOIN releases r ON r.id = mr.release_id WHERE mr.movie_id = m.id AND r.verdict IN ('eligible', 'waived'))) ORDER BY title"#)
|
|
.fetch_all(pool(&state)?)
|
|
.await?;
|
|
let needs_decision = sqlx::query_as!(Movie, r#"SELECT id AS "id!: i64", tmdb_id AS "tmdb_id!: i64", title AS "title!: String", year, original_language, root_id AS "root_id!: i64", wanted AS "wanted!: bool", overrides AS "overrides!: serde_json::Value", state AS "state!: String", blocked AS "blocked!: bool", search_attempts AS "search_attempts!: i64", last_searched_at FROM movies WHERE (SELECT count(DISTINCT g.release_id) FROM grabs g WHERE g.target_kind = 'movie' AND g.target_id = movies.id AND g.state = 'failed') >= 2 ORDER BY title"#)
|
|
.fetch_all(pool(&state)?)
|
|
.await?;
|
|
Ok(Json(AttentionQueues {
|
|
no_pt_source,
|
|
needs_decision,
|
|
}))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
get, path = "/api/movies/{movie_id}/owners", tag = "movies",
|
|
params(("movie_id" = i64, Path, description = "Movie row id")),
|
|
responses(
|
|
(status = 200, body = [Owner]),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn list_owners(
|
|
State(state): State<AppState>,
|
|
Path(id): Path<i64>,
|
|
) -> Result<Json<Vec<Owner>>, ApiError> {
|
|
load_movie(&state, id).await?;
|
|
let owners = sqlx::query_as!(
|
|
Owner,
|
|
r#"SELECT o.id AS "id!: i64", o.name AS "name!: String", o.ntfy_topic AS "ntfy_topic!: String"
|
|
FROM owners o
|
|
JOIN title_owners t ON t.owner_id = o.id
|
|
WHERE t.title_kind = 'movie' AND t.title_id = ?
|
|
ORDER BY o.name"#,
|
|
id
|
|
)
|
|
.fetch_all(pool(&state)?)
|
|
.await?;
|
|
Ok(Json(owners))
|
|
}
|
|
|
|
#[utoipa::path(
|
|
put, path = "/api/movies/{movie_id}/owners/{owner_id}", tag = "movies",
|
|
params(("movie_id" = i64, Path), ("owner_id" = i64, Path)),
|
|
responses(
|
|
(status = 204),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn tag_owner(
|
|
State(state): State<AppState>,
|
|
Path((movie_id, owner_id)): Path<(i64, i64)>,
|
|
) -> Result<StatusCode, ApiError> {
|
|
load_movie(&state, movie_id).await?;
|
|
let owner_exists = sqlx::query_scalar!(
|
|
"SELECT EXISTS(SELECT 1 FROM owners WHERE id = ?) AS 'exists!: bool'",
|
|
owner_id
|
|
)
|
|
.fetch_one(pool(&state)?)
|
|
.await?;
|
|
if !owner_exists {
|
|
return Err(ApiError::OwnerNotFound);
|
|
}
|
|
sqlx::query!(
|
|
"INSERT INTO title_owners (title_kind, title_id, owner_id) VALUES ('movie', ?, ?) ON CONFLICT DO NOTHING",
|
|
movie_id, owner_id
|
|
)
|
|
.execute(pool(&state)?)
|
|
.await?;
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
#[utoipa::path(
|
|
delete, path = "/api/movies/{movie_id}/owners/{owner_id}", tag = "movies",
|
|
params(("movie_id" = i64, Path), ("owner_id" = i64, Path)),
|
|
responses(
|
|
(status = 204),
|
|
(status = 404, body = ErrorBody),
|
|
(status = 500, body = ErrorBody),
|
|
(status = 503, body = ErrorBody)
|
|
)
|
|
)]
|
|
pub async fn untag_owner(
|
|
State(state): State<AppState>,
|
|
Path((movie_id, owner_id)): Path<(i64, i64)>,
|
|
) -> Result<StatusCode, ApiError> {
|
|
load_movie(&state, movie_id).await?;
|
|
sqlx::query!(
|
|
"DELETE FROM title_owners WHERE title_kind = 'movie' AND title_id = ? AND owner_id = ?",
|
|
movie_id,
|
|
owner_id
|
|
)
|
|
.execute(pool(&state)?)
|
|
.await?;
|
|
Ok(StatusCode::NO_CONTENT)
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use crate::{router, Upstreams};
|
|
|
|
async fn application() -> (tempfile::TempDir, AppState, String) {
|
|
let dir = tempfile::tempdir().expect("tempdir");
|
|
let database = arr_db::Db::connect(dir.path().join("arr.db"))
|
|
.await
|
|
.expect("connect database");
|
|
database.migrate().await.expect("migrate database");
|
|
let state = AppState::new(Upstreams::new(
|
|
"http://127.0.0.1:1".into(),
|
|
"http://127.0.0.1:1".into(),
|
|
))
|
|
.expect("state")
|
|
.with_database(database);
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
|
|
.await
|
|
.expect("bind");
|
|
let address = listener.local_addr().expect("address");
|
|
let app = router(state.clone());
|
|
tokio::spawn(async move { axum::serve(listener, app).await.expect("serve") });
|
|
(dir, state, format!("http://{address}"))
|
|
}
|
|
|
|
async fn add_movie(base: &str, tmdb_id: i64, root_id: i64) -> serde_json::Value {
|
|
let response = reqwest::Client::new()
|
|
.post(format!("{base}/api/movies"))
|
|
.json(&serde_json::json!({
|
|
"tmdb_id": tmdb_id, "title": "Dune Part Two", "year": 2024,
|
|
"original_language": "en", "root_id": root_id,
|
|
"overrides": {"only_4k": true}
|
|
}))
|
|
.send()
|
|
.await
|
|
.expect("create movie");
|
|
assert_eq!(response.status(), StatusCode::CREATED);
|
|
response.json().await.expect("movie json")
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn crud_preserves_intent_and_overrides() {
|
|
let (_dir, _state, base) = application().await;
|
|
let movie = add_movie(&base, 693_134, 2).await;
|
|
let id = movie["id"].as_i64().expect("id");
|
|
assert_eq!(movie["wanted"], true);
|
|
assert_eq!(movie["overrides"]["only_4k"], true);
|
|
|
|
let updated: serde_json::Value = reqwest::Client::new()
|
|
.patch(format!("{base}/api/movies/{id}"))
|
|
.json(&serde_json::json!({
|
|
"wanted": false, "blocked": true,
|
|
"overrides": {"allow_english_audio": true}
|
|
}))
|
|
.send()
|
|
.await
|
|
.expect("update")
|
|
.json()
|
|
.await
|
|
.expect("updated json");
|
|
assert_eq!(updated["wanted"], false);
|
|
assert_eq!(updated["blocked"], true);
|
|
assert_eq!(updated["overrides"]["allow_english_audio"], true);
|
|
|
|
let listed: Vec<serde_json::Value> = reqwest::get(format!("{base}/api/movies"))
|
|
.await
|
|
.expect("list")
|
|
.json()
|
|
.await
|
|
.expect("list json");
|
|
assert_eq!(listed.len(), 1);
|
|
|
|
let deleted = reqwest::Client::new()
|
|
.delete(format!("{base}/api/movies/{id}"))
|
|
.send()
|
|
.await
|
|
.expect("delete");
|
|
assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
|
|
assert_eq!(
|
|
reqwest::get(format!("{base}/api/movies/{id}"))
|
|
.await
|
|
.expect("get deleted")
|
|
.status(),
|
|
StatusCode::NOT_FOUND
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn release_actions_are_scoped_to_the_movie() {
|
|
let (_dir, state, base) = application().await;
|
|
let movie = add_movie(&base, 693_134, 2).await;
|
|
let movie_id = movie["id"].as_i64().expect("id");
|
|
let pool = state.database().expect("database").pool();
|
|
let release_id = sqlx::query("INSERT INTO releases (indexer_id, guid, name, size, download_url, parsed, score, verdict) VALUES (7, 'guid', 'release', 1000, 'url', '{}', 42, 'eligible')")
|
|
.execute(pool).await.expect("release").last_insert_rowid();
|
|
sqlx::query("INSERT INTO movie_releases (movie_id, release_id) VALUES (?, ?)")
|
|
.bind(movie_id)
|
|
.bind(release_id)
|
|
.execute(pool)
|
|
.await
|
|
.expect("association");
|
|
let releases: Vec<serde_json::Value> =
|
|
reqwest::get(format!("{base}/api/movies/{movie_id}/releases"))
|
|
.await
|
|
.expect("releases")
|
|
.json()
|
|
.await
|
|
.expect("release json");
|
|
assert_eq!(releases[0]["verdict"], "eligible");
|
|
|
|
let response = reqwest::Client::new()
|
|
.post(format!(
|
|
"{base}/api/movies/{movie_id}/releases/{release_id}/grab"
|
|
))
|
|
.send()
|
|
.await
|
|
.expect("grab");
|
|
assert_eq!(response.status(), StatusCode::ACCEPTED);
|
|
assert_eq!(
|
|
state.next_movie_command().await.expect("command"),
|
|
MovieCommand::Grab {
|
|
movie_id,
|
|
release_id
|
|
}
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn a_full_action_queue_returns_service_unavailable() {
|
|
let (_dir, state, base) = application().await;
|
|
let movie = add_movie(&base, 693_134, 2).await;
|
|
let movie_id = movie["id"].as_i64().expect("id");
|
|
for _ in 0..64 {
|
|
state
|
|
.send_movie_command(MovieCommand::Search { movie_id })
|
|
.expect("queue has capacity");
|
|
}
|
|
|
|
let response = reqwest::Client::new()
|
|
.post(format!("{base}/api/movies/{movie_id}/search"))
|
|
.send()
|
|
.await
|
|
.expect("search");
|
|
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn attention_queues_follow_search_and_failure_state() {
|
|
let (_dir, state, base) = application().await;
|
|
let pool = state.database().expect("database").pool();
|
|
let root_id: i64 = sqlx::query_scalar("SELECT id FROM roots WHERE audience = 'kids'")
|
|
.fetch_one(pool)
|
|
.await
|
|
.expect("kids root");
|
|
let movie = add_movie(&base, 82728, root_id).await;
|
|
let movie_id = movie["id"].as_i64().expect("id");
|
|
sqlx::query("UPDATE movies SET search_attempts = 1 WHERE id = ?")
|
|
.bind(movie_id)
|
|
.execute(pool)
|
|
.await
|
|
.expect("record search");
|
|
|
|
let mut release_ids = Vec::new();
|
|
for suffix in ["a", "b"] {
|
|
let release_id = sqlx::query("INSERT INTO releases (indexer_id, guid, name, size, download_url, parsed, verdict, rejected_rule) VALUES (1, ?, ?, 1, 'url', '{}', 'rejected', 'required_audio')")
|
|
.bind(suffix)
|
|
.bind(suffix)
|
|
.execute(pool)
|
|
.await
|
|
.expect("release")
|
|
.last_insert_rowid();
|
|
release_ids.push(release_id);
|
|
sqlx::query("INSERT INTO grabs (release_id, target_kind, target_id, infohash, state) VALUES (?, 'movie', ?, ?, 'failed')")
|
|
.bind(release_id)
|
|
.bind(movie_id)
|
|
.bind(format!("hash-{suffix}"))
|
|
.execute(pool)
|
|
.await
|
|
.expect("failed grab");
|
|
}
|
|
|
|
let queues: serde_json::Value = reqwest::get(format!("{base}/api/queues/attention"))
|
|
.await
|
|
.expect("queues")
|
|
.json()
|
|
.await
|
|
.expect("queues json");
|
|
assert_eq!(queues["no_pt_source"][0]["id"], movie_id);
|
|
assert_eq!(queues["needs_decision"][0]["id"], movie_id);
|
|
|
|
sqlx::query("UPDATE movies SET blocked = 1 WHERE id = ?")
|
|
.bind(movie_id)
|
|
.execute(pool)
|
|
.await
|
|
.expect("block movie");
|
|
let queues: serde_json::Value = reqwest::get(format!("{base}/api/queues/attention"))
|
|
.await
|
|
.expect("blocked queues")
|
|
.json()
|
|
.await
|
|
.expect("blocked queues json");
|
|
assert_eq!(queues["no_pt_source"].as_array().map(Vec::len), Some(0));
|
|
let search = reqwest::Client::new()
|
|
.post(format!("{base}/api/movies/{movie_id}/search"))
|
|
.send()
|
|
.await
|
|
.expect("blocked search");
|
|
assert_eq!(search.status(), StatusCode::CONFLICT);
|
|
|
|
sqlx::query("UPDATE movies SET blocked = 0 WHERE id = ?")
|
|
.bind(movie_id)
|
|
.execute(pool)
|
|
.await
|
|
.expect("unblock movie");
|
|
|
|
sqlx::query("UPDATE releases SET verdict = 'eligible', rejected_rule = NULL WHERE id = ?")
|
|
.bind(release_ids[0])
|
|
.execute(pool)
|
|
.await
|
|
.expect("eligible release");
|
|
sqlx::query("INSERT INTO movie_releases (movie_id, release_id) VALUES (?, ?)")
|
|
.bind(movie_id)
|
|
.bind(release_ids[0])
|
|
.execute(pool)
|
|
.await
|
|
.expect("associate release");
|
|
|
|
let queues: serde_json::Value = reqwest::get(format!("{base}/api/queues/attention"))
|
|
.await
|
|
.expect("queues")
|
|
.json()
|
|
.await
|
|
.expect("queues json");
|
|
assert_eq!(queues["no_pt_source"].as_array().map(Vec::len), Some(0));
|
|
assert_eq!(queues["needs_decision"][0]["id"], movie_id);
|
|
}
|
|
}
|