Files
arr/crates/arr-compat/src/movies.rs
T
naps62-yolo 94c334ffe9
ci / web (push) Successful in 12s
ci / rust (push) Successful in 1m44s
e2e / e2e (push) Successful in 1m21s
Radarr v3 shim for Jellyseerr (#62)
2026-08-22 21:00:35 +01:00

323 lines
11 KiB
Rust

//! `movie`, `movie/{id}` and `movie/lookup`.
//!
//! Two of Radarr's ideas have to be absorbed here rather than passed on:
//!
//! - **The quality profile.** Policy attaches to a root (§5.1), so the profile
//! id on an add is read and dropped and `rootFolderPath` decides everything.
//! - **`searchForMovie`.** The reconcile loop searches whatever is wanted
//! (§8). Acting on the flag would be a second search path to keep correct,
//! so it is dropped too.
use std::collections::HashMap;
use axum::extract::{Path, Query, State};
use axum::http::StatusCode;
use axum::Json;
use serde::Deserialize;
use crate::error::CompatError;
use crate::model::{AddMovie, MovieResource};
use crate::CompatState;
/// A row of `movies` with everything a Radarr movie needs joined on.
#[derive(Debug, Clone)]
pub(crate) struct MovieRow {
pub(crate) id: i64,
pub(crate) tmdb_id: i64,
pub(crate) title: String,
pub(crate) year: Option<i64>,
pub(crate) wanted: bool,
pub(crate) root_id: i64,
pub(crate) root_path: String,
pub(crate) created_at: String,
pub(crate) file_count: i64,
pub(crate) size_on_disk: i64,
}
/// `?tmdbId=` on the list endpoint, and nothing else Radarr accepts there.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ListQuery {
#[serde(default)]
tmdb_id: Option<i64>,
}
/// `?term=` on lookup.
#[derive(Debug, Deserialize)]
pub(crate) struct LookupQuery {
#[serde(default)]
term: String,
}
/// `GET /api/v3/movie`, optionally narrowed to one TMDB id — Jellyseerr's
/// existence check.
pub(crate) async fn list(
State(state): State<CompatState>,
Query(query): Query<ListQuery>,
) -> Result<Json<Vec<MovieResource>>, CompatError> {
let rows = load_movies(&state, None, query.tmdb_id).await?;
let mut tags = load_tags(&state).await?;
Ok(Json(
rows.iter()
.map(|row| MovieResource::from_library(row, tags.remove(&row.id).unwrap_or_default()))
.collect(),
))
}
/// `GET /api/v3/movie/{id}`.
pub(crate) async fn get(
State(state): State<CompatState>,
Path(id): Path<i64>,
) -> Result<Json<MovieResource>, CompatError> {
let row = load_movies(&state, Some(id), None)
.await?
.into_iter()
.next()
.ok_or(CompatError::NotFound)?;
let tags = load_tags(&state).await?.remove(&row.id).unwrap_or_default();
Ok(Json(MovieResource::from_library(&row, tags)))
}
/// `POST /api/v3/movie` — the request Jellyseerr approves turning into a
/// wanted movie under the root the operator picked.
pub(crate) async fn add(
State(state): State<CompatState>,
Json(input): Json<AddMovie>,
) -> Result<(StatusCode, Json<MovieResource>), CompatError> {
if input.tmdb_id <= 0 {
return Err(CompatError::Validation {
property: "TmdbId",
message: "a TMDB id is required".into(),
});
}
let title = input.title.trim();
if title.is_empty() {
return Err(CompatError::Validation {
property: "Title",
message: "a title is required".into(),
});
}
let root = resolve_root(&state, input.root_folder_path.as_deref()).await?;
if let Some(existing) = load_movies(&state, None, Some(input.tmdb_id))
.await?
.first()
{
return Err(CompatError::Validation {
property: "TmdbId",
message: format!("{} has already been added", existing.title),
});
}
// §5.2 is expressed against the title's original language, and nothing
// else fills it in yet, so take it while a TMDB client is already at hand.
// Best effort: TMDB being down is not a reason to refuse a request.
let original_language = original_language(&state, input.tmdb_id).await;
let inserted = sqlx::query!(
"INSERT INTO movies (tmdb_id, title, year, original_language, root_id, wanted) \
VALUES (?, ?, ?, ?, ?, ?)",
input.tmdb_id,
title,
input.year,
original_language,
root,
input.monitored,
)
.execute(state.pool())
.await?
.last_insert_rowid();
attach_owners(&state, inserted, &input.tags).await?;
let row = load_movies(&state, Some(inserted), None)
.await?
.into_iter()
.next()
.ok_or(CompatError::NotFound)?;
let tags = load_tags(&state).await?.remove(&row.id).unwrap_or_default();
Ok((
StatusCode::CREATED,
Json(MovieResource::from_library(&row, tags)),
))
}
/// `GET /api/v3/movie/lookup?term=` — TMDB search, with the library's own id
/// stamped onto anything already added.
pub(crate) async fn lookup(
State(state): State<CompatState>,
Query(query): Query<LookupQuery>,
) -> Result<Json<Vec<MovieResource>>, CompatError> {
let term = query.term.trim();
if term.is_empty() {
return Ok(Json(Vec::new()));
}
let tmdb = state.tmdb()?;
if let Some(id) = term.strip_prefix("tmdb:") {
let Ok(id) = id.trim().parse::<u32>() else {
return Ok(Json(Vec::new()));
};
return match tmdb.movie(id).await {
Ok(movie) => {
let resource = MovieResource::from_tmdb(&movie);
let existing = load_movies(&state, None, Some(i64::from(movie.tmdb_id))).await?;
Ok(Json(vec![match existing.first() {
Some(row) => resource.with_library(row),
None => resource,
}]))
}
// Radarr answers an unknown id with an empty list, not a 404, and
// Jellyseerr reads that as "not a film" rather than as an outage.
Err(arr_meta::Error::NotFound { .. }) => Ok(Json(Vec::new())),
Err(error) => Err(error.into()),
};
}
// `imdb:` is the other prefix Radarr accepts. TMDB's find-by-external-id
// endpoint is not wired up here, and guessing from the digits would return
// the wrong film, so it answers empty until there is a reason to add it.
if term.starts_with("imdb:") {
tracing::debug!(term, "compat lookup by IMDb id is not supported");
return Ok(Json(Vec::new()));
}
let hits = tmdb.search_movies(term, None).await?;
let library: HashMap<i64, MovieRow> = load_movies(&state, None, None)
.await?
.into_iter()
.map(|row| (row.tmdb_id, row))
.collect();
Ok(Json(
hits.iter()
.map(|hit| {
let resource = MovieResource::from_search(hit);
match library.get(&i64::from(hit.tmdb_id)) {
Some(row) => resource.with_library(row),
None => resource,
}
})
.collect(),
))
}
/// Every movie, or the one matching an id or a TMDB id.
///
/// One query rather than three near-identical ones: a `NULL` filter matches
/// everything, so the shape of the row mapping stays in a single place.
async fn load_movies(
state: &CompatState,
id: Option<i64>,
tmdb_id: Option<i64>,
) -> Result<Vec<MovieRow>, CompatError> {
Ok(sqlx::query_as!(
MovieRow,
r#"
SELECT m.id AS "id!: i64",
m.tmdb_id AS "tmdb_id!: i64",
m.title AS "title!: String",
m.year,
m.wanted AS "wanted!: bool",
m.root_id AS "root_id!: i64",
r.path AS "root_path!: String",
m.created_at AS "created_at!: String",
(SELECT count(*) FROM media_files f
WHERE f.owner_kind = 'movie' AND f.owner_id = m.id)
AS "file_count!: i64",
(SELECT coalesce(sum(f.size), 0) FROM media_files f
WHERE f.owner_kind = 'movie' AND f.owner_id = m.id)
AS "size_on_disk!: i64"
FROM movies m
JOIN roots r ON r.id = m.root_id
WHERE (?1 IS NULL OR m.id = ?1)
AND (?2 IS NULL OR m.tmdb_id = ?2)
ORDER BY m.title, m.year, m.id
"#,
id,
tmdb_id,
)
.fetch_all(state.pool())
.await?)
}
/// Owner ids per movie, in one query. The library is small enough that
/// fetching the whole mapping beats a query per row.
async fn load_tags(state: &CompatState) -> Result<HashMap<i64, Vec<i64>>, CompatError> {
let rows = sqlx::query!(
r#"SELECT title_id AS "title_id!: i64", owner_id AS "owner_id!: i64"
FROM title_owners WHERE title_kind = 'movie' ORDER BY owner_id"#
)
.fetch_all(state.pool())
.await?;
let mut tags: HashMap<i64, Vec<i64>> = HashMap::new();
for row in rows {
tags.entry(row.title_id).or_default().push(row.owner_id);
}
Ok(tags)
}
/// Which root a `rootFolderPath` names, rejecting anything else.
///
/// No default and no fallback to the quality profile: guessing here files a
/// film under the wrong policy, and for the `kids` root that means the wrong
/// audio in front of a child (§5.2).
async fn resolve_root(state: &CompatState, path: Option<&str>) -> Result<i64, CompatError> {
let Some(path) = path.map(normalise_path).filter(|path| !path.is_empty()) else {
return Err(CompatError::Validation {
property: "RootFolderPath",
message: "a root folder path is required".into(),
});
};
state
.database()
.list_roots()
.await?
.into_iter()
.find(|root| root.kind == "movie" && normalise_path(&root.path) == path)
.map(|root| root.id)
.ok_or(CompatError::Validation {
property: "RootFolderPath",
message: format!("{path} is not a configured movie root"),
})
}
/// Trailing separators are cosmetic; Jellyseerr stores whatever was typed.
fn normalise_path(path: &str) -> String {
path.trim().trim_end_matches('/').to_owned()
}
/// The title's original language from TMDB (§5.2), or nothing.
async fn original_language(state: &CompatState, tmdb_id: i64) -> Option<String> {
let id = u32::try_from(tmdb_id).ok()?;
match state.tmdb().ok()?.movie(id).await {
Ok(movie) if !movie.original_language.is_empty() => Some(movie.original_language),
Ok(_) => None,
Err(error) => {
tracing::warn!(%error, tmdb_id, "compat add could not read the original language");
None
}
}
}
/// Radarr's tags are owners (§4.3). Ids that name no owner are dropped rather
/// than failing the add: Jellyseerr's tag list can outlive an owner row, and
/// losing a notification recipient is better than losing the request.
async fn attach_owners(
state: &CompatState,
movie_id: i64,
tags: &[i64],
) -> Result<(), CompatError> {
for tag in tags {
sqlx::query!(
"INSERT OR IGNORE INTO title_owners (title_kind, title_id, owner_id) \
SELECT 'movie', ?, id FROM owners WHERE id = ?",
movie_id,
tag,
)
.execute(state.pool())
.await?;
}
Ok(())
}