//! The TV side of the library API. See DESIGN.md §4, §4.1 and §4.2. //! //! Nothing here is generic over media kind (§11): movies are concrete in //! `movies.rs` and series are concrete here. What the two do share is the //! policy loader, the release table and the owner tags, which already exist. //! //! Two rules shape the endpoints: //! //! - **Intent lives at the leaf** (§4.1). `wanted` is set on an episode. //! `auto_track` on the series and `tracked` on the season are rules that //! decide what happens to episodes a metadata refresh reveals; neither is //! intent, and neither is read to answer "is this wanted". //! - **Status is derived, never stored** (§4.2). Every series the API returns //! carries a status computed from its episodes at request time. use std::collections::HashMap; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use arr_core::tracking::{apply_auto_track, RefreshedSeason}; use arr_core::{ derive_series_status, EpisodeId, Language, MediaState, RootId, SeasonId, SeriesId, SeriesStatus, TitleOverrides, }; use arr_db::policy::language; use axum::extract::{Path, Query, State}; use axum::http::StatusCode; use axum::Json; use chrono::{DateTime, NaiveDate, NaiveTime, Utc}; use serde::{Deserialize, Serialize}; use utoipa::{IntoParams, ToSchema}; use crate::movies::{pool, rescore, Accepted, ApiError, ErrorBody, Release}; use crate::owners::Owner; use crate::state::{AppState, EpisodeCommand}; /// A series with the status derived from its episodes (§4.2). #[derive(Debug, Clone, Serialize, ToSchema)] pub struct Series { pub id: i64, pub tmdb_id: i64, pub title: String, pub year: Option, pub original_language: Option, pub root_id: i64, /// §4.1. A rule about seasons metadata reveals, not intent. pub auto_track: bool, pub overrides: serde_json::Value, /// Whether the show finished upstream, which `ended` is derived from. pub upstream_ended: bool, pub blocked: bool, /// `airing`, `incomplete`, `waiting`, `complete` or `ended` (§4.2). pub status: String, /// Episodes currently marked wanted (§4.1 — the only intent). pub wanted_episodes: i64, /// Wanted episodes already on disk. pub available_episodes: i64, } #[derive(Debug, Deserialize, ToSchema)] pub struct CreateSeries { pub tmdb_id: i64, pub title: String, pub year: Option, pub original_language: Option, pub root_id: i64, #[serde(default)] pub auto_track: bool, #[serde(default)] pub blocked: bool, #[serde(default)] pub upstream_ended: bool, #[serde(default = "empty_overrides")] pub overrides: serde_json::Value, } #[derive(Debug, Deserialize, ToSchema)] pub struct UpdateSeries { pub title: Option, pub year: Option>, pub original_language: Option>, pub root_id: Option, pub auto_track: Option, pub blocked: Option, pub upstream_ended: Option, pub overrides: Option, } /// A season and every episode in it, which is how the UI reads it. #[derive(Debug, Clone, Serialize, ToSchema)] pub struct Season { pub id: i64, pub series_id: i64, pub number: i64, /// §4.1. Whether new episodes of this season arrive wanted. pub tracked: bool, pub episodes: Vec, } #[derive(Debug, Clone, Serialize, ToSchema)] pub struct Episode { pub id: i64, pub season_id: i64, pub number: i64, pub title: String, pub air_date: Option, /// §4.1. The only intent in the TV aggregate. pub wanted: bool, pub state: String, pub search_attempts: i64, pub last_searched_at: Option, } /// A season revealed by metadata, with the episodes it holds. /// /// The series' `auto_track` decides whether those episodes arrive wanted /// (§4.1); the request never says so directly. #[derive(Debug, Deserialize, ToSchema)] pub struct CreateSeason { pub number: i64, #[serde(default)] pub episodes: Vec, } #[derive(Debug, Deserialize, ToSchema)] pub struct CreateEpisode { pub number: i64, pub title: String, /// ISO-8601 date, as TMDB gives it. pub air_date: Option, } /// Both fields of a season a person can set by hand. /// /// `tracked` changes the rule for episodes not yet revealed. `wanted` is the /// one-click "grab this season", and writes intent onto every episode already /// in it — the two are deliberately separate (§4.1). #[derive(Debug, Deserialize, ToSchema)] pub struct UpdateSeason { pub tracked: Option, pub wanted: Option, } #[derive(Debug, Deserialize, ToSchema)] pub struct UpdateEpisode { pub wanted: Option, } 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(()) } /// The stored columns, before the derived status is attached. struct SeriesRow { id: i64, tmdb_id: i64, title: String, year: Option, original_language: Option, root_id: i64, auto_track: bool, overrides: serde_json::Value, upstream_ended: bool, blocked: bool, } struct EpisodeRow { series_id: i64, id: i64, season_id: i64, number: i64, title: String, air_date: Option, wanted: bool, state: String, search_attempts: i64, last_searched_at: Option, } fn media_state(value: &str) -> MediaState { match value { "downloading" => MediaState::Downloading, "available" => MediaState::Available, _ => MediaState::Missing, } } /// An `air_date` as TMDB writes it, or as a full timestamp if one ever /// arrives that way. Anything else is treated as unknown, which §4.2 already /// has a meaning for: it cannot pull a series into `airing`. fn air_date(value: Option<&str>) -> Option { let value = value?; let timestamp = if let Ok(date) = value.parse::() { date.and_time(NaiveTime::MIN).and_utc().timestamp() } else { value.parse::>().ok()?.timestamp() }; let seconds = u64::try_from(timestamp.abs()).ok()?; if timestamp < 0 { UNIX_EPOCH.checked_sub(Duration::from_secs(seconds)) } else { UNIX_EPOCH.checked_add(Duration::from_secs(seconds)) } } fn core_series(row: &SeriesRow) -> arr_core::Series { arr_core::Series { id: SeriesId(row.id), tmdb_id: u64::try_from(row.tmdb_id).unwrap_or_default(), title: row.title.clone(), year: row .year .and_then(|year| u16::try_from(year).ok()) .unwrap_or_default(), original_language: row .original_language .as_deref() .map_or(Language::Other(String::new()), language), root_id: RootId(row.root_id), auto_track: row.auto_track, overrides: TitleOverrides::default(), upstream_ended: row.upstream_ended, blocked: row.blocked, } } fn core_episode(row: &EpisodeRow) -> arr_core::Episode { arr_core::Episode { id: EpisodeId(row.id), season_id: SeasonId(row.season_id), number: u16::try_from(row.number).unwrap_or_default(), title: row.title.clone(), air_date: air_date(row.air_date.as_deref()), wanted: row.wanted, state: media_state(&row.state), search_attempts: u32::try_from(row.search_attempts).unwrap_or_default(), last_searched_at: None, } } fn status_name(status: SeriesStatus) -> &'static str { match status { SeriesStatus::Airing => "airing", SeriesStatus::Incomplete => "incomplete", SeriesStatus::Waiting => "waiting", SeriesStatus::Complete => "complete", SeriesStatus::Ended => "ended", } } fn with_status(row: &SeriesRow, episodes: &[arr_core::Episode], now: SystemTime) -> Series { let wanted = episodes.iter().filter(|episode| episode.wanted); let available = wanted .clone() .filter(|episode| episode.state == MediaState::Available); Series { id: row.id, tmdb_id: row.tmdb_id, title: row.title.clone(), year: row.year, original_language: row.original_language.clone(), root_id: row.root_id, auto_track: row.auto_track, overrides: row.overrides.clone(), upstream_ended: row.upstream_ended, blocked: row.blocked, status: status_name(derive_series_status(&core_series(row), episodes, now)).to_owned(), wanted_episodes: i64::try_from(wanted.count()).unwrap_or(i64::MAX), available_episodes: i64::try_from(available.count()).unwrap_or(i64::MAX), } } /// Every episode in the library, keyed by the series it belongs to. /// /// One query rather than one per series: the whole table is a few thousand /// rows for a single household (§10), and the status of every listed series /// needs all of them anyway. async fn episodes_by_series( state: &AppState, ) -> Result>, ApiError> { let rows = sqlx::query_as!( EpisodeRow, r#"SELECT se.series_id AS "series_id!: i64", e.id AS "id!: i64", e.season_id AS "season_id!: i64", e.number AS "number!: i64", e.title AS "title!: String", e.air_date, e.wanted AS "wanted!: bool", e.state AS "state!: String", e.search_attempts AS "search_attempts!: i64", e.last_searched_at FROM episodes e JOIN seasons se ON se.id = e.season_id"# ) .fetch_all(pool(state)?) .await?; let mut grouped: HashMap> = HashMap::new(); for row in &rows { grouped .entry(row.series_id) .or_default() .push(core_episode(row)); } Ok(grouped) } async fn load_series_row(state: &AppState, id: i64) -> Result { sqlx::query_as!(SeriesRow, 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", auto_track AS "auto_track!: bool", overrides AS "overrides!: serde_json::Value", upstream_ended AS "upstream_ended!: bool", blocked AS "blocked!: bool" FROM series WHERE id = ?"#, id) .fetch_optional(pool(state)?) .await? .ok_or(ApiError::SeriesNotFound) } async fn load_series(state: &AppState, id: i64) -> Result { let row = load_series_row(state, id).await?; let episodes = sqlx::query_as!( EpisodeRow, r#"SELECT se.series_id AS "series_id!: i64", e.id AS "id!: i64", e.season_id AS "season_id!: i64", e.number AS "number!: i64", e.title AS "title!: String", e.air_date, e.wanted AS "wanted!: bool", e.state AS "state!: String", e.search_attempts AS "search_attempts!: i64", e.last_searched_at FROM episodes e JOIN seasons se ON se.id = e.season_id WHERE se.series_id = ?"#, id ) .fetch_all(pool(state)?) .await?; let episodes: Vec<_> = episodes.iter().map(core_episode).collect(); Ok(with_status(&row, &episodes, SystemTime::now())) } async fn require_tv_root(state: &AppState, root_id: i64) -> Result<(), ApiError> { let tv_root = sqlx::query_scalar!( "SELECT EXISTS(SELECT 1 FROM roots WHERE id = ? AND kind = 'tv') AS 'exists!: bool'", root_id ) .fetch_one(pool(state)?) .await?; if tv_root { Ok(()) } else { Err(ApiError::Invalid("root_id must name a TV root".into())) } } #[derive(Debug, Deserialize, IntoParams)] pub struct ListSeriesQuery { /// Restrict to series tagged with this owner (DESIGN.md §4.3). pub owner_id: Option, } #[utoipa::path( get, path = "/api/series", tag = "series", params(ListSeriesQuery), responses( (status = 200, body = [Series]), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn list( State(state): State, Query(query): Query, ) -> Result>, ApiError> { let rows = if let Some(owner_id) = query.owner_id { sqlx::query_as!(SeriesRow, r#"SELECT s.id AS "id!: i64", s.tmdb_id AS "tmdb_id!: i64", s.title AS "title!: String", s.year, s.original_language, s.root_id AS "root_id!: i64", s.auto_track AS "auto_track!: bool", s.overrides AS "overrides!: serde_json::Value", s.upstream_ended AS "upstream_ended!: bool", s.blocked AS "blocked!: bool" FROM series s JOIN title_owners t ON t.title_kind = 'series' AND t.title_id = s.id WHERE t.owner_id = ? ORDER BY s.title, s.year, s.id"#, owner_id) .fetch_all(pool(&state)?) .await? } else { sqlx::query_as!(SeriesRow, 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", auto_track AS "auto_track!: bool", overrides AS "overrides!: serde_json::Value", upstream_ended AS "upstream_ended!: bool", blocked AS "blocked!: bool" FROM series ORDER BY title, year, id"#) .fetch_all(pool(&state)?) .await? }; let episodes = episodes_by_series(&state).await?; let now = SystemTime::now(); let empty = Vec::new(); Ok(Json( rows.iter() .map(|row| with_status(row, episodes.get(&row.id).unwrap_or(&empty), now)) .collect(), )) } #[utoipa::path( post, path = "/api/series", tag = "series", request_body = CreateSeries, responses( (status = 201, body = Series), (status = 409, body = ErrorBody), (status = 422, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn create( State(state): State, Json(input): Json, ) -> Result<(StatusCode, Json), 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)?; require_tv_root(&state, input.root_id).await?; 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 series (tmdb_id, title, year, original_language, root_id, auto_track, upstream_ended, blocked, overrides) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", input.tmdb_id, title, input.year, input.original_language, input.root_id, input.auto_track, input.upstream_ended, input.blocked, overrides ) .execute(pool(&state)?) .await?; Ok(( StatusCode::CREATED, Json(load_series(&state, result.last_insert_rowid()).await?), )) } #[utoipa::path( get, path = "/api/series/{series_id}", tag = "series", params(("series_id" = i64, Path, description = "Series row id")), responses( (status = 200, body = Series), (status = 404, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn get( State(state): State, Path(id): Path, ) -> Result, ApiError> { Ok(Json(load_series(&state, id).await?)) } #[utoipa::path( patch, path = "/api/series/{series_id}", tag = "series", request_body = UpdateSeries, params(("series_id" = i64, Path, description = "Series row id")), responses( (status = 200, body = Series), (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, Path(id): Path, Json(input): Json, ) -> Result, ApiError> { let current = load_series_row(&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() { require_tv_root(&state, root_id).await?; } let auto_track = input.auto_track.unwrap_or(current.auto_track); let upstream_ended = input.upstream_ended.unwrap_or(current.upstream_ended); let blocked = input.blocked.unwrap_or(current.blocked); sqlx::query!("UPDATE series SET title = ?, year = ?, original_language = ?, root_id = ?, auto_track = ?, upstream_ended = ?, blocked = ?, overrides = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?", title, year, original_language, root_id, auto_track, upstream_ended, blocked, overrides, id) .execute(pool(&state)?) .await?; Ok(Json(load_series(&state, id).await?)) } #[utoipa::path( delete, path = "/api/series/{series_id}", tag = "series", params(("series_id" = i64, Path, description = "Series 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, Path(id): Path, ) -> Result { let result = sqlx::query!("DELETE FROM series WHERE id = ?", id) .execute(pool(&state)?) .await?; if result.rows_affected() == 0 { return Err(ApiError::SeriesNotFound); } Ok(StatusCode::NO_CONTENT) } async fn load_seasons(state: &AppState, series_id: i64) -> Result, ApiError> { let seasons = sqlx::query!( r#"SELECT id AS "id!: i64", series_id AS "series_id!: i64", number AS "number!: i64", tracked AS "tracked!: bool" FROM seasons WHERE series_id = ? ORDER BY number"#, series_id ) .fetch_all(pool(state)?) .await?; let episodes = sqlx::query_as!( EpisodeRow, r#"SELECT se.series_id AS "series_id!: i64", e.id AS "id!: i64", e.season_id AS "season_id!: i64", e.number AS "number!: i64", e.title AS "title!: String", e.air_date, e.wanted AS "wanted!: bool", e.state AS "state!: String", e.search_attempts AS "search_attempts!: i64", e.last_searched_at FROM episodes e JOIN seasons se ON se.id = e.season_id WHERE se.series_id = ? ORDER BY se.number, e.number"#, series_id ) .fetch_all(pool(state)?) .await?; Ok(seasons .into_iter() .map(|season| Season { id: season.id, series_id: season.series_id, number: season.number, tracked: season.tracked, episodes: episodes .iter() .filter(|episode| episode.season_id == season.id) .map(|episode| Episode { id: episode.id, season_id: episode.season_id, number: episode.number, title: episode.title.clone(), air_date: episode.air_date.clone(), wanted: episode.wanted, state: episode.state.clone(), search_attempts: episode.search_attempts, last_searched_at: episode.last_searched_at.clone(), }) .collect(), }) .collect()) } #[utoipa::path( get, path = "/api/series/{series_id}/seasons", tag = "series", params(("series_id" = i64, Path, description = "Series row id")), responses( (status = 200, body = [Season]), (status = 404, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn seasons( State(state): State, Path(series_id): Path, ) -> Result>, ApiError> { load_series_row(&state, series_id).await?; Ok(Json(load_seasons(&state, series_id).await?)) } /// Records a season metadata has revealed, applying the series' tracking rule. #[utoipa::path( post, path = "/api/series/{series_id}/seasons", tag = "series", request_body = CreateSeason, params(("series_id" = i64, Path, description = "Series row id")), responses( (status = 201, body = Season), (status = 404, body = ErrorBody), (status = 409, body = ErrorBody), (status = 422, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn create_season( State(state): State, Path(series_id): Path, Json(input): Json, ) -> Result<(StatusCode, Json), ApiError> { let series = load_series_row(&state, series_id).await?; if input.number < 0 { return Err(ApiError::Invalid("season number cannot be negative".into())); } if input.episodes.iter().any(|episode| episode.number < 0) { return Err(ApiError::Invalid( "episode number cannot be negative".into(), )); } let mut numbers: Vec = input .episodes .iter() .map(|episode| episode.number) .collect(); numbers.sort_unstable(); if numbers.windows(2).any(|pair| pair[0] == pair[1]) { return Err(ApiError::Invalid( "episode numbers must be unique within the season".into(), )); } // §4.1. The request does not say whether the episodes are wanted; the // series' auto_track rule does, through the one function that owns it. let mut revealed = [RefreshedSeason { season: arr_core::Season { id: SeasonId(0), series_id: SeriesId(series_id), number: u16::try_from(input.number).unwrap_or_default(), tracked: false, }, episodes: input .episodes .iter() .map(|episode| arr_core::Episode { id: EpisodeId(0), season_id: SeasonId(0), number: u16::try_from(episode.number).unwrap_or_default(), title: episode.title.clone(), air_date: air_date(episode.air_date.as_deref()), wanted: false, state: MediaState::Missing, search_attempts: 0, last_searched_at: None, }) .collect(), is_new: true, }]; apply_auto_track(&core_series(&series), &mut revealed); let [revealed] = revealed; // One transaction: a rejected episode must not leave the season behind, // or the retry that fixes the request collides with it instead. let mut transaction = pool(&state)?.begin().await?; let season_id = sqlx::query!( "INSERT INTO seasons (series_id, number, tracked) VALUES (?, ?, ?)", series_id, input.number, revealed.season.tracked ) .execute(&mut *transaction) .await? .last_insert_rowid(); for (episode, source) in revealed.episodes.iter().zip(&input.episodes) { sqlx::query!( "INSERT INTO episodes (season_id, number, title, air_date, wanted) VALUES (?, ?, ?, ?, ?)", season_id, source.number, source.title, source.air_date, episode.wanted ) .execute(&mut *transaction) .await?; } transaction.commit().await?; let seasons = load_seasons(&state, series_id).await?; let season = seasons .into_iter() .find(|season| season.id == season_id) .ok_or(ApiError::SeasonNotFound)?; Ok((StatusCode::CREATED, Json(season))) } #[utoipa::path( patch, path = "/api/series/{series_id}/seasons/{season_number}", tag = "series", request_body = UpdateSeason, params( ("series_id" = i64, Path, description = "Series row id"), ("season_number" = i64, Path, description = "Season number, not its row id") ), responses( (status = 200, body = Season), (status = 404, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn update_season( State(state): State, Path((series_id, number)): Path<(i64, i64)>, Json(input): Json, ) -> Result, ApiError> { load_series_row(&state, series_id).await?; let season_id = sqlx::query_scalar!( r#"SELECT id AS "id!: i64" FROM seasons WHERE series_id = ? AND number = ?"#, series_id, number ) .fetch_optional(pool(&state)?) .await? .ok_or(ApiError::SeasonNotFound)?; if let Some(tracked) = input.tracked { sqlx::query!( "UPDATE seasons SET tracked = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?", tracked, season_id ) .execute(pool(&state)?) .await?; } // §4.1. Marking a season wanted is intent written onto its episodes, so // an untracked series with one wanted season needs no special case. if let Some(wanted) = input.wanted { sqlx::query!( "UPDATE episodes SET wanted = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE season_id = ?", wanted, season_id ) .execute(pool(&state)?) .await?; } let seasons = load_seasons(&state, series_id).await?; seasons .into_iter() .find(|season| season.id == season_id) .map(Json) .ok_or(ApiError::SeasonNotFound) } async fn load_episode(state: &AppState, id: i64) -> Result { let row = sqlx::query_as!( EpisodeRow, r#"SELECT se.series_id AS "series_id!: i64", e.id AS "id!: i64", e.season_id AS "season_id!: i64", e.number AS "number!: i64", e.title AS "title!: String", e.air_date, e.wanted AS "wanted!: bool", e.state AS "state!: String", e.search_attempts AS "search_attempts!: i64", e.last_searched_at FROM episodes e JOIN seasons se ON se.id = e.season_id WHERE e.id = ?"#, id ) .fetch_optional(pool(state)?) .await? .ok_or(ApiError::EpisodeNotFound)?; Ok(Episode { id: row.id, season_id: row.season_id, number: row.number, title: row.title, air_date: row.air_date, wanted: row.wanted, state: row.state, search_attempts: row.search_attempts, last_searched_at: row.last_searched_at, }) } #[utoipa::path( get, path = "/api/episodes/{episode_id}", tag = "series", params(("episode_id" = i64, Path, description = "Episode row id")), responses( (status = 200, body = Episode), (status = 404, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn get_episode( State(state): State, Path(id): Path, ) -> Result, ApiError> { Ok(Json(load_episode(&state, id).await?)) } /// Sets the only intent the TV aggregate carries (§4.1). #[utoipa::path( patch, path = "/api/episodes/{episode_id}", tag = "series", request_body = UpdateEpisode, params(("episode_id" = i64, Path, description = "Episode row id")), responses( (status = 200, body = Episode), (status = 404, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn update_episode( State(state): State, Path(id): Path, Json(input): Json, ) -> Result, ApiError> { load_episode(&state, id).await?; if let Some(wanted) = input.wanted { sqlx::query!( "UPDATE episodes SET wanted = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%fZ', 'now') WHERE id = ?", wanted, id ) .execute(pool(&state)?) .await?; } Ok(Json(load_episode(&state, id).await?)) } #[utoipa::path( post, path = "/api/episodes/{episode_id}/search", tag = "series", params(("episode_id" = i64, Path, description = "Episode 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_episode( State(state): State, Path(id): Path, ) -> Result<(StatusCode, Json), ApiError> { load_episode(&state, id).await?; // §6.3. `blocked` stops targeted search for the whole series. let blocked = sqlx::query_scalar!( r#"SELECT s.blocked AS "blocked!: bool" FROM episodes e JOIN seasons se ON se.id = e.season_id JOIN series s ON s.id = se.series_id WHERE e.id = ?"#, id ) .fetch_one(pool(&state)?) .await?; if blocked { return Err(ApiError::Conflict("series is blocked".into())); } state .send_episode_command(EpisodeCommand::Search { episode_id: id }) .map_err(|_| ApiError::Unavailable)?; Ok((StatusCode::ACCEPTED, Json(Accepted { accepted: true }))) } #[utoipa::path( get, path = "/api/episodes/{episode_id}/releases", tag = "series", params(("episode_id" = i64, Path, description = "Episode row id")), responses( (status = 200, body = [Release]), (status = 404, body = ErrorBody), (status = 500, body = ErrorBody), (status = 503, body = ErrorBody) ) )] pub async fn episode_releases( State(state): State, Path(id): Path, ) -> Result>, ApiError> { load_episode(&state, id).await?; let mut 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 episode_releases er ON er.release_id = r.id WHERE er.episode_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?; let policy = state .database() .ok_or(ApiError::Unavailable)? .episode_policy(id) .await .map_err(|error| ApiError::Database(error.to_string()))? .ok_or(ApiError::EpisodeNotFound)? .policy; rescore(&mut releases, &policy)?; Ok(Json(releases)) } #[utoipa::path( post, path = "/api/episodes/{episode_id}/releases/{release_id}/grab", tag = "series", params(("episode_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_episode( State(state): State, Path((episode_id, release_id)): Path<(i64, i64)>, ) -> Result<(StatusCode, Json), ApiError> { let exists = sqlx::query_scalar!("SELECT EXISTS(SELECT 1 FROM episode_releases WHERE episode_id = ? AND release_id = ?) AS 'exists!: bool'", episode_id, release_id) .fetch_one(pool(&state)?) .await?; if !exists { return Err(ApiError::EpisodeNotFound); } state .send_episode_command(EpisodeCommand::Grab { episode_id, release_id, }) .map_err(|_| ApiError::Unavailable)?; Ok((StatusCode::ACCEPTED, Json(Accepted { accepted: true }))) } #[utoipa::path( get, path = "/api/series/{series_id}/owners", tag = "series", params(("series_id" = i64, Path, description = "Series 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, Path(id): Path, ) -> Result>, ApiError> { load_series_row(&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 = 'series' AND t.title_id = ? ORDER BY o.name"#, id ) .fetch_all(pool(&state)?) .await?; Ok(Json(owners)) } #[utoipa::path( put, path = "/api/series/{series_id}/owners/{owner_id}", tag = "series", params(("series_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, Path((series_id, owner_id)): Path<(i64, i64)>, ) -> Result { load_series_row(&state, series_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 ('series', ?, ?) ON CONFLICT DO NOTHING", series_id, owner_id ) .execute(pool(&state)?) .await?; Ok(StatusCode::NO_CONTENT) } #[utoipa::path( delete, path = "/api/series/{series_id}/owners/{owner_id}", tag = "series", params(("series_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, Path((series_id, owner_id)): Path<(i64, i64)>, ) -> Result { load_series_row(&state, series_id).await?; sqlx::query!( "DELETE FROM title_owners WHERE title_kind = 'series' AND title_id = ? AND owner_id = ?", series_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 tv_root(state: &AppState, audience: &str) -> i64 { sqlx::query_scalar("SELECT id FROM roots WHERE kind = 'tv' AND audience = ?") .bind(audience) .fetch_one(state.database().expect("database").pool()) .await .expect("TV root") } async fn add_series(base: &str, root_id: i64, auto_track: bool) -> serde_json::Value { let response = reqwest::Client::new() .post(format!("{base}/api/series")) .json(&serde_json::json!({ "tmdb_id": 82_728, "title": "Bluey", "year": 2018, "original_language": "en", "root_id": root_id, "auto_track": auto_track })) .send() .await .expect("create series"); assert_eq!(response.status(), StatusCode::CREATED); response.json().await.expect("series json") } async fn add_season( base: &str, series_id: i64, number: i64, episodes: serde_json::Value, ) -> serde_json::Value { let response = reqwest::Client::new() .post(format!("{base}/api/series/{series_id}/seasons")) .json(&serde_json::json!({ "number": number, "episodes": episodes })) .send() .await .expect("create season"); assert_eq!(response.status(), StatusCode::CREATED); response.json().await.expect("season json") } #[tokio::test] async fn series_must_sit_on_a_tv_root() { let (_dir, state, base) = application().await; let movie_root: i64 = sqlx::query_scalar("SELECT id FROM roots WHERE kind = 'movie' LIMIT 1") .fetch_one(state.database().expect("database").pool()) .await .expect("movie root"); let response = reqwest::Client::new() .post(format!("{base}/api/series")) .json(&serde_json::json!({ "tmdb_id": 82_728, "title": "Bluey", "root_id": movie_root })) .send() .await .expect("create series"); assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); } #[tokio::test] async fn auto_track_decides_whether_a_new_season_arrives_wanted() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "kids").await; let tracked = add_series(&base, root_id, true).await; let season = add_season( &base, tracked["id"].as_i64().expect("id"), 1, serde_json::json!([ {"number": 1, "title": "The Magic Xylophone", "air_date": "2018-10-01"}, {"number": 2, "title": "Hospital", "air_date": "2018-10-02"} ]), ) .await; assert_eq!(season["tracked"], true); assert!( season["episodes"] .as_array() .expect("episodes") .iter() .all(|episode| episode["wanted"] == true), "§4.1: auto_track marks the episodes of a revealed season wanted" ); let untracked_id = sqlx::query_scalar::<_, i64>( "INSERT INTO series (tmdb_id, title, root_id, auto_track) VALUES (1668, 'Friends', ?, 0) RETURNING id", ) .bind(root_id) .fetch_one(state.database().expect("database").pool()) .await .expect("untracked series"); let season = add_season( &base, untracked_id, 2, serde_json::json!([{"number": 1, "title": "The One", "air_date": "1995-09-21"}]), ) .await; assert_eq!(season["tracked"], false); assert_eq!(season["episodes"][0]["wanted"], false); } #[tokio::test] async fn a_rejected_season_leaves_nothing_behind_to_retry_over() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "main").await; let series = add_series(&base, root_id, false).await; let series_id = series["id"].as_i64().expect("id"); let response = reqwest::Client::new() .post(format!("{base}/api/series/{series_id}/seasons")) .json(&serde_json::json!({"number": 1, "episodes": [ {"number": 1, "title": "One"}, {"number": 1, "title": "One again"} ]})) .send() .await .expect("create season"); assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY); let seasons: i64 = sqlx::query_scalar("SELECT count(*) FROM seasons") .fetch_one(state.database().expect("database").pool()) .await .expect("count seasons"); assert_eq!(seasons, 0, "the season number stays free for the retry"); let season = add_season( &base, series_id, 1, serde_json::json!([{"number": 1, "title": "One"}]), ) .await; assert_eq!(season["number"], 1); } #[tokio::test] async fn intent_is_set_on_seasons_and_on_single_episodes() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "main").await; let series = add_series(&base, root_id, false).await; let series_id = series["id"].as_i64().expect("id"); let season = add_season( &base, series_id, 2, serde_json::json!([ {"number": 1, "title": "One", "air_date": "2020-01-01"}, {"number": 2, "title": "Two", "air_date": "2020-01-08"} ]), ) .await; assert_eq!(season["episodes"][0]["wanted"], false); // The whole season, in one click. let updated: serde_json::Value = reqwest::Client::new() .patch(format!("{base}/api/series/{series_id}/seasons/2")) .json(&serde_json::json!({"wanted": true})) .send() .await .expect("update season") .json() .await .expect("season json"); assert!(updated["episodes"] .as_array() .expect("episodes") .iter() .all(|episode| episode["wanted"] == true)); assert_eq!( updated["tracked"], false, "§4.1: wanting a season is not tracking the series" ); // And one episode on its own. let episode_id = updated["episodes"][1]["id"].as_i64().expect("episode id"); let episode: serde_json::Value = reqwest::Client::new() .patch(format!("{base}/api/episodes/{episode_id}")) .json(&serde_json::json!({"wanted": false})) .send() .await .expect("update episode") .json() .await .expect("episode json"); assert_eq!(episode["wanted"], false); } #[tokio::test] async fn listed_series_carry_a_derived_status() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "main").await; let series = add_series(&base, root_id, false).await; let series_id = series["id"].as_i64().expect("id"); assert_eq!( series["status"], "complete", "nothing wanted is nothing missing" ); let season = add_season( &base, series_id, 1, serde_json::json!([{"number": 1, "title": "Pilot", "air_date": "2001-01-01"}]), ) .await; let episode_id = season["episodes"][0]["id"].as_i64().expect("episode id"); reqwest::Client::new() .patch(format!("{base}/api/episodes/{episode_id}")) .json(&serde_json::json!({"wanted": true})) .send() .await .expect("want the episode"); let listed: Vec = reqwest::get(format!("{base}/api/series")) .await .expect("list") .json() .await .expect("list json"); assert_eq!(listed.len(), 1); assert_eq!( listed[0]["status"], "incomplete", "§4.2: an aired wanted episode with no file" ); assert_eq!(listed[0]["wanted_episodes"], 1); assert_eq!(listed[0]["available_episodes"], 0); sqlx::query("UPDATE episodes SET state = 'available' WHERE id = ?") .bind(episode_id) .execute(state.database().expect("database").pool()) .await .expect("import the episode"); let after: serde_json::Value = reqwest::get(format!("{base}/api/series/{series_id}")) .await .expect("get") .json() .await .expect("series json"); assert_eq!(after["status"], "complete"); } #[tokio::test] async fn manual_episode_actions_are_scoped_and_respect_blocked() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "main").await; let series = add_series(&base, root_id, false).await; let series_id = series["id"].as_i64().expect("id"); let season = add_season( &base, series_id, 1, serde_json::json!([{"number": 1, "title": "Pilot", "air_date": "2001-01-01"}]), ) .await; let episode_id = season["episodes"][0]["id"].as_i64().expect("episode id"); let response = reqwest::Client::new() .post(format!("{base}/api/episodes/{episode_id}/search")) .send() .await .expect("search"); assert_eq!(response.status(), StatusCode::ACCEPTED); assert_eq!( state.next_episode_command().await.expect("command"), EpisodeCommand::Search { episode_id } ); let pool = state.database().expect("database").pool(); let release_id = sqlx::query_scalar::<_, i64>("INSERT INTO releases (indexer_id, guid, name, size, download_url, parsed, score, verdict) VALUES (7, 'guid', 'Bluey S01E01 1080p WEB-DL', 1000, 'url', '{}', 42, 'eligible') RETURNING id") .fetch_one(pool) .await .expect("release"); sqlx::query("INSERT INTO episode_releases (episode_id, release_id) VALUES (?, ?)") .bind(episode_id) .bind(release_id) .execute(pool) .await .expect("association"); let releases: Vec = reqwest::get(format!("{base}/api/episodes/{episode_id}/releases")) .await .expect("releases") .json() .await .expect("releases json"); assert_eq!(releases[0]["verdict"], "eligible"); let response = reqwest::Client::new() .post(format!( "{base}/api/episodes/{episode_id}/releases/{release_id}/grab" )) .send() .await .expect("grab"); assert_eq!(response.status(), StatusCode::ACCEPTED); assert_eq!( state.next_episode_command().await.expect("command"), EpisodeCommand::Grab { episode_id, release_id } ); // A release belonging to another episode is not grabbable through // this one. let other = sqlx::query_scalar::<_, i64>("INSERT INTO releases (indexer_id, guid, name, size, download_url, parsed, verdict) VALUES (7, 'other', 'other', 1, 'url', '{}', 'eligible') RETURNING id") .fetch_one(pool) .await .expect("other release"); let response = reqwest::Client::new() .post(format!( "{base}/api/episodes/{episode_id}/releases/{other}/grab" )) .send() .await .expect("grab"); assert_eq!(response.status(), StatusCode::NOT_FOUND); reqwest::Client::new() .patch(format!("{base}/api/series/{series_id}")) .json(&serde_json::json!({"blocked": true})) .send() .await .expect("block the series"); let response = reqwest::Client::new() .post(format!("{base}/api/episodes/{episode_id}/search")) .send() .await .expect("blocked search"); assert_eq!(response.status(), StatusCode::CONFLICT); } #[tokio::test] async fn owner_tags_filter_the_series_list() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "kids").await; let series = add_series(&base, root_id, true).await; let series_id = series["id"].as_i64().expect("id"); let owner_id = sqlx::query_scalar::<_, i64>( "INSERT INTO owners (name, ntfy_topic) VALUES ('kid', 'arr-kid') RETURNING id", ) .fetch_one(state.database().expect("database").pool()) .await .expect("owner"); let empty: Vec = reqwest::get(format!("{base}/api/series?owner_id={owner_id}")) .await .expect("filtered list") .json() .await .expect("json"); assert!(empty.is_empty()); let tagged = reqwest::Client::new() .put(format!("{base}/api/series/{series_id}/owners/{owner_id}")) .send() .await .expect("tag"); assert_eq!(tagged.status(), StatusCode::NO_CONTENT); let filtered: Vec = reqwest::get(format!("{base}/api/series?owner_id={owner_id}")) .await .expect("filtered list") .json() .await .expect("json"); assert_eq!(filtered.len(), 1); assert_eq!(filtered[0]["id"], series_id); let owners: Vec = reqwest::get(format!("{base}/api/series/{series_id}/owners")) .await .expect("owners") .json() .await .expect("json"); assert_eq!(owners.len(), 1); reqwest::Client::new() .delete(format!("{base}/api/series/{series_id}/owners/{owner_id}")) .send() .await .expect("untag"); let owners: Vec = reqwest::get(format!("{base}/api/series/{series_id}/owners")) .await .expect("owners") .json() .await .expect("json"); assert!(owners.is_empty()); } #[tokio::test] async fn deleting_a_series_takes_its_seasons_and_episodes() { let (_dir, state, base) = application().await; let root_id = tv_root(&state, "main").await; let series = add_series(&base, root_id, true).await; let series_id = series["id"].as_i64().expect("id"); add_season( &base, series_id, 1, serde_json::json!([{"number": 1, "title": "Pilot", "air_date": "2001-01-01"}]), ) .await; let response = reqwest::Client::new() .delete(format!("{base}/api/series/{series_id}")) .send() .await .expect("delete"); assert_eq!(response.status(), StatusCode::NO_CONTENT); let episodes: i64 = sqlx::query_scalar("SELECT count(*) FROM episodes") .fetch_one(state.database().expect("database").pool()) .await .expect("count episodes"); assert_eq!(episodes, 0); } #[test] fn air_dates_parse_as_dates_and_as_timestamps() { assert_eq!( air_date(Some("1970-01-02")), Some(UNIX_EPOCH + Duration::from_hours(24)) ); assert_eq!( air_date(Some("1970-01-02T00:00:00Z")), Some(UNIX_EPOCH + Duration::from_hours(24)) ); assert_eq!(air_date(Some("not a date")), None); assert_eq!(air_date(None), None); } }