Initial code commit
CI / test (push) Successful in 5m7s

This commit is contained in:
IxianPixel committed 2026-11-05 14:19:37 +00:00
1 parent f47217d5a3
commit 8ceb3c8be8
60 files changed
+10884

No files matched your search

+322
View File
@@ -0,0 +1,322 @@
//! Source side of a move. An *export* is an item folder this node has agreed
//! to hand over: it has been safety-checked, hashed and its users' watch state
//! captured. Files are served from it by index, never by path, so a peer can
//! only read what was exported.
use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
use jm_core::ItemKind;
use jm_core::job::ExportInfo;
use jm_core::paths::{join_relative, relative_inside};
use jm_core::safety::{check_inside_library, check_movie_folder};
use jm_core::userdata::{ItemKey, UserDataRecord};
use jm_jellyfin::ItemQuery;
use serde::{Deserialize, Serialize};
use crate::state::{AppState, Shared};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "detail")]
pub enum ExportStatus {
/// Checking the folder and hashing files.
Preparing,
Ready,
Failed(String),
/// Folder moved to the source trash; nothing left to serve.
Completed,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Export {
pub id: String,
pub item_id: String,
pub status: ExportStatus,
pub info: Option<ExportInfo>,
/// Item folder as Jellyfin sees it.
#[serde(default)]
pub jellyfin_folder: String,
/// Library location (Jellyfin namespace) containing the folder.
#[serde(default)]
pub jellyfin_location: String,
}
impl Export {
fn local_folder(&self, state: &AppState) -> PathBuf {
state
.cfg
.path_map
.to_local(Path::new(&self.jellyfin_folder))
}
/// Absolute local path of manifest entry `idx`, if it exists in the export.
pub fn file_path(&self, state: &AppState, idx: usize) -> Option<PathBuf> {
let info = self.info.as_ref()?;
let entry = info.manifest.files.get(idx)?;
join_relative(&self.local_folder(state), &entry.rel_path)
}
}
/// Start (or reuse) an export for `item_id`. Hashing runs in the background;
/// the caller polls [`get`] until the status is `Ready`.
pub async fn create(state: &Shared, item_id: &str) -> anyhow::Result<Export> {
// One export per item: re-requesting returns the existing one, so a
// destination that restarts mid-copy reattaches instead of re-hashing.
let id = format!("item-{item_id}");
if let Some(existing) = state.store.get_export::<Export>(&id).await? {
let retry = matches!(
existing.status,
ExportStatus::Failed(_) | ExportStatus::Completed
);
if !retry {
return Ok(existing);
}
}
let export = Export {
id: id.clone(),
item_id: item_id.to_string(),
status: ExportStatus::Preparing,
info: None,
jellyfin_folder: String::new(),
jellyfin_location: String::new(),
};
state.store.put_export(&id, &export).await?;
spawn_prepare(state.clone(), export.clone());
Ok(export)
}
/// Load an export. If it was being prepared when the daemon stopped, the
/// preparation is restarted.
pub async fn get(state: &Shared, id: &str) -> anyhow::Result<Option<Export>> {
let export: Option<Export> = state.store.get_export(id).await?;
if let Some(e) = &export {
if e.status == ExportStatus::Preparing {
spawn_prepare(state.clone(), e.clone());
}
}
Ok(export)
}
fn spawn_prepare(state: Shared, mut export: Export) {
if !state
.preparing
.lock()
.expect("lock")
.insert(export.id.clone())
{
return; // already running
}
tokio::spawn(async move {
match prepare(&state, &export.item_id).await {
Ok((info, folder, location)) => {
tracing::info!(item = %info.name, files = info.manifest.files.len(), "export ready");
export.info = Some(info);
export.jellyfin_folder = folder;
export.jellyfin_location = location;
export.status = ExportStatus::Ready;
}
Err(e) => {
tracing::warn!(item = %export.item_id, error = %format!("{e:#}"), "export failed");
export.status = ExportStatus::Failed(format!("{e:#}"));
}
}
if let Err(e) = state.store.put_export(&export.id, &export).await {
tracing::error!(error = %e, "could not save export");
}
state.preparing.lock().expect("lock").remove(&export.id);
});
}
async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo, String, String)> {
let jf = &state.jellyfin;
let item = jf
.item(item_id)
.await
.context("looking up the item on Jellyfin")?;
let kind = match item.kind.as_str() {
"Movie" => ItemKind::Movie,
"Series" => ItemKind::Series,
other => bail!("can only move movies and series, not {other}"),
};
let item_path = PathBuf::from(
item.path
.clone()
.context("Jellyfin did not report a path for this item")?,
);
let folder = match kind {
ItemKind::Movie => item_path
.parent()
.context("movie path has no parent folder")?
.to_path_buf(),
ItemKind::Series => item_path.clone(),
};
let libraries = jf.virtual_folders().await?;
let (library, location) = libraries
.iter()
.find_map(|lib| {
check_inside_library(&folder, &lib.locations)
.ok()
.map(|loc| (lib, loc.to_string()))
})
.with_context(|| {
// Re-run against all locations for a precise error.
let all: Vec<String> = libraries.iter().flat_map(|l| l.locations.clone()).collect();
match check_inside_library(&folder, &all) {
Err(e) => format!("{}: {e}", folder.display()),
Ok(_) => format!("{} is not in a library", folder.display()),
}
})?;
let rel_folder = relative_inside(Path::new(&location), &folder)
.context("item folder is not below its library")?;
let local_folder = state.cfg.path_map.to_local(&folder);
if !tokio::fs::metadata(&local_folder)
.await
.map(|m| m.is_dir())
.unwrap_or(false)
{
bail!(
"folder {} (Jellyfin path {}) is not visible to jellymove; check the volume mounts or path_map",
local_folder.display(),
folder.display()
);
}
if kind == ItemKind::Movie {
let lf = local_folder.clone();
let files = tokio::task::spawn_blocking(move || jm_transfer::list_relative(&lf)).await??;
let own: Vec<String> = item
.media_sources
.iter()
.flatten()
.filter_map(|m| m.path.as_deref())
.chain(std::iter::once(item_path.to_str().unwrap_or_default()))
.filter_map(|p| relative_inside(&folder, Path::new(p)))
.collect();
check_movie_folder(&files, &own)?;
}
let manifest = jm_transfer::build_manifest(&local_folder)
.await
.context("hashing files")?;
if manifest.files.is_empty() {
bail!("the item folder is empty");
}
// Capture each user's watch state now, before anything moves.
let mut user_data = Vec::new();
let mut episode_keys = Vec::new();
for user in jf.users().await? {
let root = jf
.items(&ItemQuery {
ids: Some(item_id),
user_id: Some(&user.id),
..Default::default()
})
.await?;
if let Some(ud) = root.into_iter().next().and_then(|i| i.user_data) {
push_record(&mut user_data, &user.name, ItemKey::Root, ud.into());
}
if kind == ItemKind::Series {
let episodes = jf
.items(&ItemQuery {
parent_id: Some(item_id),
include_types: &["Episode"],
recursive: true,
user_id: Some(&user.id),
..Default::default()
})
.await?;
for ep in episodes {
let (Some(season), Some(episode)) = (ep.parent_index_number, ep.index_number)
else {
continue;
};
let key = ItemKey::Episode { season, episode };
if !episode_keys.contains(&key) {
episode_keys.push(key);
}
if let Some(ud) = ep.user_data {
push_record(&mut user_data, &user.name, key, ud.into());
}
}
}
}
let info = ExportInfo {
item_id: item_id.to_string(),
name: item.name,
kind,
library_name: library.name.clone(),
rel_folder,
manifest,
user_data,
episode_keys,
};
Ok((info, folder.display().to_string(), location))
}
fn push_record(
out: &mut Vec<UserDataRecord>,
user: &str,
key: ItemKey,
data: jm_core::userdata::UserData,
) {
if !data.is_empty() {
out.push(UserDataRecord {
user_name: user.to_string(),
key,
data,
});
}
}
/// Final step on the source: move the folder into a hidden trash folder in
/// the same library (same filesystem, so it's a rename) and rescan.
pub async fn complete(state: &Shared, id: &str) -> anyhow::Result<Export> {
let mut export: Export = state
.store
.get_export(id)
.await?
.context("no such export")?;
match &export.status {
ExportStatus::Completed => return Ok(export),
ExportStatus::Ready => {}
other => bail!("export is not ready to complete ({other:?})"),
}
let info = export.info.as_ref().context("export has no info")?;
let local_folder = export.local_folder(state);
let location_local = state
.cfg
.path_map
.to_local(Path::new(&export.jellyfin_location));
let trash_root = location_local.join(".jellymove-trash");
let trash = join_relative(&trash_root.join(&export.id), &info.rel_folder)
.context("unsafe folder name")?;
if tokio::fs::metadata(&local_folder).await.is_ok() {
if let Some(parent) = trash.parent() {
tokio::fs::create_dir_all(parent).await?;
}
let marker = trash_root.join(".ignore");
if tokio::fs::metadata(&marker).await.is_err() {
tokio::fs::write(&marker, b"").await?;
}
tokio::fs::rename(&local_folder, &trash)
.await
.with_context(|| format!("moving {} to the trash", local_folder.display()))?;
tracing::info!(from = %local_folder.display(), to = %trash.display(), "source moved to trash");
}
if let Err(e) = state
.jellyfin
.media_updated(std::slice::from_ref(&export.jellyfin_folder))
.await
{
tracing::warn!(error = %e, "could not ask Jellyfin to rescan the source folder");
}
export.status = ExportStatus::Completed;
state.store.put_export(&export.id, &export).await?;
Ok(export)
}