//! Browsing the local Jellyfin libraries. use std::path::{Path, PathBuf}; use jm_jellyfin::ItemQuery; use serde::{Deserialize, Serialize}; use crate::sizes::{self, FolderSize}; use crate::state::{AppState, Shared}; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Library { pub id: String, pub name: String, pub collection_type: Option, pub locations: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LibraryItem { pub id: String, pub name: String, /// "Movie" or "Series". pub kind: String, pub year: Option, pub path: Option, /// Size of the item's folder on disk; `None` until it has been measured. #[serde(default)] pub size: Option, } /// A season of a show, as Jellyfin lists it. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SeasonItem { pub id: String, pub name: String, pub number: Option, /// The season's own folder. `None` when its episodes sit directly in the /// show folder, in which case it can't be moved on its own. pub path: Option, /// Name of that folder inside the show folder, to match it with the /// show's per-folder sizes. pub folder: Option, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct LocationCheck { pub library: String, pub jellyfin_path: String, pub local_path: String, pub exists: bool, pub writable: bool, } /// Only libraries jellymove knows how to move items out of. fn supported(collection_type: Option<&str>) -> bool { matches!(collection_type, Some("movies") | Some("tvshows") | None) } pub async fn libraries(state: &AppState) -> anyhow::Result> { Ok(state .jellyfin .virtual_folders() .await? .into_iter() .filter(|v| supported(v.collection_type.as_deref())) .map(|v| Library { id: v.item_id, name: v.name, collection_type: v.collection_type, locations: v.locations, }) .collect()) } /// The movies and series in a library, with the size of each one's folder if /// it's known yet. Sizes still missing are being measured in the background. pub async fn items( state: &Shared, library_id: &str, search: Option<&str>, ) -> anyhow::Result> { let search = search.map(str::trim).filter(|s| !s.is_empty()); let items = state .jellyfin .items(&ItemQuery { parent_id: Some(library_id), include_types: &["Movie", "Series"], recursive: true, search, ..Default::default() }) .await?; let mut out: Vec = items .into_iter() .map(|i| LibraryItem { id: i.id, name: i.name, kind: i.kind, year: i.production_year, path: i.path, size: None, }) .collect(); // Only items whose folder we can place are measured. let folders: Vec<(usize, PathBuf)> = out .iter() .enumerate() .filter_map(|(n, i)| Some((n, item_folder(state, i)?))) .collect(); let paths: Vec = folders.iter().map(|(_, p)| p.clone()).collect(); let sizes = sizes::lookup(state, &paths).await?; for ((n, _), size) in folders.into_iter().zip(sizes) { out[n].size = size; } Ok(out) } /// The seasons of a show, in order. Seasons without a folder of their own /// inside the show folder are listed with no path. pub async fn seasons(state: &AppState, series_id: &str) -> anyhow::Result> { let series = state.jellyfin.item(series_id).await?; let show = series.path.map(PathBuf::from); let mut out: Vec = state .jellyfin .items(&ItemQuery { parent_id: Some(series_id), include_types: &["Season"], ..Default::default() }) .await? .into_iter() .map(|s| { let path = s .path .filter(|p| show.as_deref().is_some_and(|show| Path::new(p).parent() == Some(show))); let folder = path .as_deref() .and_then(|p| Path::new(p).file_name()) .map(|n| n.to_string_lossy().into_owned()); SeasonItem { id: s.id, name: s.name, number: s.index_number, path, folder, } }) .collect(); out.sort_by_key(|s| s.number.unwrap_or(i32::MAX)); Ok(out) } /// The folder a move would take, as this agent sees it: a movie's parent /// folder, or the series folder itself. fn item_folder(state: &AppState, item: &LibraryItem) -> Option { let path = Path::new(item.path.as_deref()?); let folder = match item.kind.as_str() { "Movie" => path.parent()?, "Series" => path, _ => return None, }; Some(state.cfg.path_map.to_local(folder)) } /// Confirm every library location exists and is writable from this agent. /// The most common setup mistakes (wrong mount, wrong PUID/PGID, missing /// path_map) all show up here. pub async fn check_locations(state: &AppState) -> anyhow::Result> { let mut out = Vec::new(); for lib in libraries(state).await? { for loc in &lib.locations { let local = state.cfg.path_map.to_local(Path::new(loc)); let exists = tokio::fs::metadata(&local) .await .map(|m| m.is_dir()) .unwrap_or(false); let writable = exists && { let probe = local.join(format!(".jellymove-probe-{}", uuid::Uuid::new_v4())); let ok = tokio::fs::write(&probe, b"").await.is_ok(); let _ = tokio::fs::remove_file(&probe).await; ok }; out.push(LocationCheck { library: lib.name.clone(), jellyfin_path: loc.clone(), local_path: local.display().to_string(), exists, writable, }); } } Ok(out) }