Files
Jellymove/crates/jm-server/src/library.rs
T
IxianPixel 484ac50508
CI / test (push) Successful in 1m14s
Move a single season of a TV show (#4)
Shows can be expanded to list their seasons, each with its size and its own Dry run / Move buttons. A season joins the same show on the other
server, so finished seasons can go to the big server while the current one stays on the fast one.

- Source exports a season from the show folder, with a manifest of just that season's folder plus the show's loose non-video files. Refuses
  seasons with no folder of their own, or whose folder holds otherseasons' episodes.
- Destination finds the show by provider ID, then name. If it already has the show, the show's own files are skipped (Job.skip_files) and
  never overwritten; otherwise they come with the season. Refuses if the season folder already exists.
- Only episode watch state is carried for a season.
- Source trashes just the season folder; after the last season, the leftover show folder joins it in the same trash entry if no videos
  remain. The chosen trash entry is saved so a re-run after a crash finishes in the same place.
- New GET /seasons (UI and peer). Fake Jellyfin gains season items.
- e2e tests: season into a new show, into an existing show, last season leaving, destination already has the season, misfiled episodes.
2026-11-06 17:02:40 +00:00

196 lines
6.1 KiB
Rust

//! 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<String>,
pub locations: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LibraryItem {
pub id: String,
pub name: String,
/// "Movie" or "Series".
pub kind: String,
pub year: Option<i32>,
pub path: Option<String>,
/// Size of the item's folder on disk; `None` until it has been measured.
#[serde(default)]
pub size: Option<FolderSize>,
}
/// 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<i32>,
/// 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<String>,
/// Name of that folder inside the show folder, to match it with the
/// show's per-folder sizes.
pub folder: Option<String>,
}
#[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<Vec<Library>> {
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<Vec<LibraryItem>> {
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<LibraryItem> = 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<PathBuf> = 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<Vec<SeasonItem>> {
let series = state.jellyfin.item(series_id).await?;
let show = series.path.map(PathBuf::from);
let mut out: Vec<SeasonItem> = 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<PathBuf> {
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<Vec<LocationCheck>> {
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)
}