1 parent
f47217d5a3
commit
8ceb3c8be8
60 files changed
+10884
No files matched your search
@@ -0,0 +1,425 @@
|
||||
//! A thin, typed client for the handful of Jellyfin endpoints jellymove needs.
|
||||
//!
|
||||
//! Written against Jellyfin 10.9+ (including the v12 line). Routes for user
|
||||
//! data moved in 10.9 (`/UserItems/...`); check against your server's
|
||||
//! `/api-docs/openapi.json` if something returns 404.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::time::Duration;
|
||||
|
||||
use reqwest::header::{AUTHORIZATION, HeaderMap, HeaderValue};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub use jm_core::userdata::UserData;
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum JellyfinError {
|
||||
#[error("could not reach Jellyfin: {0}")]
|
||||
Http(#[from] reqwest::Error),
|
||||
#[error("Jellyfin returned HTTP {status} for {path}")]
|
||||
Status { status: u16, path: String },
|
||||
#[error("invalid Jellyfin URL: {0}")]
|
||||
BadUrl(String),
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, JellyfinError>;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Client {
|
||||
base: String,
|
||||
http: reqwest::Client,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct SystemInfo {
|
||||
pub server_name: String,
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct VirtualFolder {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub locations: Vec<String>,
|
||||
#[serde(default)]
|
||||
pub collection_type: Option<String>,
|
||||
#[serde(default)]
|
||||
pub item_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct MediaSource {
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct ItemUserData {
|
||||
#[serde(default)]
|
||||
pub played: bool,
|
||||
#[serde(default)]
|
||||
pub play_count: i32,
|
||||
#[serde(default)]
|
||||
pub is_favorite: bool,
|
||||
#[serde(default)]
|
||||
pub playback_position_ticks: i64,
|
||||
#[serde(default)]
|
||||
pub last_played_date: Option<String>,
|
||||
}
|
||||
|
||||
impl From<ItemUserData> for UserData {
|
||||
fn from(u: ItemUserData) -> Self {
|
||||
UserData {
|
||||
played: u.played,
|
||||
play_count: u.play_count,
|
||||
is_favorite: u.is_favorite,
|
||||
playback_position_ticks: u.playback_position_ticks,
|
||||
last_played_date: u.last_played_date,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct Item {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
#[serde(rename = "Type")]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub production_year: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub provider_ids: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub media_sources: Option<Vec<MediaSource>>,
|
||||
/// Season number for episodes.
|
||||
#[serde(default)]
|
||||
pub parent_index_number: Option<i32>,
|
||||
/// Episode number for episodes.
|
||||
#[serde(default)]
|
||||
pub index_number: Option<i32>,
|
||||
#[serde(default)]
|
||||
pub user_data: Option<ItemUserData>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct ItemsPage {
|
||||
#[serde(default)]
|
||||
items: Vec<Item>,
|
||||
#[serde(default)]
|
||||
total_record_count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
pub struct User {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
/// Query for `GET /Items`.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ItemQuery<'a> {
|
||||
pub ids: Option<&'a str>,
|
||||
pub parent_id: Option<&'a str>,
|
||||
pub include_types: &'a [&'a str],
|
||||
pub recursive: bool,
|
||||
pub search: Option<&'a str>,
|
||||
/// Ask for this user's watch state alongside each item.
|
||||
pub user_id: Option<&'a str>,
|
||||
}
|
||||
|
||||
const FIELDS: &str = "Path,ProviderIds,MediaSources,ProductionYear";
|
||||
const PAGE: usize = 500;
|
||||
|
||||
impl Client {
|
||||
pub fn new(base_url: &str, api_key: &str) -> Result<Self> {
|
||||
let base = base_url.trim_end_matches('/').to_string();
|
||||
if !(base.starts_with("http://") || base.starts_with("https://")) {
|
||||
return Err(JellyfinError::BadUrl(base_url.to_string()));
|
||||
}
|
||||
let mut headers = HeaderMap::new();
|
||||
let auth = format!(
|
||||
r#"MediaBrowser Client="jellymove", Device="jellymove", DeviceId="jellymove", Version="{}", Token="{}""#,
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
api_key
|
||||
);
|
||||
headers.insert(
|
||||
AUTHORIZATION,
|
||||
HeaderValue::from_str(&auth).map_err(|_| JellyfinError::BadUrl("api key".into()))?,
|
||||
);
|
||||
let http = reqwest::Client::builder()
|
||||
.default_headers(headers)
|
||||
.timeout(Duration::from_secs(60))
|
||||
.build()?;
|
||||
Ok(Self { base, http })
|
||||
}
|
||||
|
||||
async fn get<T: for<'de> Deserialize<'de>>(
|
||||
&self,
|
||||
path: &str,
|
||||
query: &[(&str, String)],
|
||||
) -> Result<T> {
|
||||
let resp = self
|
||||
.http
|
||||
.get(format!("{}{path}", self.base))
|
||||
.query(query)
|
||||
.send()
|
||||
.await?;
|
||||
check(resp, path).await?.json().await.map_err(Into::into)
|
||||
}
|
||||
|
||||
async fn post_json<B: Serialize>(
|
||||
&self,
|
||||
path: &str,
|
||||
query: &[(&str, String)],
|
||||
body: &B,
|
||||
) -> Result<()> {
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}{path}", self.base))
|
||||
.query(query)
|
||||
.json(body)
|
||||
.send()
|
||||
.await?;
|
||||
check(resp, path).await.map(|_| ())
|
||||
}
|
||||
|
||||
pub async fn system_info(&self) -> Result<SystemInfo> {
|
||||
self.get("/System/Info", &[]).await
|
||||
}
|
||||
|
||||
pub async fn virtual_folders(&self) -> Result<Vec<VirtualFolder>> {
|
||||
self.get("/Library/VirtualFolders", &[]).await
|
||||
}
|
||||
|
||||
pub async fn users(&self) -> Result<Vec<User>> {
|
||||
self.get("/Users", &[]).await
|
||||
}
|
||||
|
||||
pub async fn item(&self, id: &str) -> Result<Item> {
|
||||
let mut items = self
|
||||
.get::<ItemsPage>(
|
||||
"/Items",
|
||||
&[("ids", id.to_string()), ("fields", FIELDS.to_string())],
|
||||
)
|
||||
.await?
|
||||
.items;
|
||||
items.pop().ok_or(JellyfinError::Status {
|
||||
status: 404,
|
||||
path: format!("/Items?ids={id}"),
|
||||
})
|
||||
}
|
||||
|
||||
/// Fetch every item matching `q`, following pagination.
|
||||
pub async fn items(&self, q: &ItemQuery<'_>) -> Result<Vec<Item>> {
|
||||
let mut out = Vec::new();
|
||||
loop {
|
||||
let mut query: Vec<(&str, String)> = vec![
|
||||
("fields", FIELDS.to_string()),
|
||||
("recursive", q.recursive.to_string()),
|
||||
("startIndex", out.len().to_string()),
|
||||
("limit", PAGE.to_string()),
|
||||
("sortBy", "SortName".to_string()),
|
||||
];
|
||||
if let Some(ids) = q.ids {
|
||||
query.push(("ids", ids.to_string()));
|
||||
}
|
||||
if let Some(p) = q.parent_id {
|
||||
query.push(("parentId", p.to_string()));
|
||||
}
|
||||
if !q.include_types.is_empty() {
|
||||
query.push(("includeItemTypes", q.include_types.join(",")));
|
||||
}
|
||||
if let Some(s) = q.search {
|
||||
query.push(("searchTerm", s.to_string()));
|
||||
}
|
||||
if let Some(u) = q.user_id {
|
||||
query.push(("userId", u.to_string()));
|
||||
query.push(("enableUserData", "true".to_string()));
|
||||
}
|
||||
let page: ItemsPage = self.get("/Items", &query).await?;
|
||||
let got = page.items.len();
|
||||
out.extend(page.items);
|
||||
if got < PAGE || out.len() >= page.total_record_count {
|
||||
return Ok(out);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Ask Jellyfin to rescan just these folders. Jellyfin answers 204 even for
|
||||
/// paths outside every library and waits `LibraryMonitorDelay` (60 s by
|
||||
/// default) before scanning, so callers must poll for the result.
|
||||
pub async fn media_updated(&self, paths: &[String]) -> Result<()> {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Update<'a> {
|
||||
path: &'a str,
|
||||
update_type: &'a str,
|
||||
}
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Body<'a> {
|
||||
updates: Vec<Update<'a>>,
|
||||
}
|
||||
let body = Body {
|
||||
updates: paths
|
||||
.iter()
|
||||
.map(|p| Update {
|
||||
path: p,
|
||||
update_type: "Modified",
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
self.post_json("/Library/Media/Updated", &[], &body).await
|
||||
}
|
||||
|
||||
/// Full library scan. A fallback when targeted updates don't take.
|
||||
pub async fn refresh_library(&self) -> Result<()> {
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/Library/Refresh", self.base))
|
||||
.send()
|
||||
.await?;
|
||||
check(resp, "/Library/Refresh").await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Write a user's watch state for an item (Jellyfin 10.9+).
|
||||
pub async fn set_user_data(&self, user_id: &str, item_id: &str, data: &UserData) -> Result<()> {
|
||||
#[derive(Serialize)]
|
||||
#[serde(rename_all = "PascalCase")]
|
||||
struct Dto<'a> {
|
||||
played: bool,
|
||||
play_count: i32,
|
||||
is_favorite: bool,
|
||||
playback_position_ticks: i64,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
last_played_date: Option<&'a str>,
|
||||
}
|
||||
let dto = Dto {
|
||||
played: data.played,
|
||||
play_count: data.play_count,
|
||||
is_favorite: data.is_favorite,
|
||||
playback_position_ticks: data.playback_position_ticks,
|
||||
last_played_date: data.last_played_date.as_deref(),
|
||||
};
|
||||
self.post_json(
|
||||
&format!("/UserItems/{item_id}/UserData"),
|
||||
&[("userId", user_id.to_string())],
|
||||
&dto,
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
async fn check(resp: reqwest::Response, path: &str) -> Result<reqwest::Response> {
|
||||
if resp.status().is_success() {
|
||||
Ok(resp)
|
||||
} else {
|
||||
Err(JellyfinError::Status {
|
||||
status: resp.status().as_u16(),
|
||||
path: path.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use axum::extract::Query;
|
||||
use axum::http::{HeaderMap as AxHeaders, StatusCode};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
async fn mock() -> String {
|
||||
async fn items(
|
||||
headers: AxHeaders,
|
||||
Query(q): Query<HashMap<String, String>>,
|
||||
) -> std::result::Result<Json<Value>, StatusCode> {
|
||||
let auth = headers
|
||||
.get("authorization")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.unwrap_or_default();
|
||||
if !auth.contains(r#"Token="secret""#) {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
// 1 200 fake movies served in pages.
|
||||
let start: usize = q
|
||||
.get("startIndex")
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let limit: usize = q.get("limit").and_then(|s| s.parse().ok()).unwrap_or(100);
|
||||
let total = 1200;
|
||||
let items: Vec<Value> = (start..(start + limit).min(total))
|
||||
.map(|i| json!({"Id": format!("id{i}"), "Name": format!("Movie {i}"), "Type": "Movie",
|
||||
"Path": format!("/media/movies/Movie {i}/Movie {i}.mkv"),
|
||||
"ProviderIds": {"Tmdb": i.to_string()},
|
||||
"UserData": {"Played": i % 2 == 0, "PlaybackPositionTicks": 0, "PlayCount": 1, "IsFavorite": false}}))
|
||||
.collect();
|
||||
Ok(Json(json!({"Items": items, "TotalRecordCount": total})))
|
||||
}
|
||||
async fn updated(Json(body): Json<Value>) -> StatusCode {
|
||||
assert_eq!(body["Updates"][0]["Path"], "/media/movies/X");
|
||||
StatusCode::NO_CONTENT
|
||||
}
|
||||
let app = Router::new()
|
||||
.route("/Items", get(items))
|
||||
.route("/Library/Media/Updated", post(updated))
|
||||
.route("/Library/VirtualFolders", get(|| async {
|
||||
Json(json!([{"Name": "Movies", "Locations": ["/media/movies"], "CollectionType": "movies", "ItemId": "lib1"}]))
|
||||
}));
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
|
||||
format!("http://{addr}/")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn paginates_and_parses_items() {
|
||||
let c = Client::new(&mock().await, "secret").unwrap();
|
||||
let items = c
|
||||
.items(&ItemQuery {
|
||||
include_types: &["Movie"],
|
||||
recursive: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(items.len(), 1200);
|
||||
assert_eq!(items[1199].name, "Movie 1199");
|
||||
assert_eq!(items[3].provider_ids["Tmdb"], "3");
|
||||
assert!(items[2].user_data.as_ref().unwrap().played);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bad_token_is_an_error() {
|
||||
let c = Client::new(&mock().await, "wrong").unwrap();
|
||||
let err = c.items(&ItemQuery::default()).await.unwrap_err();
|
||||
assert!(matches!(err, JellyfinError::Status { status: 401, .. }));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn virtual_folders_and_media_updated() {
|
||||
let c = Client::new(&mock().await, "secret").unwrap();
|
||||
let vf = c.virtual_folders().await.unwrap();
|
||||
assert_eq!(vf[0].locations, ["/media/movies"]);
|
||||
c.media_updated(&["/media/movies/X".to_string()])
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_bad_url() {
|
||||
assert!(Client::new("jellyfin:8096", "k").is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user