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
@@ -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<()> {
|
||||
|
||||
Reference in new issue
Block a user