571 lines
17 KiB
Rust
571 lines
17 KiB
Rust
//! Sonarr API client library
|
|
//!
|
|
//! This crate provides a Rust client for the Sonarr API, allowing you to interact
|
|
//! with Sonarr instances programmatically.
|
|
|
|
pub mod error;
|
|
|
|
pub use error::{ApiError, Result};
|
|
|
|
use reqwest::Client;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::collections::HashMap;
|
|
|
|
#[derive(Clone)]
|
|
pub struct SonarrClient {
|
|
client: Client,
|
|
base_url: String,
|
|
api_key: String,
|
|
}
|
|
|
|
impl SonarrClient {
|
|
pub fn new(base_url: String, api_key: String) -> Self {
|
|
Self {
|
|
client: Client::new(),
|
|
base_url: base_url.trim_end_matches('/').to_string(),
|
|
api_key,
|
|
}
|
|
}
|
|
|
|
async fn get<T: for<'de> Deserialize<'de>>(&self, endpoint: &str) -> Result<T, ApiError> {
|
|
let url = format!("{}/api/v3{}", self.base_url, endpoint);
|
|
let response = self
|
|
.client
|
|
.get(&url)
|
|
.header("X-Api-Key", &self.api_key)
|
|
.send()
|
|
.await?;
|
|
|
|
if !response.status().is_success() {
|
|
let status = response.status();
|
|
let error_text = response
|
|
.text()
|
|
.await
|
|
.unwrap_or_else(|_| "Unknown error".to_string());
|
|
return Err(ApiError::Generic {
|
|
message: format!("HTTP {}: {}", status, error_text),
|
|
});
|
|
}
|
|
|
|
let text = response.text().await?;
|
|
let result: T = serde_json::from_str(&text)?;
|
|
Ok(result)
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
async fn get_debug<T: for<'de> Deserialize<'de>>(&self, endpoint: &str) -> Result<T, ApiError> {
|
|
let url = format!("{}/api/v3{}", self.base_url, endpoint);
|
|
let response = self
|
|
.client
|
|
.get(&url)
|
|
.header("X-Api-Key", &self.api_key)
|
|
.send()
|
|
.await?;
|
|
|
|
if !response.status().is_success() {
|
|
let status = response.status();
|
|
let error_text = response
|
|
.text()
|
|
.await
|
|
.unwrap_or_else(|_| "Unknown error".to_string());
|
|
return Err(ApiError::Generic {
|
|
message: format!("Debug HTTP {}: {}", status, error_text),
|
|
});
|
|
}
|
|
|
|
let text = response.text().await?;
|
|
let _ = std::fs::write(endpoint.replace("/", "_"), &text);
|
|
let result: T = serde_json::from_str(&text)?;
|
|
Ok(result)
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
async fn post<T: Serialize, R: for<'de> Deserialize<'de>>(
|
|
&self,
|
|
endpoint: &str,
|
|
body: &T,
|
|
) -> Result<R, ApiError> {
|
|
let url = format!("{}/api/v3{}", self.base_url, endpoint);
|
|
let response = self
|
|
.client
|
|
.post(&url)
|
|
.header("X-Api-Key", &self.api_key)
|
|
.json(body)
|
|
.send()
|
|
.await?;
|
|
|
|
if !response.status().is_success() {
|
|
let status = response.status();
|
|
let error_text = response
|
|
.text()
|
|
.await
|
|
.unwrap_or_else(|_| "Unknown error".to_string());
|
|
return Err(ApiError::Generic {
|
|
message: format!("POST HTTP {}: {}", status, error_text),
|
|
});
|
|
}
|
|
|
|
let text = response.text().await?;
|
|
let result: R = serde_json::from_str(&text)?;
|
|
Ok(result)
|
|
}
|
|
|
|
pub async fn get_system_status(&self) -> Result<SystemStatus, ApiError> {
|
|
self.get("/system/status").await
|
|
}
|
|
|
|
pub async fn get_series(&self) -> Result<Vec<Series>, ApiError> {
|
|
self.get("/series").await
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub async fn get_series_by_id(&self, id: u32) -> Result<Series, ApiError> {
|
|
self.get(&format!("/series/{}", id)).await
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub async fn get_episodes(
|
|
&self,
|
|
series_id: Option<u32>,
|
|
season_number: Option<u32>,
|
|
) -> Result<Vec<Episode>, ApiError> {
|
|
let mut query = Vec::new();
|
|
if let Some(id) = series_id {
|
|
query.push(format!("seriesId={}", id));
|
|
}
|
|
if let Some(season) = season_number {
|
|
query.push(format!("seasonNumber={}", season));
|
|
}
|
|
|
|
let query_string = if query.is_empty() {
|
|
String::new()
|
|
} else {
|
|
format!("?{}", query.join("&"))
|
|
};
|
|
|
|
self.get(&format!("/episode{}", query_string)).await
|
|
}
|
|
|
|
pub async fn get_calendar(
|
|
&self,
|
|
start: Option<&str>,
|
|
end: Option<&str>,
|
|
) -> Result<Vec<Episode>, ApiError> {
|
|
let mut query = Vec::new();
|
|
if let Some(start_date) = start {
|
|
query.push(format!("start={}", start_date));
|
|
}
|
|
if let Some(end_date) = end {
|
|
query.push(format!("end={}", end_date));
|
|
}
|
|
|
|
let query_string = if query.is_empty() {
|
|
String::new()
|
|
} else {
|
|
format!("?{}", query.join("&"))
|
|
};
|
|
|
|
self.get(&format!("/calendar{}", query_string)).await
|
|
}
|
|
|
|
pub async fn get_queue(&self) -> Result<QueuePagingResource, ApiError> {
|
|
self.get("/queue").await
|
|
}
|
|
|
|
pub async fn get_history(&self) -> Result<HistoryPagingResource, ApiError> {
|
|
self.get("/history").await
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub async fn get_missing_episodes(&self) -> Result<EpisodePagingResource, ApiError> {
|
|
self.get("/wanted/missing").await
|
|
}
|
|
|
|
pub async fn get_health(&self) -> Result<Vec<HealthResource>, ApiError> {
|
|
self.get("/health").await
|
|
}
|
|
|
|
pub async fn search_series(&self, term: &str) -> Result<Vec<Series>, ApiError> {
|
|
self.get(&format!(
|
|
"/series/lookup?term={}",
|
|
urlencoding::encode(term)
|
|
))
|
|
.await
|
|
}
|
|
|
|
#[allow(dead_code)]
|
|
pub async fn add_series(&self, series: &Series) -> Result<Series, ApiError> {
|
|
self.post("/series", series).await
|
|
}
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct SystemStatus {
|
|
pub app_name: Option<String>,
|
|
pub instance_name: Option<String>,
|
|
pub version: Option<String>,
|
|
pub build_time: chrono::DateTime<chrono::Utc>,
|
|
pub is_debug: bool,
|
|
pub is_production: bool,
|
|
pub is_admin: bool,
|
|
pub is_user_interactive: bool,
|
|
pub startup_path: Option<String>,
|
|
pub app_data: Option<String>,
|
|
pub os_name: Option<String>,
|
|
pub os_version: Option<String>,
|
|
pub is_net_core: bool,
|
|
pub is_linux: bool,
|
|
pub is_osx: bool,
|
|
pub is_windows: bool,
|
|
pub is_docker: bool,
|
|
pub mode: String,
|
|
pub branch: Option<String>,
|
|
pub authentication: String,
|
|
pub sqlite_version: Option<String>,
|
|
pub migration_version: i32,
|
|
pub url_base: Option<String>,
|
|
pub runtime_version: Option<String>,
|
|
pub runtime_name: Option<String>,
|
|
pub start_time: chrono::DateTime<chrono::Utc>,
|
|
pub package_version: Option<String>,
|
|
pub package_author: Option<String>,
|
|
pub package_update_mechanism: String,
|
|
pub package_update_mechanism_message: Option<String>,
|
|
pub database_version: Option<String>,
|
|
pub database_type: String,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Series {
|
|
pub id: Option<u32>,
|
|
pub title: Option<String>,
|
|
pub alternate_titles: Option<Vec<AlternateTitle>>,
|
|
pub sort_title: Option<String>,
|
|
pub status: String,
|
|
pub ended: Option<bool>,
|
|
pub profile_name: Option<String>,
|
|
pub overview: Option<String>,
|
|
pub next_airing: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub previous_airing: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub network: Option<String>,
|
|
pub air_time: Option<String>,
|
|
pub images: Option<Vec<MediaCover>>,
|
|
pub original_language: Option<Language>,
|
|
pub remote_poster: Option<String>,
|
|
pub seasons: Option<Vec<Season>>,
|
|
pub year: u32,
|
|
pub path: Option<String>,
|
|
pub quality_profile_id: u32,
|
|
pub season_folder: bool,
|
|
pub monitored: bool,
|
|
pub monitor_new_items: String,
|
|
pub use_scene_numbering: bool,
|
|
pub runtime: u32,
|
|
pub tvdb_id: u32,
|
|
pub tv_rage_id: u32,
|
|
pub tv_maze_id: u32,
|
|
pub tmdb_id: u32,
|
|
pub first_aired: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub last_aired: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub series_type: String,
|
|
pub clean_title: Option<String>,
|
|
pub imdb_id: Option<String>,
|
|
pub title_slug: Option<String>,
|
|
pub root_folder_path: Option<String>,
|
|
pub folder: Option<String>,
|
|
pub certification: Option<String>,
|
|
pub genres: Option<Vec<String>>,
|
|
pub tags: Option<Vec<u32>>,
|
|
pub added: chrono::DateTime<chrono::Utc>,
|
|
pub add_options: Option<AddSeriesOptions>,
|
|
pub ratings: Option<Ratings>,
|
|
pub statistics: Option<SeriesStatistics>,
|
|
pub episodes_changed: Option<bool>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct AlternateTitle {
|
|
pub title: Option<String>,
|
|
pub season_number: Option<i32>,
|
|
pub scene_season_number: Option<i32>,
|
|
pub scene_origin: Option<String>,
|
|
pub comment: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct MediaCover {
|
|
pub cover_type: String,
|
|
pub url: Option<String>,
|
|
pub remote_url: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Language {
|
|
pub id: u32,
|
|
pub name: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Season {
|
|
pub season_number: i32,
|
|
pub monitored: bool,
|
|
pub statistics: Option<SeasonStatistics>,
|
|
pub images: Option<Vec<MediaCover>>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct AddSeriesOptions {
|
|
pub ignore_episodes_with_files: bool,
|
|
pub ignore_episodes_without_files: bool,
|
|
pub monitor: String,
|
|
pub search_for_missing_episodes: bool,
|
|
pub search_for_cutoff_unmet_episodes: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Ratings {
|
|
pub votes: i32,
|
|
pub value: f64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct SeriesStatistics {
|
|
pub season_count: i32,
|
|
pub episode_file_count: i32,
|
|
pub episode_count: i32,
|
|
pub total_episode_count: i32,
|
|
pub size_on_disk: i64,
|
|
pub release_groups: Option<Vec<String>>,
|
|
pub percent_of_episodes: f64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct SeasonStatistics {
|
|
pub next_airing: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub previous_airing: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub episode_file_count: i32,
|
|
pub episode_count: i32,
|
|
pub total_episode_count: i32,
|
|
pub size_on_disk: i64,
|
|
pub release_groups: Option<Vec<String>>,
|
|
pub percent_of_episodes: f64,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Episode {
|
|
pub id: u32,
|
|
pub series_id: u32,
|
|
pub tvdb_id: u32,
|
|
pub episode_file_id: u32,
|
|
pub season_number: i32,
|
|
pub episode_number: i32,
|
|
pub title: Option<String>,
|
|
pub air_date: Option<String>,
|
|
pub air_date_utc: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub last_search_time: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub runtime: i32,
|
|
pub finale_type: Option<String>,
|
|
pub overview: Option<String>,
|
|
pub episode_file: Option<EpisodeFile>,
|
|
pub has_file: bool,
|
|
pub monitored: bool,
|
|
pub absolute_episode_number: Option<i32>,
|
|
pub scene_absolute_episode_number: Option<i32>,
|
|
pub scene_episode_number: Option<i32>,
|
|
pub scene_season_number: Option<i32>,
|
|
pub unverified_scene_numbering: bool,
|
|
pub end_time: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub grab_date: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub series: Option<Series>,
|
|
pub images: Option<Vec<MediaCover>>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct EpisodeFile {
|
|
pub id: u32,
|
|
pub series_id: u32,
|
|
pub season_number: i32,
|
|
pub relative_path: Option<String>,
|
|
pub path: Option<String>,
|
|
pub size: i64,
|
|
pub date_added: chrono::DateTime<chrono::Utc>,
|
|
pub scene_name: Option<String>,
|
|
pub release_group: Option<String>,
|
|
pub languages: Option<Vec<Language>>,
|
|
pub quality: Option<Quality>,
|
|
pub custom_formats: Option<Vec<CustomFormat>>,
|
|
pub custom_format_score: i32,
|
|
pub indexer_flags: Option<i32>,
|
|
pub release_type: Option<String>,
|
|
pub media_info: Option<MediaInfo>,
|
|
pub quality_cutoff_not_met: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Quality {
|
|
pub quality: QualityDefinition,
|
|
pub revision: Revision,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct QualityDefinition {
|
|
pub id: u32,
|
|
pub name: Option<String>,
|
|
pub source: String,
|
|
pub resolution: i32,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct Revision {
|
|
pub version: i32,
|
|
pub real: i32,
|
|
pub is_repack: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct CustomFormat {
|
|
pub id: u32,
|
|
pub name: Option<String>,
|
|
pub include_custom_format_when_renaming: Option<bool>,
|
|
pub specifications: Option<Vec<HashMap<String, serde_json::Value>>>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct MediaInfo {
|
|
pub id: u32,
|
|
pub audio_bitrate: i64,
|
|
pub audio_channels: f64,
|
|
pub audio_codec: Option<String>,
|
|
pub audio_languages: Option<String>,
|
|
pub audio_stream_count: i32,
|
|
pub video_bit_depth: i32,
|
|
pub video_bitrate: i64,
|
|
pub video_codec: Option<String>,
|
|
pub video_fps: f64,
|
|
pub video_dynamic_range: Option<String>,
|
|
pub video_dynamic_range_type: Option<String>,
|
|
pub resolution: Option<String>,
|
|
pub run_time: Option<String>,
|
|
pub scan_type: Option<String>,
|
|
pub subtitles: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct QueuePagingResource {
|
|
pub page: i32,
|
|
pub page_size: i32,
|
|
pub sort_key: Option<String>,
|
|
pub sort_direction: String,
|
|
pub total_records: i32,
|
|
pub records: Vec<QueueItem>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct QueueItem {
|
|
pub id: u32,
|
|
pub series_id: Option<u32>,
|
|
pub episode_id: Option<u32>,
|
|
pub season_number: Option<i32>,
|
|
pub series: Option<Series>,
|
|
pub episode: Option<Episode>,
|
|
pub languages: Option<Vec<Language>>,
|
|
pub quality: Option<Quality>,
|
|
pub custom_formats: Option<Vec<CustomFormat>>,
|
|
pub custom_format_score: i32,
|
|
pub size: f64,
|
|
pub title: Option<String>,
|
|
pub estimated_completion_time: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub added: Option<chrono::DateTime<chrono::Utc>>,
|
|
pub status: String,
|
|
pub tracked_download_status: Option<String>,
|
|
pub tracked_download_state: Option<String>,
|
|
pub status_messages: Option<Vec<StatusMessage>>,
|
|
pub error_message: Option<String>,
|
|
pub download_id: Option<String>,
|
|
pub protocol: String,
|
|
pub download_client: Option<String>,
|
|
pub download_client_has_post_import_category: bool,
|
|
pub indexer: Option<String>,
|
|
pub output_path: Option<String>,
|
|
pub episode_has_file: bool,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct StatusMessage {
|
|
pub title: Option<String>,
|
|
pub messages: Option<Vec<String>>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct HistoryPagingResource {
|
|
pub page: i32,
|
|
pub page_size: i32,
|
|
pub sort_key: Option<String>,
|
|
pub sort_direction: String,
|
|
pub total_records: i32,
|
|
pub records: Vec<HistoryItem>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct HistoryItem {
|
|
pub id: u32,
|
|
pub episode_id: u32,
|
|
pub series_id: u32,
|
|
pub source_title: Option<String>,
|
|
pub languages: Option<Vec<Language>>,
|
|
pub quality: Option<Quality>,
|
|
pub custom_formats: Option<Vec<CustomFormat>>,
|
|
pub custom_format_score: i32,
|
|
pub quality_cutoff_not_met: bool,
|
|
pub date: chrono::DateTime<chrono::Utc>,
|
|
pub download_id: Option<String>,
|
|
pub event_type: Option<String>,
|
|
pub data: Option<HashMap<String, Option<String>>>,
|
|
pub episode: Option<Episode>,
|
|
pub series: Option<Series>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct EpisodePagingResource {
|
|
pub page: i32,
|
|
pub page_size: i32,
|
|
pub sort_key: Option<String>,
|
|
pub sort_direction: String,
|
|
pub total_records: i32,
|
|
pub records: Vec<Episode>,
|
|
}
|
|
|
|
#[derive(Debug, Clone, Deserialize, Serialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
pub struct HealthResource {
|
|
pub id: Option<i32>,
|
|
pub source: Option<String>,
|
|
#[serde(rename = "type")]
|
|
pub health_type: String,
|
|
pub message: Option<String>,
|
|
pub wiki_url: Option<String>,
|
|
}
|