402 lines
14 KiB
Rust
402 lines
14 KiB
Rust
//! 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<String>,
|
|
season: Option<i32>,
|
|
/// Episode number, or a season's own number.
|
|
episode: Option<i32>,
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Fake {
|
|
libs: Arc<Vec<Lib>>,
|
|
items: Arc<Mutex<Vec<FakeItem>>>,
|
|
/// (user id, item id) → UserData JSON
|
|
pub user_data: Arc<Mutex<HashMap<(String, String), Value>>>,
|
|
/// (user id, name)
|
|
users: Arc<Mutex<Vec<(String, String)>>>,
|
|
}
|
|
|
|
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 "S<digits>E<digits>" 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<PathBuf>) {
|
|
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<Lib>) -> Self {
|
|
let f = Self {
|
|
libs: Arc::new(libs),
|
|
items: Default::default(),
|
|
user_data: Default::default(),
|
|
users: Arc::new(Mutex::new(vec![("u1".into(), "Alice".into())])),
|
|
};
|
|
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::<String>()
|
|
.parse::<i32>()
|
|
.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<String> {
|
|
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<String> {
|
|
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<String> {
|
|
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 add_user(&self, id: &str, name: &str) {
|
|
self.users.lock().unwrap().push((id.into(), name.into()));
|
|
}
|
|
|
|
pub fn set_user_data_for(&self, user: &str, item: &str, data: Value) {
|
|
self.user_data
|
|
.lock()
|
|
.unwrap()
|
|
.insert((user.into(), item.into()), data);
|
|
}
|
|
|
|
pub fn get_user_data_for(&self, user: &str, item: &str) -> Option<Value> {
|
|
self.user_data
|
|
.lock()
|
|
.unwrap()
|
|
.get(&(user.to_string(), item.to_string()))
|
|
.cloned()
|
|
}
|
|
|
|
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<Value> {
|
|
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(users))
|
|
.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 users(State(f): State<Fake>) -> Json<Value> {
|
|
Json(Value::Array(
|
|
f.users
|
|
.lock()
|
|
.unwrap()
|
|
.iter()
|
|
.map(|(id, name)| json!({"Id": id, "Name": name}))
|
|
.collect(),
|
|
))
|
|
}
|
|
|
|
async fn virtual_folders(State(f): State<Fake>) -> Json<Value> {
|
|
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<Fake>, Query(q): Query<HashMap<String, String>>) -> Json<Value> {
|
|
let all = f.items.lock().unwrap().clone();
|
|
let types: Option<Vec<&str>> = q.get("includeItemTypes").map(|t| t.split(',').collect());
|
|
let ids: Option<Vec<&str>> = q.get("ids").map(|t| t.split(',').collect());
|
|
let ud = f.user_data.lock().unwrap().clone();
|
|
let user = q.get("userId");
|
|
let out: Vec<Value> = 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<Fake>) -> 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<Fake>,
|
|
AxPath(id): AxPath<String>,
|
|
Query(q): Query<HashMap<String, String>>,
|
|
Json(body): Json<Value>,
|
|
) -> StatusCode {
|
|
f.user_data
|
|
.lock()
|
|
.unwrap()
|
|
.insert((q["userId"].clone(), id), body);
|
|
StatusCode::OK
|
|
}
|