1 parent
f47217d5a3
commit
8ceb3c8be8
60 files changed
+10884
No files matched your search
@@ -0,0 +1,296 @@
|
||||
//! 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,
|
||||
season: Option<i32>,
|
||||
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>>>,
|
||||
}
|
||||
|
||||
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(),
|
||||
};
|
||||
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(),
|
||||
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(),
|
||||
season: None,
|
||||
episode: None,
|
||||
});
|
||||
for f in files
|
||||
.iter()
|
||||
.filter(|f| f.extension().is_some_and(|e| e == "mkv"))
|
||||
{
|
||||
let fname = f.file_name().unwrap().to_string_lossy();
|
||||
if let Some((s, e)) = parse_sxxexx(&fname) {
|
||||
items.push(FakeItem {
|
||||
id: id_for(f),
|
||||
name: fname.to_string(),
|
||||
kind: "Episode",
|
||||
path: f.display().to_string(),
|
||||
parent: series_id.clone(),
|
||||
season: Some(s),
|
||||
episode: Some(e),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*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.parent == series_id && i.season == Some(season) && i.episode == Some(ep))
|
||||
.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<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(|| 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<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| q.get("parentId").is_none_or(|p| &i.parent == p))
|
||||
.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,
|
||||
"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
|
||||
}
|
||||
Reference in new issue
Block a user