1 parent
f47217d5a3
commit
8ceb3c8be8
60 files changed
+10884
No files matched your search
@@ -0,0 +1,444 @@
|
||||
//! HTTP routes. `/api/*` serves the browser UI; `/peer/v1/*` is the
|
||||
//! agent-to-agent protocol, authenticated with the shared peer token.
|
||||
|
||||
use std::convert::Infallible;
|
||||
use std::time::Duration;
|
||||
|
||||
use axum::extract::{Path, Query, Request, State};
|
||||
use axum::http::{HeaderMap, Method, StatusCode, header};
|
||||
use axum::middleware::{self, Next};
|
||||
use axum::response::sse::{Event, KeepAlive, Sse};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use base64::Engine;
|
||||
use futures::Stream;
|
||||
use jm_core::{Job, JobId, JobStatus};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use tokio_stream::StreamExt;
|
||||
use tokio_stream::wrappers::BroadcastStream;
|
||||
|
||||
use crate::export::{self, Export, ExportStatus};
|
||||
use crate::library::{self, Library, LibraryItem, LocationCheck};
|
||||
use crate::peer::{CreateJob, NodeInfo};
|
||||
use crate::runner;
|
||||
use crate::state::Shared;
|
||||
|
||||
pub struct ApiError(StatusCode, String);
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
(self.0, Json(json!({ "error": self.1 }))).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for ApiError {
|
||||
fn from(e: anyhow::Error) -> Self {
|
||||
ApiError(StatusCode::BAD_GATEWAY, format!("{e:#}"))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<jm_store::StoreError> for ApiError {
|
||||
fn from(e: jm_store::StoreError) -> Self {
|
||||
ApiError(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<jm_jellyfin::JellyfinError> for ApiError {
|
||||
fn from(e: jm_jellyfin::JellyfinError) -> Self {
|
||||
ApiError(StatusCode::BAD_GATEWAY, e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
type ApiResult<T> = Result<Json<T>, ApiError>;
|
||||
|
||||
pub fn router(state: Shared) -> Router {
|
||||
let ui_api = Router::new()
|
||||
.route("/status", get(status))
|
||||
.route("/libraries", get(ui_libraries))
|
||||
.route("/items", get(ui_items))
|
||||
.route("/moves", post(ui_move))
|
||||
.route("/jobs", get(ui_jobs))
|
||||
.route("/jobs/{id}/retry", post(ui_retry))
|
||||
.route("/events", get(events));
|
||||
|
||||
let peer_api = Router::new()
|
||||
.route("/info", get(peer_info))
|
||||
.route("/libraries", get(peer_libraries))
|
||||
.route("/items", get(peer_items))
|
||||
.route("/exports", post(peer_create_export))
|
||||
.route("/exports/{id}", get(peer_get_export))
|
||||
.route("/exports/{id}/files/{idx}", get(peer_file))
|
||||
.route("/exports/{id}/complete", post(peer_complete_export))
|
||||
.route("/jobs", get(peer_jobs).post(peer_create_job))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
require_peer_token,
|
||||
));
|
||||
|
||||
Router::new()
|
||||
.nest(
|
||||
"/api",
|
||||
ui_api.layer(middleware::from_fn(require_csrf_header)),
|
||||
)
|
||||
.nest("/peer/v1", peer_api)
|
||||
.fallback(crate::ui::serve)
|
||||
.layer(middleware::from_fn_with_state(
|
||||
state.clone(),
|
||||
require_ui_auth,
|
||||
))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- auth
|
||||
|
||||
fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||
}
|
||||
|
||||
async fn require_peer_token(State(state): State<Shared>, req: Request, next: Next) -> Response {
|
||||
let Some(peer) = &state.cfg.peer else {
|
||||
return ApiError(StatusCode::SERVICE_UNAVAILABLE, "no peer configured".into())
|
||||
.into_response();
|
||||
};
|
||||
let presented = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Bearer "))
|
||||
.unwrap_or_default();
|
||||
if constant_time_eq(presented.as_bytes(), peer.token.as_bytes()) {
|
||||
next.run(req).await
|
||||
} else {
|
||||
ApiError(StatusCode::UNAUTHORIZED, "bad peer token".into()).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// HTTP Basic auth for everything except the peer API, if a password is set.
|
||||
async fn require_ui_auth(State(state): State<Shared>, req: Request, next: Next) -> Response {
|
||||
let (Some(user), Some(pass)) = (&state.cfg.ui.username, &state.cfg.ui.password) else {
|
||||
return next.run(req).await;
|
||||
};
|
||||
if req.uri().path().starts_with("/peer/") {
|
||||
return next.run(req).await;
|
||||
}
|
||||
let ok = req
|
||||
.headers()
|
||||
.get(header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|v| v.strip_prefix("Basic "))
|
||||
.and_then(|b| base64::engine::general_purpose::STANDARD.decode(b).ok())
|
||||
.is_some_and(|decoded| constant_time_eq(&decoded, format!("{user}:{pass}").as_bytes()));
|
||||
if ok {
|
||||
next.run(req).await
|
||||
} else {
|
||||
(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
[(header::WWW_AUTHENTICATE, r#"Basic realm="jellymove""#)],
|
||||
"login required",
|
||||
)
|
||||
.into_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// Browsers send Basic credentials automatically, so state-changing requests
|
||||
/// must carry a header a cross-site form can't set.
|
||||
async fn require_csrf_header(req: Request, next: Next) -> Response {
|
||||
if req.method() != Method::GET && !req.headers().contains_key("x-jellymove") {
|
||||
return ApiError(StatusCode::FORBIDDEN, "missing X-Jellymove header".into())
|
||||
.into_response();
|
||||
}
|
||||
next.run(req).await
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- UI API
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Status {
|
||||
node: NodeInfo,
|
||||
jellyfin_error: Option<String>,
|
||||
locations: Vec<LocationCheck>,
|
||||
peer_url: Option<String>,
|
||||
peer: Option<NodeInfo>,
|
||||
peer_error: Option<String>,
|
||||
config: crate::config::Config,
|
||||
}
|
||||
|
||||
async fn node_info(state: &Shared) -> (NodeInfo, Option<String>) {
|
||||
let (server, err) = match state.jellyfin.system_info().await {
|
||||
Ok(i) => (Some(i), None),
|
||||
Err(e) => (None, Some(e.to_string())),
|
||||
};
|
||||
(
|
||||
NodeInfo {
|
||||
node_name: state.cfg.node_name.clone(),
|
||||
version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
jellyfin_server: server.as_ref().map(|s| s.server_name.clone()),
|
||||
jellyfin_version: server.map(|s| s.version),
|
||||
},
|
||||
err,
|
||||
)
|
||||
}
|
||||
|
||||
async fn status(State(state): State<Shared>) -> ApiResult<Status> {
|
||||
let (node, jellyfin_error) = node_info(&state).await;
|
||||
let locations = if jellyfin_error.is_none() {
|
||||
library::check_locations(&state).await?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
let (peer, peer_error) = match &state.peer {
|
||||
None => (None, None),
|
||||
Some(p) => match p.info().await {
|
||||
Ok(i) => (Some(i), None),
|
||||
Err(e) => (None, Some(format!("{e:#}"))),
|
||||
},
|
||||
};
|
||||
Ok(Json(Status {
|
||||
node,
|
||||
jellyfin_error,
|
||||
locations,
|
||||
peer_url: state.cfg.peer.as_ref().map(|p| p.url.clone()),
|
||||
peer,
|
||||
peer_error,
|
||||
config: state.cfg.redacted(),
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct NodeQuery {
|
||||
#[serde(default)]
|
||||
node: Side,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
enum Side {
|
||||
#[default]
|
||||
Local,
|
||||
Peer,
|
||||
}
|
||||
|
||||
async fn ui_libraries(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<NodeQuery>,
|
||||
) -> ApiResult<Vec<Library>> {
|
||||
Ok(Json(match q.node {
|
||||
Side::Local => library::libraries(&state).await?,
|
||||
Side::Peer => state.peer()?.libraries().await?,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ItemsQuery {
|
||||
#[serde(default)]
|
||||
node: Side,
|
||||
library: String,
|
||||
search: Option<String>,
|
||||
}
|
||||
|
||||
async fn ui_items(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<ItemsQuery>,
|
||||
) -> ApiResult<Vec<LibraryItem>> {
|
||||
Ok(Json(match q.node {
|
||||
Side::Local => library::items(&state, &q.library, q.search.as_deref()).await?,
|
||||
Side::Peer => state.peer()?.items(&q.library, q.search.as_deref()).await?,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct MoveRequest {
|
||||
/// Where the item is now.
|
||||
from: Side,
|
||||
item_id: String,
|
||||
name: String,
|
||||
#[serde(default)]
|
||||
dry_run: bool,
|
||||
}
|
||||
|
||||
/// Start a move. Jobs always run on the destination, which pulls the data.
|
||||
async fn ui_move(State(state): State<Shared>, Json(req): Json<MoveRequest>) -> ApiResult<Job> {
|
||||
let peer = state.peer()?;
|
||||
match req.from {
|
||||
Side::Peer => {
|
||||
let peer_name = peer.info().await?.node_name;
|
||||
let job = Job::new(
|
||||
&req.item_id,
|
||||
&req.name,
|
||||
peer_name,
|
||||
&state.cfg.node_name,
|
||||
req.dry_run,
|
||||
);
|
||||
state.save(&job).await?;
|
||||
runner::start(state.clone(), job.clone());
|
||||
Ok(Json(job))
|
||||
}
|
||||
Side::Local => {
|
||||
let job = peer
|
||||
.create_job(&CreateJob {
|
||||
item_id: req.item_id,
|
||||
name: req.name,
|
||||
dry_run: req.dry_run,
|
||||
})
|
||||
.await?;
|
||||
Ok(Json(job))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct JobsView {
|
||||
/// Jobs this node is running (items moving *to* here).
|
||||
local: Vec<Job>,
|
||||
/// Jobs the peer is running (items moving *from* here).
|
||||
peer: Vec<Job>,
|
||||
peer_error: Option<String>,
|
||||
}
|
||||
|
||||
async fn ui_jobs(State(state): State<Shared>) -> ApiResult<JobsView> {
|
||||
let local = state.store.list_jobs(100).await?;
|
||||
let (peer, peer_error) = match &state.peer {
|
||||
None => (vec![], None),
|
||||
Some(p) => match p.jobs().await {
|
||||
Ok(j) => (j, None),
|
||||
Err(e) => (vec![], Some(format!("{e:#}"))),
|
||||
},
|
||||
};
|
||||
Ok(Json(JobsView {
|
||||
local,
|
||||
peer,
|
||||
peer_error,
|
||||
}))
|
||||
}
|
||||
|
||||
async fn ui_retry(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
|
||||
let id: JobId = id
|
||||
.parse()
|
||||
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?;
|
||||
let mut job = state
|
||||
.store
|
||||
.get_job(id)
|
||||
.await?
|
||||
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?;
|
||||
match &job.status {
|
||||
JobStatus::Failed(_) => {}
|
||||
JobStatus::Planned => job.dry_run = false, // "run it for real"
|
||||
other => return Err(ApiError(StatusCode::CONFLICT, format!("job is {other:?}"))),
|
||||
}
|
||||
job.note("retry requested");
|
||||
state.save(&job).await?;
|
||||
runner::start(state.clone(), job.clone());
|
||||
Ok(Json(job))
|
||||
}
|
||||
|
||||
async fn events(State(state): State<Shared>) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
|
||||
let stream = BroadcastStream::new(state.events.subscribe()).filter_map(|msg| {
|
||||
msg.ok().and_then(|mut job| {
|
||||
job.export = None; // manifests can be large; the UI doesn't need them live
|
||||
Event::default().event("job").json_data(&job).ok().map(Ok)
|
||||
})
|
||||
});
|
||||
Sse::new(stream).keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- peer API
|
||||
|
||||
async fn peer_info(State(state): State<Shared>) -> Json<NodeInfo> {
|
||||
Json(node_info(&state).await.0)
|
||||
}
|
||||
|
||||
async fn peer_libraries(State(state): State<Shared>) -> ApiResult<Vec<Library>> {
|
||||
Ok(Json(library::libraries(&state).await?))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PeerItemsQuery {
|
||||
library: String,
|
||||
search: Option<String>,
|
||||
}
|
||||
|
||||
async fn peer_items(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<PeerItemsQuery>,
|
||||
) -> ApiResult<Vec<LibraryItem>> {
|
||||
Ok(Json(
|
||||
library::items(&state, &q.library, q.search.as_deref()).await?,
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreateExport {
|
||||
item_id: String,
|
||||
}
|
||||
|
||||
async fn peer_create_export(
|
||||
State(state): State<Shared>,
|
||||
Json(req): Json<CreateExport>,
|
||||
) -> ApiResult<Export> {
|
||||
Ok(Json(export::create(&state, &req.item_id).await?))
|
||||
}
|
||||
|
||||
async fn peer_get_export(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Export> {
|
||||
export::get(&state, &id)
|
||||
.await?
|
||||
.map(Json)
|
||||
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such export".into()))
|
||||
}
|
||||
|
||||
async fn peer_file(
|
||||
State(state): State<Shared>,
|
||||
Path((id, idx)): Path<(String, usize)>,
|
||||
headers: HeaderMap,
|
||||
) -> Response {
|
||||
let export = match export::get(&state, &id).await {
|
||||
Ok(Some(e)) if e.status == ExportStatus::Ready => e,
|
||||
Ok(Some(_)) => {
|
||||
return ApiError(StatusCode::CONFLICT, "export not ready".into()).into_response();
|
||||
}
|
||||
Ok(None) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Err(e) => return ApiError::from(e).into_response(),
|
||||
};
|
||||
match export.file_path(&state, idx) {
|
||||
Some(path) => jm_transfer::range_response(&path, &headers).await,
|
||||
None => StatusCode::NOT_FOUND.into_response(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn peer_complete_export(
|
||||
State(state): State<Shared>,
|
||||
Path(id): Path<String>,
|
||||
) -> ApiResult<Export> {
|
||||
Ok(Json(export::complete(&state, &id).await?))
|
||||
}
|
||||
|
||||
async fn peer_create_job(
|
||||
State(state): State<Shared>,
|
||||
Json(req): Json<CreateJob>,
|
||||
) -> ApiResult<Job> {
|
||||
let peer_name = state
|
||||
.peer()?
|
||||
.info()
|
||||
.await
|
||||
.map(|i| i.node_name)
|
||||
.unwrap_or_else(|_| "peer".into());
|
||||
let job = Job::new(
|
||||
&req.item_id,
|
||||
&req.name,
|
||||
peer_name,
|
||||
&state.cfg.node_name,
|
||||
req.dry_run,
|
||||
);
|
||||
state.save(&job).await?;
|
||||
runner::start(state.clone(), job.clone());
|
||||
Ok(Json(job))
|
||||
}
|
||||
|
||||
async fn peer_jobs(State(state): State<Shared>) -> ApiResult<Vec<Job>> {
|
||||
let mut jobs = state.store.list_jobs(100).await?;
|
||||
for j in &mut jobs {
|
||||
j.export = None;
|
||||
}
|
||||
Ok(Json(jobs))
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
use std::collections::HashMap;
|
||||
use std::net::SocketAddr;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use jm_core::PathMap;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Daemon configuration. Loaded from TOML plus `JELLYMOVE_*` environment
|
||||
/// variables (nested keys use `__`, e.g. `JELLYMOVE_PEER__TOKEN`).
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct Config {
|
||||
/// Name shown in the UI and in job history, e.g. "cloud" or "home".
|
||||
pub node_name: String,
|
||||
#[serde(default = "default_listen")]
|
||||
pub listen: SocketAddr,
|
||||
/// Where the SQLite database lives.
|
||||
#[serde(default = "default_data_dir")]
|
||||
pub data_dir: PathBuf,
|
||||
pub jellyfin: JellyfinConfig,
|
||||
/// Jellyfin path → local path translations. Leave empty when this agent
|
||||
/// mounts media at the same paths as Jellyfin (recommended).
|
||||
#[serde(default)]
|
||||
pub path_map: PathMap,
|
||||
pub peer: Option<PeerConfig>,
|
||||
/// When an item arrives from the peer's library "X", put it in local
|
||||
/// library `incoming_libraries["X"]`. Unlisted libraries map to a local
|
||||
/// library with the same name.
|
||||
#[serde(default)]
|
||||
pub incoming_libraries: HashMap<String, String>,
|
||||
#[serde(default)]
|
||||
pub transfer: TransferConfig,
|
||||
#[serde(default)]
|
||||
pub ui: UiConfig,
|
||||
#[serde(default)]
|
||||
pub hooks: HooksConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct JellyfinConfig {
|
||||
pub url: String,
|
||||
pub api_key: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
pub struct PeerConfig {
|
||||
/// Base URL of the other jellymove agent, e.g. `https://cloud.example.com:8097`.
|
||||
pub url: String,
|
||||
/// Shared secret. Both agents must use the same value.
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Deserialize, Serialize)]
|
||||
#[serde(default)]
|
||||
pub struct TransferConfig {
|
||||
/// Cap on incoming transfer speed in megabits per second. 0 = unlimited.
|
||||
pub bandwidth_limit_mbps: f64,
|
||||
/// Attempts per file before the job fails (each attempt resumes).
|
||||
pub retries: u32,
|
||||
/// How long to wait for Jellyfin to index a moved item.
|
||||
pub scan_timeout_secs: u64,
|
||||
pub max_concurrent_jobs: usize,
|
||||
}
|
||||
|
||||
impl Default for TransferConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
bandwidth_limit_mbps: 0.0,
|
||||
retries: 20,
|
||||
scan_timeout_secs: 1200,
|
||||
max_concurrent_jobs: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
pub struct UiConfig {
|
||||
/// Protect the web UI with HTTP Basic auth. Strongly recommended if the
|
||||
/// port is reachable from anywhere but localhost.
|
||||
pub username: Option<String>,
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
|
||||
pub struct HooksConfig {
|
||||
/// Shell command run on the destination after a move finishes, e.g.
|
||||
/// `docker restart jellyswarrm` to clear Jellyswarrm's merge cache.
|
||||
/// Gets JELLYMOVE_ITEM_NAME and JELLYMOVE_TARGET_FOLDER in its environment.
|
||||
pub post_move: Option<String>,
|
||||
}
|
||||
|
||||
fn default_listen() -> SocketAddr {
|
||||
"0.0.0.0:8097".parse().expect("valid")
|
||||
}
|
||||
|
||||
fn default_data_dir() -> PathBuf {
|
||||
PathBuf::from("./data")
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn bytes_per_sec(&self) -> Option<std::num::NonZeroU32> {
|
||||
let bps = self.transfer.bandwidth_limit_mbps * 1_000_000.0 / 8.0;
|
||||
if bps >= 1.0 {
|
||||
std::num::NonZeroU32::new(bps.min(u32::MAX as f64) as u32)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Redacted copy safe to show in the UI.
|
||||
pub fn redacted(&self) -> Config {
|
||||
let mut c = self.clone();
|
||||
c.jellyfin.api_key = "••••".into();
|
||||
if let Some(p) = c.peer.as_mut() {
|
||||
p.token = "••••".into();
|
||||
}
|
||||
if c.ui.password.is_some() {
|
||||
c.ui.password = Some("••••".into());
|
||||
}
|
||||
c
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! The jellymove daemon: HTTP API, embedded UI, job runner and source exports.
|
||||
|
||||
pub mod api;
|
||||
pub mod config;
|
||||
pub mod export;
|
||||
pub mod library;
|
||||
pub mod peer;
|
||||
pub mod runner;
|
||||
pub mod state;
|
||||
pub mod ui;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub use config::Config;
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
/// Open state, resume interrupted jobs and serve until shutdown.
|
||||
pub async fn run(cfg: Config) -> anyhow::Result<()> {
|
||||
std::fs::create_dir_all(&cfg.data_dir)?;
|
||||
let store = jm_store::Store::open(&cfg.data_dir.join("jellymove.db"))?;
|
||||
let listen = cfg.listen;
|
||||
let state = Arc::new(state::AppState::new(cfg, store)?);
|
||||
|
||||
match state.jellyfin.system_info().await {
|
||||
Ok(i) => {
|
||||
tracing::info!(server = %i.server_name, version = %i.version, "connected to Jellyfin")
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!(error = %e, "can't reach Jellyfin yet; will keep trying on demand")
|
||||
}
|
||||
}
|
||||
runner::resume_all(&state).await?;
|
||||
|
||||
let app = api::router(state.clone()).layer(TraceLayer::new_for_http());
|
||||
let listener = tokio::net::TcpListener::bind(listen).await?;
|
||||
tracing::info!(%listen, node = %state.cfg.node_name, "jellymove listening");
|
||||
axum::serve(listener, app)
|
||||
.with_graceful_shutdown(shutdown_signal())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_signal() {
|
||||
let ctrl_c = async {
|
||||
let _ = tokio::signal::ctrl_c().await;
|
||||
};
|
||||
#[cfg(unix)]
|
||||
let term = async {
|
||||
if let Ok(mut s) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
|
||||
{
|
||||
s.recv().await;
|
||||
}
|
||||
};
|
||||
#[cfg(not(unix))]
|
||||
let term = std::future::pending::<()>();
|
||||
tokio::select! { _ = ctrl_c => {}, _ = term => {} }
|
||||
tracing::info!("shutting down; in-flight transfers will resume on next start");
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//! Browsing the local Jellyfin libraries.
|
||||
|
||||
use std::path::Path;
|
||||
|
||||
use jm_jellyfin::ItemQuery;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::state::AppState;
|
||||
|
||||
#[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>,
|
||||
}
|
||||
|
||||
#[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())
|
||||
}
|
||||
|
||||
pub async fn items(
|
||||
state: &AppState,
|
||||
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?;
|
||||
Ok(items
|
||||
.into_iter()
|
||||
.map(|i| LibraryItem {
|
||||
id: i.id,
|
||||
name: i.name,
|
||||
kind: i.kind,
|
||||
year: i.production_year,
|
||||
path: i.path,
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// 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)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Client for the other agent's `/peer/v1` API.
|
||||
|
||||
use jm_core::Job;
|
||||
use reqwest::header::AUTHORIZATION;
|
||||
use serde::{Deserialize, Serialize, de::DeserializeOwned};
|
||||
|
||||
use crate::export::Export;
|
||||
use crate::library::{Library, LibraryItem};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct PeerClient {
|
||||
http: reqwest::Client,
|
||||
base: String,
|
||||
token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NodeInfo {
|
||||
pub node_name: String,
|
||||
pub version: String,
|
||||
pub jellyfin_server: Option<String>,
|
||||
pub jellyfin_version: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CreateJob {
|
||||
pub item_id: String,
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
impl PeerClient {
|
||||
pub fn new(http: reqwest::Client, base: &str, token: &str) -> Self {
|
||||
Self {
|
||||
http,
|
||||
base: base.trim_end_matches('/').to_string(),
|
||||
token: token.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn url(&self, path: &str) -> String {
|
||||
format!("{}/peer/v1{path}", self.base)
|
||||
}
|
||||
|
||||
async fn send<T: DeserializeOwned>(
|
||||
&self,
|
||||
req: reqwest::RequestBuilder,
|
||||
what: &str,
|
||||
) -> anyhow::Result<T> {
|
||||
let resp = req
|
||||
.header(AUTHORIZATION, format!("Bearer {}", self.token))
|
||||
.timeout(std::time::Duration::from_secs(60))
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("could not reach peer ({what}): {e}"))?;
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("peer refused {what}: HTTP {status}: {body}");
|
||||
}
|
||||
Ok(resp.json().await?)
|
||||
}
|
||||
|
||||
pub async fn info(&self) -> anyhow::Result<NodeInfo> {
|
||||
self.send(self.http.get(self.url("/info")), "info").await
|
||||
}
|
||||
|
||||
pub async fn libraries(&self) -> anyhow::Result<Vec<Library>> {
|
||||
self.send(self.http.get(self.url("/libraries")), "list libraries")
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn items(
|
||||
&self,
|
||||
library: &str,
|
||||
search: Option<&str>,
|
||||
) -> anyhow::Result<Vec<LibraryItem>> {
|
||||
let mut q = vec![("library", library)];
|
||||
if let Some(s) = search {
|
||||
q.push(("search", s));
|
||||
}
|
||||
self.send(self.http.get(self.url("/items")).query(&q), "list items")
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_export(&self, item_id: &str) -> anyhow::Result<Export> {
|
||||
self.send(
|
||||
self.http
|
||||
.post(self.url("/exports"))
|
||||
.json(&serde_json::json!({ "item_id": item_id })),
|
||||
"create export",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn export(&self, id: &str) -> anyhow::Result<Export> {
|
||||
self.send(
|
||||
self.http.get(self.url(&format!("/exports/{id}"))),
|
||||
"get export",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub fn file_url(&self, export_id: &str, idx: usize) -> String {
|
||||
self.url(&format!("/exports/{export_id}/files/{idx}"))
|
||||
}
|
||||
|
||||
pub async fn complete_export(&self, id: &str) -> anyhow::Result<Export> {
|
||||
self.send(
|
||||
self.http.post(self.url(&format!("/exports/{id}/complete"))),
|
||||
"clean up source",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn create_job(&self, req: &CreateJob) -> anyhow::Result<Job> {
|
||||
self.send(self.http.post(self.url("/jobs")).json(req), "start job")
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn jobs(&self) -> anyhow::Result<Vec<Job>> {
|
||||
self.send(self.http.get(self.url("/jobs")), "list jobs")
|
||||
.await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
//! Destination side of a move: drives a job through its stages.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, bail};
|
||||
use jm_core::job::ExportInfo;
|
||||
use jm_core::paths::join_relative;
|
||||
use jm_core::userdata::{ItemKey, same_user};
|
||||
use jm_core::{ItemKind, Job, JobStatus, Stage};
|
||||
use jm_jellyfin::ItemQuery;
|
||||
|
||||
use crate::export::ExportStatus;
|
||||
use crate::state::Shared;
|
||||
|
||||
enum Flow {
|
||||
Continue,
|
||||
Stop,
|
||||
}
|
||||
|
||||
/// Re-queue jobs that were active when the daemon last stopped.
|
||||
pub async fn resume_all(state: &Shared) -> anyhow::Result<()> {
|
||||
for job in state.store.active_jobs().await? {
|
||||
tracing::info!(job = %job.id, name = %job.name, stage = ?job.stage, "resuming job");
|
||||
start(state.clone(), job);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Run a job in the background. A job that is already running is ignored.
|
||||
pub fn start(state: Shared, mut job: Job) {
|
||||
if !state.running.lock().expect("lock").insert(job.id) {
|
||||
return;
|
||||
}
|
||||
tokio::spawn(async move {
|
||||
job.status = JobStatus::Queued;
|
||||
let _ = state.save(&job).await;
|
||||
let _permit = state
|
||||
.job_slots
|
||||
.clone()
|
||||
.acquire_owned()
|
||||
.await
|
||||
.expect("semaphore closed");
|
||||
job.status = JobStatus::Running;
|
||||
job.note(format!("started at stage {:?}", job.stage));
|
||||
let _ = state.save(&job).await;
|
||||
|
||||
loop {
|
||||
if job.stage == Stage::Done {
|
||||
job.status = JobStatus::Done;
|
||||
job.note("move complete");
|
||||
break;
|
||||
}
|
||||
match step(&state, &mut job).await {
|
||||
Ok(Flow::Continue) => {
|
||||
let _ = state.save(&job).await;
|
||||
}
|
||||
Ok(Flow::Stop) => break,
|
||||
Err(e) => {
|
||||
let msg = format!("{e:#}");
|
||||
tracing::warn!(job = %job.id, stage = ?job.stage, error = %msg, "job failed");
|
||||
job.note(format!("failed: {msg}"));
|
||||
job.status = JobStatus::Failed(msg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Err(e) = state.save(&job).await {
|
||||
tracing::error!(job = %job.id, error = %e, "could not save job");
|
||||
}
|
||||
state.running.lock().expect("lock").remove(&job.id);
|
||||
});
|
||||
}
|
||||
|
||||
async fn step(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
|
||||
match job.stage {
|
||||
Stage::Created => plan(state, job).await,
|
||||
Stage::ExportReady => copy(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::Copied => promote(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::Promoted => wait_for_scan(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::TargetScanned => apply_user_data(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::UserDataApplied => clean_source(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::SourceCleaned => finish(state, job).await.map(|_| Flow::Continue),
|
||||
Stage::Done => Ok(Flow::Stop),
|
||||
}
|
||||
}
|
||||
|
||||
fn info(job: &Job) -> anyhow::Result<&ExportInfo> {
|
||||
job.export.as_ref().context("job has no export info")
|
||||
}
|
||||
|
||||
fn target_jellyfin(job: &Job) -> anyhow::Result<PathBuf> {
|
||||
Ok(PathBuf::from(
|
||||
job.target_folder_jellyfin
|
||||
.as_deref()
|
||||
.context("job has no target folder")?,
|
||||
))
|
||||
}
|
||||
|
||||
/// Destination library location (local path) that holds the target folder.
|
||||
fn target_library_root(state: &Shared, job: &Job) -> anyhow::Result<PathBuf> {
|
||||
let info = info(job)?;
|
||||
let target = target_jellyfin(job)?;
|
||||
let depth = info.rel_folder.split('/').count();
|
||||
let mut root = target.as_path();
|
||||
for _ in 0..depth {
|
||||
root = root
|
||||
.parent()
|
||||
.context("target folder is shallower than expected")?;
|
||||
}
|
||||
Ok(state.cfg.path_map.to_local(root))
|
||||
}
|
||||
|
||||
async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
|
||||
let peer = state.peer()?;
|
||||
if job.export_id.is_none() {
|
||||
let export = peer.create_export(&job.source_item_id).await?;
|
||||
job.note("source is checking and hashing the item");
|
||||
job.export_id = Some(export.id);
|
||||
state.save(job).await?;
|
||||
}
|
||||
let export_id = job.export_id.clone().expect("set above");
|
||||
|
||||
// Hashing a 50 GB remux takes a while on slow disks; just keep polling.
|
||||
let export = loop {
|
||||
let e = peer.export(&export_id).await?;
|
||||
match &e.status {
|
||||
ExportStatus::Ready => break e,
|
||||
ExportStatus::Preparing => tokio::time::sleep(Duration::from_secs(2)).await,
|
||||
ExportStatus::Failed(why) => bail!("source refused: {why}"),
|
||||
ExportStatus::Completed => bail!("source already completed this export"),
|
||||
}
|
||||
};
|
||||
let info = export.info.context("source sent no item info")?;
|
||||
|
||||
// Choose the destination library.
|
||||
let wanted = state
|
||||
.cfg
|
||||
.incoming_libraries
|
||||
.get(&info.library_name)
|
||||
.unwrap_or(&info.library_name)
|
||||
.clone();
|
||||
let libraries = state.jellyfin.virtual_folders().await?;
|
||||
let lib = libraries
|
||||
.iter()
|
||||
.find(|l| l.name == wanted)
|
||||
.with_context(|| {
|
||||
format!(
|
||||
"this server has no library called \"{wanted}\". Create it, or map it with \
|
||||
incoming_libraries.\"{}\" = \"<local library>\"",
|
||||
info.library_name
|
||||
)
|
||||
})?;
|
||||
let expected = match info.kind {
|
||||
ItemKind::Movie => "movies",
|
||||
ItemKind::Series => "tvshows",
|
||||
};
|
||||
if let Some(ct) = &lib.collection_type {
|
||||
if ct != expected {
|
||||
bail!(
|
||||
"library \"{}\" holds {ct}, but {} is a {:?}",
|
||||
lib.name,
|
||||
info.name,
|
||||
info.kind
|
||||
);
|
||||
}
|
||||
}
|
||||
let location = lib
|
||||
.locations
|
||||
.first()
|
||||
.context("destination library has no folders")?;
|
||||
let target = join_relative(Path::new(location), &info.rel_folder)
|
||||
.context("unsafe folder name from source")?;
|
||||
let target_local = state.cfg.path_map.to_local(&target);
|
||||
if tokio::fs::metadata(&target_local).await.is_ok() {
|
||||
bail!(
|
||||
"{} already exists on this server; refusing to merge into it",
|
||||
target_local.display()
|
||||
);
|
||||
}
|
||||
|
||||
job.name = info.name.clone();
|
||||
job.progress.bytes_total = info.manifest.total_bytes();
|
||||
job.target_library = Some(lib.name.clone());
|
||||
job.target_folder_jellyfin = Some(target.display().to_string());
|
||||
job.note(format!(
|
||||
"plan: {} files, {} into \"{}\" at {}",
|
||||
info.manifest.files.len(),
|
||||
human_bytes(job.progress.bytes_total),
|
||||
lib.name,
|
||||
target.display()
|
||||
));
|
||||
job.export = Some(info);
|
||||
|
||||
if job.dry_run {
|
||||
job.status = JobStatus::Planned;
|
||||
job.note("dry run: stopping before anything is copied");
|
||||
return Ok(Flow::Stop);
|
||||
}
|
||||
job.advance(Stage::ExportReady);
|
||||
Ok(Flow::Continue)
|
||||
}
|
||||
|
||||
async fn copy(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let peer = state.peer()?;
|
||||
let export_id = job.export_id.clone().context("no export")?;
|
||||
let files = info(job)?.manifest.files.clone();
|
||||
let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string());
|
||||
jm_transfer::prepare_partial(&partial).await?;
|
||||
|
||||
let mut done_before: u64 = 0;
|
||||
let mut last_emit = Instant::now();
|
||||
let mut last_save = Instant::now();
|
||||
for (idx, entry) in files.iter().enumerate() {
|
||||
job.progress.current_file = Some(entry.rel_path.clone());
|
||||
let url = peer.file_url(&export_id, idx);
|
||||
let part = jm_transfer::part_path(&partial, idx);
|
||||
let base = done_before;
|
||||
let snapshot_state = state.clone();
|
||||
let mut snapshot = job.clone();
|
||||
let mut on_progress = |have: u64| {
|
||||
if last_emit.elapsed() >= Duration::from_millis(500) {
|
||||
snapshot.progress.bytes_done = base + have;
|
||||
let _ = snapshot_state.events.send(snapshot.clone());
|
||||
last_emit = Instant::now();
|
||||
}
|
||||
if last_save.elapsed() >= Duration::from_secs(2) {
|
||||
snapshot.progress.bytes_done = base + have;
|
||||
let (st, snap) = (snapshot_state.clone(), snapshot.clone());
|
||||
tokio::spawn(async move {
|
||||
let _ = st.store.put_job(&snap).await;
|
||||
});
|
||||
last_save = Instant::now();
|
||||
}
|
||||
};
|
||||
state
|
||||
.puller
|
||||
.pull_verified(&url, entry, &part, &mut on_progress)
|
||||
.await
|
||||
.with_context(|| format!("copying {}", entry.rel_path))?;
|
||||
done_before += entry.size;
|
||||
job.progress.bytes_done = done_before;
|
||||
if last_save.elapsed() >= Duration::from_secs(2) {
|
||||
state.save(job).await?;
|
||||
last_save = Instant::now();
|
||||
}
|
||||
}
|
||||
job.progress.current_file = None;
|
||||
job.note(format!("copied and verified {} files", files.len()));
|
||||
job.advance(Stage::Copied);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn promote(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let partial = jm_transfer::partial_dir(&target_library_root(state, job)?, &job.id.to_string());
|
||||
let target_local = state.cfg.path_map.to_local(&target_jellyfin(job)?);
|
||||
jm_transfer::promote(&partial, &target_local, &info(job)?.manifest).await?;
|
||||
job.note(format!("moved into {}", target_local.display()));
|
||||
job.advance(Stage::Promoted);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn wait_for_scan(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let target = target_jellyfin(job)?;
|
||||
let target_str = target.display().to_string();
|
||||
state
|
||||
.jellyfin
|
||||
.media_updated(std::slice::from_ref(&target_str))
|
||||
.await?;
|
||||
job.note(
|
||||
"asked Jellyfin to scan the new folder (it waits LibraryMonitorDelay, 60 s by default)",
|
||||
);
|
||||
state.save(job).await?;
|
||||
|
||||
let info = info(job)?.clone();
|
||||
let deadline = Instant::now() + Duration::from_secs(state.cfg.transfer.scan_timeout_secs);
|
||||
let mut nudged = false;
|
||||
loop {
|
||||
if let Some(id) = find_new_item(state, job, &info, &target).await? {
|
||||
let missing = missing_episodes(state, &id, &info).await?;
|
||||
if missing == 0 {
|
||||
job.target_item_id = Some(id);
|
||||
job.note("Jellyfin has indexed the item");
|
||||
job.advance(Stage::TargetScanned);
|
||||
return Ok(());
|
||||
}
|
||||
tracing::debug!(job = %job.id, missing, "waiting for episodes to appear");
|
||||
}
|
||||
if Instant::now() > deadline {
|
||||
bail!(
|
||||
"Jellyfin hadn't indexed everything after {} s. Check the library on this server, \
|
||||
then retry: the copied files are in place and nothing has been deleted from the source",
|
||||
state.cfg.transfer.scan_timeout_secs
|
||||
);
|
||||
}
|
||||
// Halfway through, nudge again in case the first update was dropped.
|
||||
if !nudged
|
||||
&& deadline.saturating_duration_since(Instant::now()).as_secs()
|
||||
< state.cfg.transfer.scan_timeout_secs / 2
|
||||
{
|
||||
let _ = state
|
||||
.jellyfin
|
||||
.media_updated(std::slice::from_ref(&target_str))
|
||||
.await;
|
||||
nudged = true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the item Jellyfin created for the moved folder, by path.
|
||||
async fn find_new_item(
|
||||
state: &Shared,
|
||||
job: &Job,
|
||||
info: &ExportInfo,
|
||||
target: &Path,
|
||||
) -> anyhow::Result<Option<String>> {
|
||||
let lib_name = job.target_library.as_deref().context("no target library")?;
|
||||
let libs = state.jellyfin.virtual_folders().await?;
|
||||
let lib = libs
|
||||
.iter()
|
||||
.find(|l| l.name == lib_name)
|
||||
.context("target library disappeared")?;
|
||||
let kind = match info.kind {
|
||||
ItemKind::Movie => "Movie",
|
||||
ItemKind::Series => "Series",
|
||||
};
|
||||
let matches = |p: &str| match info.kind {
|
||||
ItemKind::Movie => Path::new(p).parent() == Some(target),
|
||||
ItemKind::Series => Path::new(p) == target,
|
||||
};
|
||||
// Search by name first (cheap), then fall back to listing the library.
|
||||
for search in [Some(info.name.as_str()), None] {
|
||||
let items = state
|
||||
.jellyfin
|
||||
.items(&ItemQuery {
|
||||
parent_id: Some(&lib.item_id),
|
||||
include_types: &[kind],
|
||||
recursive: true,
|
||||
search,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
if let Some(found) = items
|
||||
.into_iter()
|
||||
.find(|i| i.path.as_deref().is_some_and(matches))
|
||||
{
|
||||
return Ok(Some(found.id));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn episode_ids(state: &Shared, series_id: &str) -> anyhow::Result<HashMap<ItemKey, String>> {
|
||||
let eps = state
|
||||
.jellyfin
|
||||
.items(&ItemQuery {
|
||||
parent_id: Some(series_id),
|
||||
include_types: &["Episode"],
|
||||
recursive: true,
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
Ok(eps
|
||||
.into_iter()
|
||||
.filter_map(|e| {
|
||||
Some((
|
||||
ItemKey::Episode {
|
||||
season: e.parent_index_number?,
|
||||
episode: e.index_number?,
|
||||
},
|
||||
e.id,
|
||||
))
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn missing_episodes(
|
||||
state: &Shared,
|
||||
series_id: &str,
|
||||
info: &ExportInfo,
|
||||
) -> anyhow::Result<usize> {
|
||||
if info.kind != ItemKind::Series || info.episode_keys.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let found = episode_ids(state, series_id).await?;
|
||||
Ok(info
|
||||
.episode_keys
|
||||
.iter()
|
||||
.filter(|k| !found.contains_key(k))
|
||||
.count())
|
||||
}
|
||||
|
||||
async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let info = info(job)?.clone();
|
||||
let root_id = job.target_item_id.clone().context("no target item")?;
|
||||
let episodes = if info.kind == ItemKind::Series {
|
||||
episode_ids(state, &root_id).await?
|
||||
} else {
|
||||
HashMap::new()
|
||||
};
|
||||
let users = state.jellyfin.users().await?;
|
||||
|
||||
let (mut applied, mut no_user, mut no_item) = (0, 0, 0);
|
||||
let mut unknown_users: Vec<String> = Vec::new();
|
||||
for rec in &info.user_data {
|
||||
let Some(user) = users.iter().find(|u| same_user(&u.name, &rec.user_name)) else {
|
||||
no_user += 1;
|
||||
if !unknown_users.contains(&rec.user_name) {
|
||||
unknown_users.push(rec.user_name.clone());
|
||||
}
|
||||
continue;
|
||||
};
|
||||
let item_id = match rec.key {
|
||||
ItemKey::Root => Some(&root_id),
|
||||
key => episodes.get(&key),
|
||||
};
|
||||
let Some(item_id) = item_id else {
|
||||
no_item += 1;
|
||||
continue;
|
||||
};
|
||||
state
|
||||
.jellyfin
|
||||
.set_user_data(&user.id, item_id, &rec.data)
|
||||
.await?;
|
||||
applied += 1;
|
||||
}
|
||||
job.note(format!("restored {applied} watch-state records"));
|
||||
if no_user > 0 {
|
||||
job.note(format!(
|
||||
"skipped {no_user} records for users missing on this server: {}",
|
||||
unknown_users.join(", ")
|
||||
));
|
||||
}
|
||||
if no_item > 0 {
|
||||
job.note(format!(
|
||||
"skipped {no_item} records whose episode wasn't found"
|
||||
));
|
||||
}
|
||||
job.advance(Stage::UserDataApplied);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let export_id = job.export_id.clone().context("no export")?;
|
||||
state.peer()?.complete_export(&export_id).await?;
|
||||
job.note("source folder moved to its trash and source library rescanned");
|
||||
job.advance(Stage::SourceCleaned);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finish(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
if let Some(cmd) = state
|
||||
.cfg
|
||||
.hooks
|
||||
.post_move
|
||||
.as_deref()
|
||||
.filter(|c| !c.trim().is_empty())
|
||||
{
|
||||
let mut command = if cfg!(windows) {
|
||||
let mut c = tokio::process::Command::new("cmd");
|
||||
c.arg("/C").arg(cmd);
|
||||
c
|
||||
} else {
|
||||
let mut c = tokio::process::Command::new("sh");
|
||||
c.arg("-c").arg(cmd);
|
||||
c
|
||||
};
|
||||
command.env("JELLYMOVE_ITEM_NAME", &job.name).env(
|
||||
"JELLYMOVE_TARGET_FOLDER",
|
||||
job.target_folder_jellyfin.as_deref().unwrap_or_default(),
|
||||
);
|
||||
// A failing hook is reported but doesn't undo a finished move.
|
||||
match tokio::time::timeout(Duration::from_secs(300), command.output()).await {
|
||||
Ok(Ok(out)) if out.status.success() => job.note("post-move hook ran"),
|
||||
Ok(Ok(out)) => job.note(format!(
|
||||
"post-move hook exited with {}: {}",
|
||||
out.status,
|
||||
String::from_utf8_lossy(&out.stderr).trim()
|
||||
)),
|
||||
Ok(Err(e)) => job.note(format!("post-move hook could not start: {e}")),
|
||||
Err(_) => job.note("post-move hook timed out after 5 minutes"),
|
||||
}
|
||||
}
|
||||
job.advance(Stage::Done);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn human_bytes(b: u64) -> String {
|
||||
const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"];
|
||||
let mut v = b as f64;
|
||||
let mut u = 0;
|
||||
while v >= 1000.0 && u < UNITS.len() - 1 {
|
||||
v /= 1000.0;
|
||||
u += 1;
|
||||
}
|
||||
if u == 0 {
|
||||
format!("{b} B")
|
||||
} else {
|
||||
format!("{v:.1} {}", UNITS[u])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
use std::collections::HashSet;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use jm_core::{Job, JobId};
|
||||
use jm_store::Store;
|
||||
use jm_transfer::{Puller, PullerOptions};
|
||||
use tokio::sync::{Semaphore, broadcast};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::peer::PeerClient;
|
||||
|
||||
pub struct AppState {
|
||||
pub cfg: Config,
|
||||
pub store: Store,
|
||||
pub jellyfin: jm_jellyfin::Client,
|
||||
pub peer: Option<PeerClient>,
|
||||
pub puller: Puller,
|
||||
/// Job snapshots for the UI's live view.
|
||||
pub events: broadcast::Sender<Job>,
|
||||
pub job_slots: Arc<Semaphore>,
|
||||
pub running: Mutex<HashSet<JobId>>,
|
||||
/// Exports currently being hashed, so a duplicate request doesn't start a second pass.
|
||||
pub preparing: Mutex<HashSet<String>>,
|
||||
}
|
||||
|
||||
pub type Shared = Arc<AppState>;
|
||||
|
||||
impl AppState {
|
||||
pub fn new(cfg: Config, store: Store) -> anyhow::Result<Self> {
|
||||
let jellyfin = jm_jellyfin::Client::new(&cfg.jellyfin.url, &cfg.jellyfin.api_key)?;
|
||||
// Transfers can run for hours; only bound the connect phase.
|
||||
let http = reqwest::Client::builder()
|
||||
.connect_timeout(std::time::Duration::from_secs(20))
|
||||
.read_timeout(std::time::Duration::from_secs(120))
|
||||
.build()?;
|
||||
let peer = cfg
|
||||
.peer
|
||||
.as_ref()
|
||||
.map(|p| PeerClient::new(http.clone(), &p.url, &p.token));
|
||||
let puller = Puller::new(
|
||||
http,
|
||||
PullerOptions {
|
||||
token: cfg.peer.as_ref().map(|p| p.token.clone()),
|
||||
bytes_per_sec: cfg.bytes_per_sec(),
|
||||
attempts: cfg.transfer.retries.max(1),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let (events, _) = broadcast::channel(256);
|
||||
let slots = cfg.transfer.max_concurrent_jobs.max(1);
|
||||
Ok(Self {
|
||||
cfg,
|
||||
store,
|
||||
jellyfin,
|
||||
peer,
|
||||
puller,
|
||||
events,
|
||||
job_slots: Arc::new(Semaphore::new(slots)),
|
||||
running: Mutex::new(HashSet::new()),
|
||||
preparing: Mutex::new(HashSet::new()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn peer(&self) -> anyhow::Result<&PeerClient> {
|
||||
self.peer
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("no peer is configured on this node"))
|
||||
}
|
||||
|
||||
/// Save a job and tell anyone watching.
|
||||
pub async fn save(&self, job: &Job) -> anyhow::Result<()> {
|
||||
self.store.put_job(job).await?;
|
||||
let _ = self.events.send(job.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! The web UI, compiled into the binary. Build it with `npm --prefix ui run build`
|
||||
//! before `cargo build --release`; in debug builds files are read from disk.
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{StatusCode, Uri, header};
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use rust_embed::RustEmbed;
|
||||
|
||||
#[derive(RustEmbed)]
|
||||
#[folder = "../../ui/dist"]
|
||||
#[allow_missing = true]
|
||||
struct Assets;
|
||||
|
||||
pub async fn serve(uri: Uri) -> Response {
|
||||
let path = uri.path().trim_start_matches('/');
|
||||
if path.starts_with("api/") || path.starts_with("peer/") {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
if let Some(r) = asset(if path.is_empty() { "index.html" } else { path }) {
|
||||
return r;
|
||||
}
|
||||
// Single-page app: unknown paths get the shell.
|
||||
asset("index.html").unwrap_or_else(|| {
|
||||
(
|
||||
StatusCode::OK,
|
||||
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
|
||||
"<h1>jellymove</h1><p>The web UI wasn't built into this binary. \
|
||||
Run <code>npm --prefix ui ci && npm --prefix ui run build</code>, then rebuild.</p>",
|
||||
)
|
||||
.into_response()
|
||||
})
|
||||
}
|
||||
|
||||
fn asset(path: &str) -> Option<Response> {
|
||||
let file = Assets::get(path)?;
|
||||
let mime = mime_guess::from_path(path).first_or_octet_stream();
|
||||
// Vite fingerprints everything under assets/, so it can be cached forever.
|
||||
let cache = if path.starts_with("assets/") {
|
||||
"public, max-age=31536000, immutable"
|
||||
} else {
|
||||
"no-cache"
|
||||
};
|
||||
Some(
|
||||
Response::builder()
|
||||
.header(header::CONTENT_TYPE, mime.as_ref())
|
||||
.header(header::CACHE_CONTROL, cache)
|
||||
.body(Body::from(file.data.into_owned()))
|
||||
.expect("valid response"),
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user