//! A tiny filesystem-backed stand-in for Jellyfin, good enough to drive a //! real move end to end. Like real Jellyfin, item IDs are derived from paths, //! scans happen a moment after `/Library/Media/Updated`, and user data is //! keyed by (user, item). use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use std::time::Duration; use axum::extract::{Path as AxPath, Query, State}; use axum::http::StatusCode; use axum::routing::{get, post}; use axum::{Json, Router}; use serde_json::{Value, json}; #[derive(Clone)] pub struct Lib { pub name: String, pub collection_type: &'static str, pub location: PathBuf, } impl Lib { pub fn id(&self) -> String { format!("lib-{}", self.name.to_lowercase().replace(' ', "-")) } } #[derive(Clone, Debug)] struct FakeItem { id: String, name: String, kind: &'static str, path: String, parent: String, /// The series a season or episode belongs to. series: Option, season: Option, /// Episode number, or a season's own number. episode: Option, } #[derive(Clone)] pub struct Fake { libs: Arc>, items: Arc>>, /// (user id, item id) → UserData JSON pub user_data: Arc>>, } pub fn id_for(path: &Path) -> String { blake3::hash(path.to_string_lossy().as_bytes()).to_hex()[..32].to_string() } fn parse_sxxexx(name: &str) -> Option<(i32, i32)> { // Find the first "SE" anywhere in the name. let up = name.to_uppercase(); let b = up.as_bytes(); for i in 0..b.len() { if b[i] != b'S' { continue; } let s: String = up[i + 1..] .chars() .take_while(|c| c.is_ascii_digit()) .collect(); let after = i + 1 + s.len(); if s.is_empty() || b.get(after) != Some(&b'E') { continue; } let e: String = up[after + 1..] .chars() .take_while(|c| c.is_ascii_digit()) .collect(); if let (Ok(season), Ok(ep)) = (s.parse(), e.parse()) { return Some((season, ep)); } } None } fn walk(dir: &Path, out: &mut Vec) { let Ok(rd) = std::fs::read_dir(dir) else { return; }; for e in rd.flatten() { let name = e.file_name().to_string_lossy().to_string(); if name.starts_with('.') { continue; // Jellyfin skips hidden folders } if e.file_type().unwrap().is_dir() { walk(&e.path(), out); } else { out.push(e.path()); } } } impl Fake { pub fn new(libs: Vec) -> Self { let f = Self { libs: Arc::new(libs), items: Default::default(), user_data: Default::default(), }; f.scan(); f } pub fn scan(&self) { let mut items = Vec::new(); for lib in self.libs.iter() { let Ok(rd) = std::fs::read_dir(&lib.location) else { continue; }; for entry in rd.flatten() { let name = entry.file_name().to_string_lossy().to_string(); if name.starts_with('.') || !entry.file_type().unwrap().is_dir() { continue; } let folder = entry.path(); let mut files = Vec::new(); walk(&folder, &mut files); if lib.collection_type == "movies" { for f in files .iter() .filter(|f| f.extension().is_some_and(|e| e == "mkv")) { if f.parent() != Some(folder.as_path()) { continue; // extras } items.push(FakeItem { id: id_for(f), name: name.split(" (").next().unwrap().to_string(), kind: "Movie", path: f.display().to_string(), parent: lib.id(), series: None, season: None, episode: None, }); } } else { let series_id = id_for(&folder); items.push(FakeItem { id: series_id.clone(), name: name.clone(), kind: "Series", path: folder.display().to_string(), parent: lib.id(), series: None, season: None, episode: None, }); // Like Jellyfin: a season per season folder, holding its // episodes; episodes loose in the show folder hang off // the series. let mut seasons: Vec<(PathBuf, i32, String)> = Vec::new(); for f in files .iter() .filter(|f| f.extension().is_some_and(|e| e == "mkv")) { let fname = f.file_name().unwrap().to_string_lossy(); let Some((s, e)) = parse_sxxexx(&fname) else { continue; }; let in_folder = f .strip_prefix(&folder) .ok() .and_then(|r| r.components().next()) .map(|c| folder.join(c)) .filter(|p| p.is_dir()); // The folder name gives the season's number ("Season 02", // "Specials"); an episode filed under the wrong season // doesn't belong to it. let folder_number = |p: &Path| { let n = p.file_name()?.to_string_lossy().to_lowercase(); if n == "specials" { return Some(0); } n.chars() .filter(|c| c.is_ascii_digit()) .collect::() .parse::() .ok() }; let parent = match in_folder { Some(season_folder) if folder_number(&season_folder) == Some(s) => { let id = id_for(&season_folder); if !seasons.iter().any(|(p, _, _)| p == &season_folder) { seasons.push((season_folder, s, id.clone())); } id } _ => series_id.clone(), }; items.push(FakeItem { id: id_for(f), name: fname.to_string(), kind: "Episode", path: f.display().to_string(), parent, series: Some(series_id.clone()), season: Some(s), episode: Some(e), }); } for (path, n, id) in seasons { items.push(FakeItem { id, name: if n == 0 { "Specials".into() } else { format!("Season {n}") }, kind: "Season", path: path.display().to_string(), parent: series_id.clone(), series: Some(series_id.clone()), season: None, episode: Some(n), }); } } } } *self.items.lock().unwrap() = items; } pub fn find(&self, kind: &str, name: &str) -> Option { self.items .lock() .unwrap() .iter() .find(|i| i.kind == kind && i.name == name) .map(|i| i.id.clone()) } pub fn episode_id(&self, series: &str, season: i32, ep: i32) -> Option { let series_id = self.find("Series", series)?; self.items .lock() .unwrap() .iter() .find(|i| { i.kind == "Episode" && i.series.as_deref() == Some(&series_id) && i.season == Some(season) && i.episode == Some(ep) }) .map(|i| i.id.clone()) } pub fn season_id(&self, series: &str, season: i32) -> Option { let series_id = self.find("Series", series)?; self.items .lock() .unwrap() .iter() .find(|i| i.kind == "Season" && i.parent == series_id && i.episode == Some(season)) .map(|i| i.id.clone()) } pub fn set_user_data(&self, item: &str, data: Value) { self.user_data .lock() .unwrap() .insert(("u1".into(), item.into()), data); } pub fn get_user_data(&self, item: &str) -> Option { self.user_data .lock() .unwrap() .get(&("u1".to_string(), item.to_string())) .cloned() } pub async fn serve(self) -> String { let app = Router::new() .route( "/System/Info", get(|| async { Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"})) }), ) .route( "/Users", get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }), ) .route("/Library/VirtualFolders", get(virtual_folders)) .route("/Items", get(items)) .route("/Library/Media/Updated", post(media_updated)) .route("/UserItems/{id}/UserData", post(set_user_data)) .with_state(self); 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}") } } async fn virtual_folders(State(f): State) -> Json { Json(Value::Array( f.libs .iter() .map(|l| { json!({"Name": l.name, "Locations": [l.location.display().to_string()], "CollectionType": l.collection_type, "ItemId": l.id()}) }) .collect(), )) } async fn items(State(f): State, Query(q): Query>) -> Json { let all = f.items.lock().unwrap().clone(); let types: Option> = q.get("includeItemTypes").map(|t| t.split(',').collect()); let ids: Option> = q.get("ids").map(|t| t.split(',').collect()); let ud = f.user_data.lock().unwrap().clone(); let user = q.get("userId"); let out: Vec = all .iter() .filter(|i| ids.as_ref().is_none_or(|ids| ids.contains(&i.id.as_str()))) .filter(|i| { // Recursive queries under a series also reach its episodes, // which hang off their seasons. let recursive = q.get("recursive").is_some_and(|r| r == "true"); q.get("parentId").is_none_or(|p| { &i.parent == p || (recursive && i.series.as_deref() == Some(p.as_str())) }) }) .filter(|i| types.as_ref().is_none_or(|t| t.contains(&i.kind))) .filter(|i| { q.get("searchTerm") .is_none_or(|s| i.name.to_lowercase().contains(&s.to_lowercase())) }) .map(|i| { let mut v = json!({"Id": i.id, "Name": i.name, "Type": i.kind, "Path": i.path, "ParentIndexNumber": i.season, "IndexNumber": i.episode, "SeriesId": i.series, "MediaSources": [{"Path": i.path}]}); if let Some(u) = user { v["UserData"] = ud .get(&(u.clone(), i.id.clone())) .cloned() .unwrap_or(json!({"Played": false})); } v }) .collect(); let n = out.len(); Json(json!({"Items": out, "TotalRecordCount": n})) } async fn media_updated(State(f): State) -> StatusCode { // Like Jellyfin's LibraryMonitorDelay, but much shorter. tokio::spawn(async move { tokio::time::sleep(Duration::from_millis(300)).await; f.scan(); }); StatusCode::NO_CONTENT } async fn set_user_data( State(f): State, AxPath(id): AxPath, Query(q): Query>, Json(body): Json, ) -> StatusCode { f.user_data .lock() .unwrap() .insert((q["userId"].clone(), id), body); StatusCode::OK }