Warn before watch history is left behind, and re-apply it later (#2)
CI / test (push) Successful in 1m16s
CI / test (push) Successful in 1m16s
This commit is contained in:
1 parent
2bd4489b1a
commit
8cfa0f05eb
15 files changed
+611
-73
No files matched your search
@@ -206,6 +206,11 @@ pub struct Job {
|
||||
/// into a show the destination already has.
|
||||
#[serde(default)]
|
||||
pub skip_files: Vec<usize>,
|
||||
/// Users with watch state on the source who have no account here, so
|
||||
/// their watch state wasn't (or won't be) applied. Their records stay in
|
||||
/// `export.user_data` and can be re-applied once the account exists.
|
||||
#[serde(default)]
|
||||
pub missing_users: Vec<String>,
|
||||
pub progress: Progress,
|
||||
/// Human-readable log of what happened, newest last.
|
||||
pub log: Vec<String>,
|
||||
@@ -238,6 +243,7 @@ impl Job {
|
||||
target_item_id: None,
|
||||
target_location: None,
|
||||
skip_files: Vec::new(),
|
||||
missing_users: Vec::new(),
|
||||
progress: Progress::default(),
|
||||
log: Vec::new(),
|
||||
}
|
||||
|
||||
@@ -51,10 +51,39 @@ pub fn same_user(a: &str, b: &str) -> bool {
|
||||
a.trim().eq_ignore_ascii_case(b.trim())
|
||||
}
|
||||
|
||||
/// Users with watch state in `records` who have no account among `users`,
|
||||
/// each named once, in the order they first appear.
|
||||
pub fn missing_users<'a>(
|
||||
records: &'a [UserDataRecord],
|
||||
users: impl IntoIterator<Item = &'a str> + Clone,
|
||||
) -> Vec<String> {
|
||||
let mut out: Vec<String> = Vec::new();
|
||||
for r in records {
|
||||
let known = users.clone().into_iter().any(|u| same_user(u, &r.user_name));
|
||||
if !known && !out.iter().any(|m| same_user(m, &r.user_name)) {
|
||||
out.push(r.user_name.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn finds_users_with_no_account() {
|
||||
let rec = |name: &str| UserDataRecord {
|
||||
user_name: name.into(),
|
||||
key: ItemKey::Root,
|
||||
data: UserData::default(),
|
||||
};
|
||||
let records = [rec("Alice"), rec("Bob"), rec("bob "), rec("Carol")];
|
||||
let here = ["alice", "Carol"];
|
||||
assert_eq!(missing_users(&records, here.iter().copied()), ["Bob"]);
|
||||
assert!(missing_users(&records[..1], here.iter().copied()).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_detection() {
|
||||
assert!(UserData::default().is_empty());
|
||||
|
||||
@@ -44,9 +44,14 @@ fn libs(root: &Path) -> Vec<Lib> {
|
||||
#[tokio::main]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
tracing_subscriber_init();
|
||||
let tmp = tempfile::tempdir()?;
|
||||
let cloud = tmp.path().join("cloud");
|
||||
let home = tmp.path().join("home");
|
||||
// One fixed folder, emptied on each start: a temp folder per run would
|
||||
// be left behind (hundreds of MB) whenever the demo is killed.
|
||||
let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/demo");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
std::fs::create_dir_all(&root)?;
|
||||
let root = root.canonicalize()?;
|
||||
let cloud = root.join("cloud");
|
||||
let home = root.join("home");
|
||||
for r in [&cloud, &home] {
|
||||
std::fs::create_dir_all(r.join("movies"))?;
|
||||
std::fs::create_dir_all(r.join("tv"))?;
|
||||
@@ -82,7 +87,11 @@ async fn main() -> anyhow::Result<()> {
|
||||
|
||||
let fake_cloud = Fake::new(libs(&cloud));
|
||||
let fake_home = Fake::new(libs(&home));
|
||||
// Bob only has an account on cloud, so his watch history can't follow a
|
||||
// move to home until one is created there.
|
||||
fake_cloud.add_user("u2", "Bob");
|
||||
if let Some(id) = fake_cloud.find("Movie", "Arrival") {
|
||||
fake_cloud.set_user_data_for("u2", &id, serde_json::json!({"PlaybackPositionTicks": 36_000_000_000i64}));
|
||||
fake_cloud.set_user_data(&id, serde_json::json!({"Played": true, "PlayCount": 1}));
|
||||
}
|
||||
let jf_cloud = fake_cloud.serve().await;
|
||||
@@ -124,7 +133,7 @@ async fn main() -> anyhow::Result<()> {
|
||||
axum::serve(listener, jm_server::api::router(state)).await
|
||||
}));
|
||||
}
|
||||
println!("demo media in {}", tmp.path().display());
|
||||
println!("demo media in {}", root.display());
|
||||
println!("cloud: http://127.0.0.1:8097 home: http://127.0.0.1:8098 (Ctrl+C to stop)");
|
||||
tokio::signal::ctrl_c().await?;
|
||||
Ok(())
|
||||
|
||||
@@ -61,8 +61,10 @@ pub fn router(state: Shared) -> Router {
|
||||
.route("/items", get(ui_items))
|
||||
.route("/seasons", get(ui_seasons))
|
||||
.route("/moves", post(ui_move))
|
||||
.route("/moves/check", get(ui_check_move))
|
||||
.route("/jobs", get(ui_jobs))
|
||||
.route("/jobs/{id}/retry", post(ui_retry))
|
||||
.route("/jobs/{id}/reapply", post(ui_reapply))
|
||||
.route("/trash", get(ui_trash))
|
||||
.route("/trash/empty", post(ui_empty_trash))
|
||||
.route("/events", get(events));
|
||||
@@ -77,6 +79,9 @@ pub fn router(state: Shared) -> Router {
|
||||
.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))
|
||||
.route("/jobs/{id}/reapply", post(peer_reapply))
|
||||
.route("/users", get(peer_users))
|
||||
.route("/watchers", get(peer_watchers))
|
||||
.route("/trash", get(peer_trash))
|
||||
.route("/trash/empty", post(peer_empty_trash))
|
||||
.layer(middleware::from_fn_with_state(
|
||||
@@ -337,6 +342,72 @@ async fn ui_jobs(State(state): State<Shared>) -> ApiResult<JobsView> {
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CheckMoveQuery {
|
||||
/// Where the item is now.
|
||||
from: Side,
|
||||
item_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct MoveCheck {
|
||||
/// Users with watch state for the item on the source.
|
||||
watchers: Vec<String>,
|
||||
/// Those of them with no account on the destination, whose watch state
|
||||
/// won't carry over.
|
||||
missing_users: Vec<String>,
|
||||
}
|
||||
|
||||
/// Before a move: whose watch history wouldn't carry over, because the
|
||||
/// destination has no user with that name.
|
||||
async fn ui_check_move(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<CheckMoveQuery>,
|
||||
) -> ApiResult<MoveCheck> {
|
||||
let peer = state.peer()?;
|
||||
let (watchers, dest_users) = match q.from {
|
||||
Side::Local => (
|
||||
export::watchers(&state, &q.item_id).await?,
|
||||
peer.users().await?,
|
||||
),
|
||||
Side::Peer => (
|
||||
peer.watchers(&q.item_id).await?,
|
||||
state
|
||||
.jellyfin
|
||||
.users()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|u| u.name)
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
let missing_users = watchers
|
||||
.iter()
|
||||
.filter(|w| !dest_users.iter().any(|u| jm_core::userdata::same_user(u, w)))
|
||||
.cloned()
|
||||
.collect();
|
||||
Ok(Json(MoveCheck {
|
||||
watchers,
|
||||
missing_users,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Re-apply skipped watch history on a finished move. The job lives on the
|
||||
/// destination, which may be the peer.
|
||||
async fn ui_reapply(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
|
||||
let job_id: JobId = id
|
||||
.parse()
|
||||
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?;
|
||||
match state.store.get_job(job_id).await? {
|
||||
Some(job) => {
|
||||
let mut job = runner::reapply_user_data(&state, job).await?;
|
||||
job.export = None;
|
||||
Ok(Json(job))
|
||||
}
|
||||
None => Ok(Json(state.peer()?.reapply(&id).await?)),
|
||||
}
|
||||
}
|
||||
|
||||
async fn ui_retry(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
|
||||
let id: JobId = id
|
||||
.parse()
|
||||
@@ -518,6 +589,44 @@ async fn peer_create_job(
|
||||
Ok(Json(job))
|
||||
}
|
||||
|
||||
async fn peer_reapply(State(state): State<Shared>, Path(id): Path<String>) -> ApiResult<Job> {
|
||||
let job_id: JobId = id
|
||||
.parse()
|
||||
.map_err(|_| ApiError(StatusCode::BAD_REQUEST, "bad job id".into()))?;
|
||||
let job = state
|
||||
.store
|
||||
.get_job(job_id)
|
||||
.await?
|
||||
.ok_or(ApiError(StatusCode::NOT_FOUND, "no such job".into()))?;
|
||||
let mut job = runner::reapply_user_data(&state, job).await?;
|
||||
job.export = None;
|
||||
Ok(Json(job))
|
||||
}
|
||||
|
||||
async fn peer_users(State(state): State<Shared>) -> ApiResult<Vec<String>> {
|
||||
Ok(Json(
|
||||
state
|
||||
.jellyfin
|
||||
.users()
|
||||
.await?
|
||||
.into_iter()
|
||||
.map(|u| u.name)
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct WatchersQuery {
|
||||
item: String,
|
||||
}
|
||||
|
||||
async fn peer_watchers(
|
||||
State(state): State<Shared>,
|
||||
Query(q): Query<WatchersQuery>,
|
||||
) -> ApiResult<Vec<String>> {
|
||||
Ok(Json(export::watchers(&state, &q.item).await?))
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -288,48 +288,7 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo,
|
||||
}
|
||||
|
||||
// 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? {
|
||||
// A season's own watch state isn't carried: on the destination it
|
||||
// would land on the whole show.
|
||||
if kind != ItemKind::Season {
|
||||
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.has_episodes() {
|
||||
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 (user_data, episode_keys) = capture_user_data(state, item_id, kind).await?;
|
||||
|
||||
let (name, season) = match season {
|
||||
None => (item.name, None),
|
||||
@@ -369,6 +328,78 @@ async fn prepare(state: &AppState, item_id: &str) -> anyhow::Result<(ExportInfo,
|
||||
Ok((info, folder.display().to_string(), location))
|
||||
}
|
||||
|
||||
/// Every user's watch state for an item: the item itself (not for a season,
|
||||
/// whose own state would land on the whole show at the destination) and, for
|
||||
/// shows and seasons, each episode. Also returns every episode's key.
|
||||
pub async fn capture_user_data(
|
||||
state: &AppState,
|
||||
item_id: &str,
|
||||
kind: ItemKind,
|
||||
) -> anyhow::Result<(Vec<UserDataRecord>, Vec<ItemKey>)> {
|
||||
let jf = &state.jellyfin;
|
||||
let mut user_data = Vec::new();
|
||||
let mut episode_keys = Vec::new();
|
||||
for user in jf.users().await? {
|
||||
if kind != ItemKind::Season {
|
||||
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.has_episodes() {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((user_data, episode_keys))
|
||||
}
|
||||
|
||||
/// Names of the users who have watch state for an item, for the check before
|
||||
/// a move.
|
||||
pub async fn watchers(state: &AppState, item_id: &str) -> anyhow::Result<Vec<String>> {
|
||||
let item = state.jellyfin.item(item_id).await?;
|
||||
let kind = match item.kind.as_str() {
|
||||
"Movie" => ItemKind::Movie,
|
||||
"Series" => ItemKind::Series,
|
||||
"Season" => ItemKind::Season,
|
||||
other => bail!("can only move movies, shows and seasons, not {other}"),
|
||||
};
|
||||
let (records, _) = capture_user_data(state, item_id, kind).await?;
|
||||
let mut names: Vec<String> = Vec::new();
|
||||
for r in records {
|
||||
if !names.contains(&r.user_name) {
|
||||
names.push(r.user_name);
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
fn push_record(
|
||||
out: &mut Vec<UserDataRecord>,
|
||||
user: &str,
|
||||
|
||||
@@ -58,7 +58,14 @@ impl PeerClient {
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
let body = resp.text().await.unwrap_or_default();
|
||||
anyhow::bail!("peer refused {what}: HTTP {status}: {body}");
|
||||
// Our own API answers {"error": "..."}; pass on just the message.
|
||||
let message = serde_json::from_str::<serde_json::Value>(&body)
|
||||
.ok()
|
||||
.and_then(|v| v.get("error")?.as_str().map(str::to_string));
|
||||
match message {
|
||||
Some(m) => anyhow::bail!("peer refused {what}: {m}"),
|
||||
None => anyhow::bail!("peer refused {what}: HTTP {status}: {body}"),
|
||||
}
|
||||
}
|
||||
Ok(resp.json().await?)
|
||||
}
|
||||
@@ -145,6 +152,29 @@ impl PeerClient {
|
||||
.await
|
||||
}
|
||||
|
||||
/// Names of the users on the peer's Jellyfin.
|
||||
pub async fn users(&self) -> anyhow::Result<Vec<String>> {
|
||||
self.send(self.http.get(self.url("/users")), "list users")
|
||||
.await
|
||||
}
|
||||
|
||||
/// Users on the peer with watch state for one of its items.
|
||||
pub async fn watchers(&self, item_id: &str) -> anyhow::Result<Vec<String>> {
|
||||
self.send(
|
||||
self.http.get(self.url("/watchers")).query(&[("item", item_id)]),
|
||||
"check watch history",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn reapply(&self, job_id: &str) -> anyhow::Result<Job> {
|
||||
self.send(
|
||||
self.http.post(self.url(&format!("/jobs/{job_id}/reapply"))),
|
||||
"re-apply watch history",
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn jobs(&self) -> anyhow::Result<Vec<Job>> {
|
||||
self.send(self.http.get(self.url("/jobs")), "list jobs")
|
||||
.await
|
||||
|
||||
@@ -8,7 +8,7 @@ use anyhow::{Context, bail};
|
||||
use jm_core::job::{ExportInfo, SeasonInfo};
|
||||
use jm_core::paths::join_relative;
|
||||
use jm_core::safety::check_inside_library;
|
||||
use jm_core::userdata::{ItemKey, same_user};
|
||||
use jm_core::userdata::{ItemKey, UserDataRecord, missing_users, same_user};
|
||||
use jm_core::{ItemKind, Job, JobStatus, Stage};
|
||||
use jm_jellyfin::ItemQuery;
|
||||
|
||||
@@ -230,6 +230,17 @@ async fn plan(state: &Shared, job: &mut Job) -> anyhow::Result<Flow> {
|
||||
lib.name,
|
||||
));
|
||||
job.skip_files = skip;
|
||||
|
||||
// Watch state is matched to users by name; say now whose won't carry over.
|
||||
let users = state.jellyfin.users().await?;
|
||||
job.missing_users = missing_users(&info.user_data, users.iter().map(|u| u.name.as_str()));
|
||||
if !job.missing_users.is_empty() {
|
||||
job.note(format!(
|
||||
"watch history won't carry over for {}: no user with that name on this server. \
|
||||
Create them in Jellyfin here first, or re-apply it from Moves afterwards",
|
||||
job.missing_users.join(", ")
|
||||
));
|
||||
}
|
||||
job.export = Some(info);
|
||||
|
||||
if job.dry_run {
|
||||
@@ -493,6 +504,34 @@ async fn missing_episodes(
|
||||
|
||||
async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
let info = info(job)?.clone();
|
||||
let (applied, no_item, missing) = apply_records(state, job, &info.user_data).await?;
|
||||
job.note(format!("restored {applied} watch-state records"));
|
||||
if !missing.is_empty() {
|
||||
job.note(format!(
|
||||
"skipped watch history for users missing on this server: {}. \
|
||||
Create them in Jellyfin, then use Re-apply watch history in Moves",
|
||||
missing.join(", ")
|
||||
));
|
||||
}
|
||||
if no_item > 0 {
|
||||
job.note(format!(
|
||||
"skipped {no_item} records whose episode wasn't found"
|
||||
));
|
||||
}
|
||||
job.missing_users = missing;
|
||||
job.advance(Stage::UserDataApplied);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write `records` to the moved item and its episodes for every user who has
|
||||
/// an account here. Returns (records applied, records whose episode wasn't
|
||||
/// found, users with no account).
|
||||
async fn apply_records(
|
||||
state: &Shared,
|
||||
job: &Job,
|
||||
records: &[UserDataRecord],
|
||||
) -> anyhow::Result<(usize, usize, Vec<String>)> {
|
||||
let info = info(job)?;
|
||||
let root_id = job.target_item_id.clone().context("no target item")?;
|
||||
let episodes = if info.kind.has_episodes() {
|
||||
episode_ids(state, &root_id).await?
|
||||
@@ -500,15 +539,11 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
HashMap::new()
|
||||
};
|
||||
let users = state.jellyfin.users().await?;
|
||||
let missing = missing_users(records, users.iter().map(|u| u.name.as_str()));
|
||||
|
||||
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 (mut applied, mut no_item) = (0, 0);
|
||||
for rec in records {
|
||||
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 {
|
||||
@@ -525,20 +560,59 @@ async fn apply_user_data(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
.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(", ")
|
||||
));
|
||||
Ok((applied, no_item, missing))
|
||||
}
|
||||
|
||||
/// After a move, apply the watch state of users who had no account here at
|
||||
/// the time, once their accounts exist. Only their records are applied, so
|
||||
/// anything other users have watched since is left alone.
|
||||
pub async fn reapply_user_data(state: &Shared, mut job: Job) -> anyhow::Result<Job> {
|
||||
if job.dry_run || job.status != JobStatus::Done {
|
||||
bail!("watch history can only be re-applied to a finished move");
|
||||
}
|
||||
if no_item > 0 {
|
||||
job.note(format!(
|
||||
"skipped {no_item} records whose episode wasn't found"
|
||||
));
|
||||
if job.missing_users.is_empty() {
|
||||
bail!("this move has no skipped watch history to re-apply");
|
||||
}
|
||||
job.advance(Stage::UserDataApplied);
|
||||
Ok(())
|
||||
let info = info(&job)?.clone();
|
||||
let root_id = job.target_item_id.clone().context("no target item")?;
|
||||
if state.jellyfin.item(&root_id).await.is_err() {
|
||||
bail!(
|
||||
"{} is no longer where it was moved to on {} (moved again?), \
|
||||
so its watch history can't be re-applied",
|
||||
job.name,
|
||||
state.cfg.node_name
|
||||
);
|
||||
}
|
||||
let users = state.jellyfin.users().await?;
|
||||
let records: Vec<UserDataRecord> = info
|
||||
.user_data
|
||||
.iter()
|
||||
.filter(|r| job.missing_users.iter().any(|m| same_user(m, &r.user_name)))
|
||||
.cloned()
|
||||
.collect();
|
||||
let still_missing = missing_users(&records, users.iter().map(|u| u.name.as_str()));
|
||||
let here = &state.cfg.node_name;
|
||||
if still_missing.len() == job.missing_users.len() {
|
||||
bail!(
|
||||
"there's no user called {} on {here} yet; create them in Jellyfin on {here} first",
|
||||
still_missing.join(" or ")
|
||||
);
|
||||
}
|
||||
let (applied, no_item, missing) = apply_records(state, &job, &records).await?;
|
||||
job.note(format!(
|
||||
"re-applied {applied} watch-state records{}",
|
||||
if no_item > 0 {
|
||||
format!(" ({no_item} episodes not found)")
|
||||
} else {
|
||||
String::new()
|
||||
}
|
||||
));
|
||||
if !missing.is_empty() {
|
||||
job.note(format!("still no user here called: {}", missing.join(", ")));
|
||||
}
|
||||
job.missing_users = missing;
|
||||
state.save(&job).await?;
|
||||
Ok(job)
|
||||
}
|
||||
|
||||
async fn clean_source(state: &Shared, job: &mut Job) -> anyhow::Result<()> {
|
||||
|
||||
@@ -726,6 +726,95 @@ async fn refuses_a_season_folder_holding_other_seasons() {
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn warns_about_missing_users_and_reapplies_their_watch_state_later() {
|
||||
let (cloud, home) = pair(seed_movie).await;
|
||||
// Cloud has a second user, Bob, whom home doesn't know yet.
|
||||
cloud.fake.add_user("u2", "Bob");
|
||||
let movie = cloud.fake.find("Movie", "Alien").unwrap();
|
||||
cloud.fake.set_user_data(&movie, json!({"Played": true}));
|
||||
cloud
|
||||
.fake
|
||||
.set_user_data_for("u2", &movie, json!({"PlaybackPositionTicks": 777}));
|
||||
|
||||
// Before moving, the UI can see whose watch history won't carry over,
|
||||
// whichever side it asks from.
|
||||
let check = get(
|
||||
&cloud.url,
|
||||
&format!("/api/moves/check?from=local&item_id={movie}"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(check["watchers"], json!(["Alice", "Bob"]));
|
||||
assert_eq!(check["missing_users"], json!(["Bob"]));
|
||||
let check = get(
|
||||
&home.url,
|
||||
&format!("/api/moves/check?from=peer&item_id={movie}"),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(check["missing_users"], json!(["Bob"]));
|
||||
|
||||
// A dry run says so too.
|
||||
let dry: Value = post(
|
||||
&cloud.url,
|
||||
"/api/moves",
|
||||
json!({"from": "local", "item_id": movie, "name": "Alien", "dry_run": true}),
|
||||
)
|
||||
.await
|
||||
.json()
|
||||
.await
|
||||
.unwrap();
|
||||
let dry = wait_job(&cloud.url, dry["id"].as_str().unwrap()).await;
|
||||
assert_eq!(dry["status"]["kind"], "Planned");
|
||||
assert_eq!(dry["missing_users"], json!(["Bob"]));
|
||||
assert!(
|
||||
dry["log"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|l| l.as_str().unwrap().contains("won't carry over for Bob")),
|
||||
"{dry:#}"
|
||||
);
|
||||
|
||||
// The move goes ahead; Alice's watch state follows, Bob's is kept.
|
||||
let job = move_item(&cloud.url, "local", &movie, "Alien").await;
|
||||
assert_eq!(job["missing_users"], json!(["Bob"]));
|
||||
let new_id = home.fake.find("Movie", "Alien").unwrap();
|
||||
assert_eq!(home.fake.get_user_data(&new_id).unwrap()["Played"], true);
|
||||
let id = job["id"].as_str().unwrap();
|
||||
|
||||
// Re-applying before Bob has an account explains what to do.
|
||||
let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await;
|
||||
assert!(!r.status().is_success());
|
||||
let text = r.text().await.unwrap();
|
||||
assert!(
|
||||
text.contains("no user called Bob on home yet; create them in Jellyfin on home first"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("HTTP 502"), "{text}");
|
||||
|
||||
// Alice carries on watching on home in the meantime.
|
||||
home.fake
|
||||
.set_user_data(&new_id, json!({"Played": true, "PlayCount": 5}));
|
||||
|
||||
// Once home has a "bob" (names match ignoring case), re-apply from the
|
||||
// cloud UI: the job runs on home, so the request is passed on.
|
||||
home.fake.add_user("u9", "bob");
|
||||
let r = post(&cloud.url, &format!("/api/jobs/{id}/reapply"), json!({})).await;
|
||||
assert!(r.status().is_success(), "{}", r.text().await.unwrap());
|
||||
let job: Value = r.json().await.unwrap();
|
||||
assert_eq!(job["missing_users"], json!([]));
|
||||
assert_eq!(
|
||||
home.fake.get_user_data_for("u9", &new_id).unwrap()["PlaybackPositionTicks"],
|
||||
777
|
||||
);
|
||||
// Alice's newer watch state wasn't overwritten by the old snapshot.
|
||||
assert_eq!(home.fake.get_user_data(&new_id).unwrap()["PlayCount"], 5);
|
||||
|
||||
// Nothing left to re-apply.
|
||||
let r = post(&home.url, &format!("/api/jobs/{id}/reapply"), json!({})).await;
|
||||
assert!(r.text().await.unwrap().contains("no skipped watch history"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_api_rejects_bad_token_and_ui_requires_csrf_header() {
|
||||
let (cloud, _home) = pair(|_| {}).await;
|
||||
|
||||
@@ -47,6 +47,8 @@ pub struct Fake {
|
||||
items: Arc<Mutex<Vec<FakeItem>>>,
|
||||
/// (user id, item id) → UserData JSON
|
||||
pub user_data: Arc<Mutex<HashMap<(String, String), Value>>>,
|
||||
/// (user id, name)
|
||||
users: Arc<Mutex<Vec<(String, String)>>>,
|
||||
}
|
||||
|
||||
pub fn id_for(path: &Path) -> String {
|
||||
@@ -103,6 +105,7 @@ impl Fake {
|
||||
libs: Arc::new(libs),
|
||||
items: Default::default(),
|
||||
user_data: Default::default(),
|
||||
users: Arc::new(Mutex::new(vec![("u1".into(), "Alice".into())])),
|
||||
};
|
||||
f.scan();
|
||||
f
|
||||
@@ -258,6 +261,25 @@ impl Fake {
|
||||
.map(|i| i.id.clone())
|
||||
}
|
||||
|
||||
pub fn add_user(&self, id: &str, name: &str) {
|
||||
self.users.lock().unwrap().push((id.into(), name.into()));
|
||||
}
|
||||
|
||||
pub fn set_user_data_for(&self, user: &str, item: &str, data: Value) {
|
||||
self.user_data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert((user.into(), item.into()), data);
|
||||
}
|
||||
|
||||
pub fn get_user_data_for(&self, user: &str, item: &str) -> Option<Value> {
|
||||
self.user_data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&(user.to_string(), item.to_string()))
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub fn set_user_data(&self, item: &str, data: Value) {
|
||||
self.user_data
|
||||
.lock()
|
||||
@@ -281,10 +303,7 @@ impl Fake {
|
||||
Json(json!({"ServerName": "fake", "Version": "10.11.0", "Id": "x"}))
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/Users",
|
||||
get(|| async { Json(json!([{"Id": "u1", "Name": "Alice"}])) }),
|
||||
)
|
||||
.route("/Users", get(users))
|
||||
.route("/Library/VirtualFolders", get(virtual_folders))
|
||||
.route("/Items", get(items))
|
||||
.route("/Library/Media/Updated", post(media_updated))
|
||||
@@ -297,6 +316,17 @@ impl Fake {
|
||||
}
|
||||
}
|
||||
|
||||
async fn users(State(f): State<Fake>) -> Json<Value> {
|
||||
Json(Value::Array(
|
||||
f.users
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(|(id, name)| json!({"Id": id, "Name": name}))
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn virtual_folders(State(f): State<Fake>) -> Json<Value> {
|
||||
Json(Value::Array(
|
||||
f.libs
|
||||
|
||||
Reference in new issue
Block a user