Relay device-sync v4 and keep podcast queue items
Use the shared music_dht::device_sync types instead of private copies (byte-identical for v3 content, checked against the 0.12.x types and a golden fixture) and announce protocol 4, because every v4 element is kept: - podcast operations stay in the operation log and are relayed only to peers that reported v4; their registers and the podcast snapshot sections are merged with the shared rules into an opaque relay table and returned in this server's snapshots (m_0055); - the browser bridge carries PlaybackTrack.source: items that are not library tracks keep the verbatim wire item, so podcast episodes and Jam placeholders survive the round trip; the player labels and skips them instead of dropping them; - the typed queue is persisted in queue_items_json next to queue_json, which is still written for rollback (m_0054). Peer versions come from self-reports (profile_protocol_version); relayed profiles only raise them and DeviceProfileSet no longer stores this server's constant. Invites carry the inviter's version and a DeviceProfileSet announces v4 once. Handoffs of a podcast queue to a device below v4 are refused with an update message, and its playback commands are ignored while the queue has podcast items. Jam guests see podcast items as private placeholders, which are mapped back on their commands. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
75c67026ac
commit
b558cf381e
20 files changed
+3587
-653
No files matched your search
+260
-7
@@ -29,6 +29,7 @@ use crate::youtube::{YouTubePreviewRequest, YouTubeService, YouTubeStartRequest}
|
||||
mod dto;
|
||||
mod helpers;
|
||||
mod queries;
|
||||
pub(crate) mod queue_items;
|
||||
mod rows;
|
||||
mod sharing;
|
||||
|
||||
@@ -606,7 +607,7 @@ impl PlayerDeviceHub {
|
||||
target_device_id: Option<&str>,
|
||||
jam_id: Option<&str>,
|
||||
command: &str,
|
||||
payload: serde_json::Value,
|
||||
mut payload: serde_json::Value,
|
||||
) -> Result<(), &'static str> {
|
||||
let now = current_millis();
|
||||
let mut state = self.state.lock().expect("player device hub lock");
|
||||
@@ -621,6 +622,14 @@ impl PlayerDeviceHub {
|
||||
let target_id = self
|
||||
.jam_target_device_id_locked(&state, jam)
|
||||
.ok_or("jam playback device is offline")?;
|
||||
if user_id != jam.host_user_id {
|
||||
let host_tracks = state
|
||||
.playback_state_by_user
|
||||
.get(&jam.host_user_id)
|
||||
.map(|playback| playback.tracks.clone())
|
||||
.unwrap_or_default();
|
||||
restore_jam_command_payload(command, &mut payload, &host_tracks)?;
|
||||
}
|
||||
(jam.host_user_id, target_id)
|
||||
} else {
|
||||
let target_id = match target_device_id {
|
||||
@@ -1042,11 +1051,17 @@ impl PlayerDeviceHub {
|
||||
})
|
||||
})
|
||||
.unwrap_or(user_id);
|
||||
state
|
||||
let playback = state
|
||||
.playback_state_by_user
|
||||
.get(&playback_user_id)
|
||||
.cloned()
|
||||
.map(|playback_state| playback_state_at(playback_state, now))
|
||||
.map(|playback_state| playback_state_at(playback_state, now));
|
||||
if playback_user_id == user_id {
|
||||
return playback;
|
||||
}
|
||||
// Jam participants are outside the host's trusted devices: private
|
||||
// items (podcast episodes) become opaque placeholders.
|
||||
playback.map(redact_playback_state_for_jam)
|
||||
}
|
||||
|
||||
fn jam_dtos_locked(
|
||||
@@ -1646,6 +1661,86 @@ pub struct PlayerPageTemplate {
|
||||
pub youtube_downloads_enabled: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod queue_persistence_tests {
|
||||
use super::*;
|
||||
use music_dht::device_sync::PlaybackTrack;
|
||||
|
||||
fn offline_pool() -> sqlx::PgPool {
|
||||
sqlx::postgres::PgPoolOptions::new()
|
||||
.connect_lazy("postgres://offline@127.0.0.1:1/offline")
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn request(queue_items: serde_json::Value, position: usize) -> PlaybackStateDto {
|
||||
PlaybackStateDto {
|
||||
current_track_id: Some(3),
|
||||
position_ms: 1_000,
|
||||
queue: vec![3, 4],
|
||||
queue_position: 1,
|
||||
shuffle: false,
|
||||
repeat_mode: "off".into(),
|
||||
volume: 0.5,
|
||||
queue_items: Some(queue_items),
|
||||
queue_items_position: Some(position),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn podcast_items_survive_persistence_and_reload() {
|
||||
let episode = PlaybackTrack::podcast_episode(queue_items::test_episode());
|
||||
let browser_track = queue_items::external_track_json(&episode, 1, None);
|
||||
// The browser sends `_queueItemsPayload(queue.tracks)`.
|
||||
let dto = request(
|
||||
serde_json::json!([
|
||||
{"kind": "library", "track_id": 3},
|
||||
{"kind": "external", "track": browser_track["wire_track"]},
|
||||
{"kind": "library", "track_id": 4},
|
||||
]),
|
||||
1,
|
||||
);
|
||||
let stored = stored_queue_from_request(&dto).unwrap();
|
||||
// Written to queue_items_json and read back with the legacy ids.
|
||||
let column = serde_json::to_value(&stored).unwrap();
|
||||
let loaded = queue_items::StoredQueue::from_columns(Some(&column), &[3, 4]).unwrap();
|
||||
assert_eq!(loaded, stored);
|
||||
assert_eq!(loaded.position, 1);
|
||||
let items = browser_queue_items(&offline_pool(), &loaded).await.unwrap();
|
||||
assert_eq!(
|
||||
items[0],
|
||||
serde_json::json!({"kind": "library", "track_id": 3})
|
||||
);
|
||||
assert_eq!(items[1]["kind"], "external");
|
||||
assert_eq!(items[1]["track"]["source"]["kind"], "podcast_episode");
|
||||
assert_eq!(
|
||||
queue_items::wire_track_from_browser_json(&items[1]["track"]),
|
||||
Some(episode)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_typed_queues_keep_the_legacy_ids_only() {
|
||||
let dto = request(
|
||||
serde_json::json!([{"kind": "external", "track": {"id": "x"}}]),
|
||||
0,
|
||||
);
|
||||
assert!(stored_queue_from_request(&dto).is_none());
|
||||
let legacy_only = PlaybackStateDto {
|
||||
queue_items: None,
|
||||
..request(serde_json::json!([]), 0)
|
||||
};
|
||||
assert!(stored_queue_from_request(&legacy_only).is_none());
|
||||
// Older clients do not send the new fields.
|
||||
let old: PlaybackStateDto = serde_json::from_value(serde_json::json!({
|
||||
"current_track_id": 3, "position_ms": 0, "queue": [3], "queue_position": 0,
|
||||
"shuffle": false, "repeat_mode": "off", "volume": 0.7,
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(old.queue_items.is_none());
|
||||
assert!(!serde_json::to_string(&old).unwrap().contains("queue_items"));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod page_template_tests {
|
||||
use super::*;
|
||||
@@ -5755,6 +5850,16 @@ async fn devices_select_handler(
|
||||
.and_then(normalize_device_id)
|
||||
.unwrap_or_else(|| target_device_id.clone());
|
||||
let previous_active_id = hub.active_device_id_for_commands(user.id);
|
||||
// Refuse a handoff the target cannot receive before ownership moves.
|
||||
if let Some(fed_device_id) = fed_device_id_from_virtual(&target_device_id)
|
||||
&& previous_active_id.as_deref() != Some(target_device_id.as_str())
|
||||
&& let Some(state) = hub.playback_state_json_for_commands(user.id)
|
||||
&& let Err(err) = crate::federation::handle()
|
||||
.fed_device_web_transfer_check(user.id, fed_device_id, state)
|
||||
.await
|
||||
{
|
||||
return Ok(json_error(StatusCode::CONFLICT, &format!("{err}")));
|
||||
}
|
||||
|
||||
let Some(response) = hub.select(user.id, ¤t_device_id, &target_device_id) else {
|
||||
return Ok(json_error(
|
||||
@@ -5992,6 +6097,97 @@ async fn fed_devices_sync_handler(
|
||||
}
|
||||
}
|
||||
|
||||
/// Host playback state as shown to Jam participants
|
||||
/// (`music_dht::device_sync::redact_for_jam` over the browser queue).
|
||||
fn redact_playback_state_for_jam(
|
||||
mut playback: PlayerDevicePlaybackStateDto,
|
||||
) -> PlayerDevicePlaybackStateDto {
|
||||
playback.tracks = queue_items::redact_tracks_for_jam(&playback.tracks);
|
||||
if playback
|
||||
.track
|
||||
.as_ref()
|
||||
.is_some_and(queue_items::browser_track_requires_podcast_support)
|
||||
{
|
||||
let index = usize::try_from(playback.index).unwrap_or(0);
|
||||
playback.track = playback.tracks.get(index).cloned().or_else(|| {
|
||||
Some(
|
||||
queue_items::redact_tracks_for_jam(std::slice::from_ref(playback.track.as_ref()?))
|
||||
[0]
|
||||
.clone(),
|
||||
)
|
||||
});
|
||||
}
|
||||
playback
|
||||
}
|
||||
|
||||
/// Applies the Jam privacy rules to a participant command.
|
||||
///
|
||||
/// Participants cannot add podcast episodes. A full queue they send (play or
|
||||
/// transfer) gets the host's private items back in place of the
|
||||
/// placeholders; queues that drop, duplicate or inject private items are
|
||||
/// rejected.
|
||||
fn restore_jam_command_payload(
|
||||
command: &str,
|
||||
payload: &mut serde_json::Value,
|
||||
host_tracks: &[serde_json::Value],
|
||||
) -> Result<(), &'static str> {
|
||||
const REJECTED: &str = "podcast episodes are private and cannot be changed in a jam";
|
||||
let tracks: Vec<serde_json::Value> = payload
|
||||
.get("tracks")
|
||||
.and_then(serde_json::Value::as_array)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let current = payload
|
||||
.get("track")
|
||||
.filter(|track| !track.is_null())
|
||||
.cloned();
|
||||
match command {
|
||||
"queue_add_end" | "queue_add_next" => {
|
||||
if tracks
|
||||
.iter()
|
||||
.any(queue_items::browser_track_requires_podcast_support)
|
||||
{
|
||||
return Err(REJECTED);
|
||||
}
|
||||
}
|
||||
"play_track" | "play_from_index" | "transfer_state" => {
|
||||
if !queue_items::jam_tracks_allowed(&tracks)
|
||||
|| current.as_ref().is_some_and(|track| {
|
||||
!queue_items::jam_tracks_allowed(std::slice::from_ref(track))
|
||||
})
|
||||
{
|
||||
return Err(REJECTED);
|
||||
}
|
||||
if tracks.is_empty() {
|
||||
if current
|
||||
.as_ref()
|
||||
.is_some_and(queue_items::browser_track_requires_podcast_support)
|
||||
{
|
||||
return Err(REJECTED);
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let restored = queue_items::restore_jam_tracks(host_tracks, &tracks).ok_or(REJECTED)?;
|
||||
if let Some(object) = payload.as_object_mut() {
|
||||
if current
|
||||
.as_ref()
|
||||
.is_some_and(queue_items::browser_track_requires_podcast_support)
|
||||
{
|
||||
let index = object
|
||||
.get("index")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
.unwrap_or(0) as usize;
|
||||
let track = restored.get(index).cloned().ok_or(REJECTED)?;
|
||||
object.insert("track".to_string(), track);
|
||||
}
|
||||
object.insert("tracks".to_string(), serde_json::Value::Array(restored));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stamp_jam_queue_tracks(payload: &mut serde_json::Value, user_id: i64, user_name: &str) {
|
||||
let Some(tracks) = payload
|
||||
.get_mut("tracks")
|
||||
@@ -6320,7 +6516,7 @@ async fn get_state_handler(
|
||||
};
|
||||
|
||||
let state = sqlx::query_as::<_, PlaybackStateRow>(
|
||||
r#"SELECT current_track_id, position_ms, queue_json, queue_position, shuffle, repeat_mode::text as repeat_mode, volume
|
||||
r#"SELECT current_track_id, position_ms, queue_json, queue_items_json, queue_position, shuffle, repeat_mode::text as repeat_mode, volume
|
||||
FROM furumusic__playback_state WHERE user_id = $1"#,
|
||||
)
|
||||
.bind(user.id)
|
||||
@@ -6331,6 +6527,19 @@ async fn get_state_handler(
|
||||
let dto = match state {
|
||||
Some(s) => {
|
||||
let queue: Vec<i64> = serde_json::from_str(&s.queue_json).unwrap_or_default();
|
||||
// Prefer the typed queue while it matches `queue_json`.
|
||||
let typed = queue_items::StoredQueue::from_columns(s.queue_items_json.as_ref(), &queue);
|
||||
let (queue_items, queue_items_position) = match typed {
|
||||
Some(stored) => (
|
||||
Some(
|
||||
browser_queue_items(pool, &stored)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?,
|
||||
),
|
||||
Some(stored.position),
|
||||
),
|
||||
None => (None, None),
|
||||
};
|
||||
PlaybackStateDto {
|
||||
current_track_id: s.current_track_id,
|
||||
position_ms: s.position_ms,
|
||||
@@ -6339,6 +6548,8 @@ async fn get_state_handler(
|
||||
shuffle: s.shuffle,
|
||||
repeat_mode: s.repeat_mode,
|
||||
volume: s.volume,
|
||||
queue_items,
|
||||
queue_items_position,
|
||||
}
|
||||
}
|
||||
None => PlaybackStateDto {
|
||||
@@ -6349,12 +6560,47 @@ async fn get_state_handler(
|
||||
shuffle: false,
|
||||
repeat_mode: "off".to_string(),
|
||||
volume: 0.7,
|
||||
queue_items: None,
|
||||
queue_items_position: None,
|
||||
},
|
||||
};
|
||||
|
||||
Json(dto).into_response()
|
||||
}
|
||||
|
||||
/// Typed queue items for the browser: library ids to load, external items
|
||||
/// as browser track JSON with their verbatim wire item.
|
||||
async fn browser_queue_items(
|
||||
pool: &sqlx::PgPool,
|
||||
stored: &queue_items::StoredQueue,
|
||||
) -> anyhow::Result<serde_json::Value> {
|
||||
let mut items = Vec::with_capacity(stored.items.len());
|
||||
for (index, item) in stored.items.iter().enumerate() {
|
||||
items.push(match item {
|
||||
queue_items::StoredQueueItem::Library { track_id } => {
|
||||
serde_json::json!({"kind": "library", "track_id": track_id})
|
||||
}
|
||||
queue_items::StoredQueueItem::External { track } => serde_json::json!({
|
||||
"kind": "external",
|
||||
"track": crate::federation::devices::resolve_playback_track(pool, track, index).await?,
|
||||
}),
|
||||
});
|
||||
}
|
||||
Ok(serde_json::Value::Array(items))
|
||||
}
|
||||
|
||||
/// Typed queue to persist from a state request; `None` keeps only the legacy
|
||||
/// ids (older clients, malformed or oversized queues).
|
||||
fn stored_queue_from_request(dto: &PlaybackStateDto) -> Option<queue_items::StoredQueue> {
|
||||
let items: Vec<queue_items::StoredQueueItem> =
|
||||
serde_json::from_value(dto.queue_items.clone()?).ok()?;
|
||||
queue_items::StoredQueue::new(
|
||||
items,
|
||||
dto.queue_items_position.unwrap_or(0),
|
||||
dto.queue.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// PUT /api/player/state
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -6372,15 +6618,21 @@ async fn put_state_handler(
|
||||
|
||||
let queue_json =
|
||||
serde_json::to_string(&dto.queue).map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
// `queue_json` is still written so an older release keeps working.
|
||||
let queue_items_json = stored_queue_from_request(&dto)
|
||||
.map(serde_json::to_value)
|
||||
.transpose()
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
let now = chrono::Utc::now().format("%Y-%m-%dT%H:%M:%SZ").to_string();
|
||||
|
||||
sqlx::query(
|
||||
r#"INSERT INTO furumusic__playback_state (user_id, current_track_id, position_ms, queue_json, queue_position, shuffle, repeat_mode, volume, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
r#"INSERT INTO furumusic__playback_state (user_id, current_track_id, position_ms, queue_json, queue_position, shuffle, repeat_mode, volume, updated_at, queue_items_json)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
ON CONFLICT (user_id) DO UPDATE SET
|
||||
current_track_id = $2, position_ms = $3, queue_json = $4,
|
||||
queue_position = $5, shuffle = $6, repeat_mode = $7, volume = $8, updated_at = $9"#,
|
||||
queue_position = $5, shuffle = $6, repeat_mode = $7, volume = $8, updated_at = $9,
|
||||
queue_items_json = $10"#,
|
||||
)
|
||||
.bind(user.id)
|
||||
.bind(dto.current_track_id)
|
||||
@@ -6391,6 +6643,7 @@ async fn put_state_handler(
|
||||
.bind(&dto.repeat_mode)
|
||||
.bind(dto.volume)
|
||||
.bind(&now)
|
||||
.bind(queue_items_json)
|
||||
.execute(pool)
|
||||
.await
|
||||
.map_err(|e| cot::Error::internal(e.to_string()))?;
|
||||
|
||||
Reference in new issue
Block a user