Hand off podcast queues to v4 devices and keep episodes private in Jam

Queue items now cross the wire with their explicit source: episodes as
PlaybackSource::PodcastEpisode, received ones as TrackItem episodes, and
the source mode filter never drops them. A handoff carries the episode,
position and pause; an episode that becomes current at position 0
resumes from its saved position. A podcast queue is not handed to a
device below v4 (it needs an update), and playback commands from such a
device are ignored while the queue has episodes. Controlling a v4 device
may queue episodes.

Jam hosts publish redacted snapshots, so guests see numbered private
placeholders. Guest commands that add episodes are dropped; their
placeholders are mapped back to the host's episodes, and changes that
drop or duplicate them, or seek in them, are refused. A guest leaving a
Jam drops the placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
sanapachandClaude Opus 5.5 committed 2026-11-19 21:00:39 +02:00
1 parent 79372e00fc
commit a92e12f322
7 files changed
+726 -85

No files matched your search

+288 -54
View File
@@ -712,7 +712,8 @@ fn playback_state_from_ui(state: &AppState) -> crate::devices::PlaybackStateWire
}
}
fn playback_track_to_ui(
/// A received music item, resolved to the library copy when there is one.
fn music_track_to_ui(
wire: &crate::devices::PlaybackTrack,
library: Option<&Library>,
) -> crate::library::models::TrackItem {
@@ -733,11 +734,11 @@ fn apply_playback_state_to_ui(
wire: &crate::devices::PlaybackStateWire,
library: Option<&Library>,
) {
let queue: Vec<_> = wire
.queue
.iter()
.map(|track| playback_track_to_ui(track, library))
.collect();
// Podcast episodes keep their explicit source; Jam private placeholders
// stay placeholders (numbered, so each has its own queue key).
let queue = crate::devices::track_items_from_wire(&wire.queue, |track| {
music_track_to_ui(track, library)
});
let queue_pos = queue
.iter()
.take(wire.queue_pos)
@@ -777,22 +778,6 @@ fn apply_playback_state_to_ui(
.min(state.player.queue.len().saturating_sub(1));
}
/// Shown when a queue with podcast episodes would be handed to a device.
const PODCAST_HANDOFF_UNSUPPORTED: &str = "device handoff: the queue has podcast episodes, which \
other devices cannot receive with this build yet (needs sync protocol v4)";
/// Shown when another device tries to change a queue that has episodes.
const PODCAST_REMOTE_CONTROL_UNSUPPORTED: &str = "remote control ignored: the queue has podcast \
episodes, which other devices cannot see with this build yet";
fn queue_has_podcast_episodes(state: &AppState) -> bool {
state.player.queue.iter().any(|track| track.is_podcast())
|| state
.player
.current
.as_ref()
.is_some_and(|track| track.is_podcast())
}
fn publish_playback_snapshot(state: &mut AppState, runtime: &Runtime) {
if !state.device_playback.is_audio_owner() {
return;
@@ -915,12 +900,7 @@ pub(crate) fn become_active_device(state: &mut AppState, runtime: &mut Runtime,
state.device_playback.last_remote_snapshot = None;
state.device_playback.local_idle_since_ms = None;
if was_control && start_audio && state.player.playing {
start_current_audio(
state,
runtime,
state.player.position_secs,
state.player.paused,
);
start_current_audio_from(state, runtime, remote_start(state), state.player.paused);
}
publish_playback_snapshot(state, runtime);
}
@@ -951,7 +931,7 @@ pub(crate) fn transfer_active_to_this_device(state: &mut AppState, runtime: &mut
}
become_active_device(state, runtime, false);
if should_start && state.player.current.is_some() {
start_current_audio(state, runtime, state.player.position_secs, false);
start_current_audio_from(state, runtime, remote_start(state), false);
push_media_metadata(state, runtime);
push_media_update(state, runtime, true);
}
@@ -972,11 +952,13 @@ pub(crate) fn transfer_active_to_remote_device(
transfer_active_to_this_device(state, runtime);
return;
}
if queue_has_podcast_episodes(state) {
// Protocol 3 cannot carry episodes (they travel as private
// placeholders), so the other device could neither play nor keep
// them: refuse before ownership changes.
state.status_message = Some(PODCAST_HANDOFF_UNSUPPORTED.into());
// A device below sync v4 could neither play nor keep podcast episodes:
// refuse before ownership changes (never strip them from the queue).
if let Err(error) = runtime
.devices
.ensure_playback_supported_by(&target_device_id, &playback_state_from_ui(state))
{
state.status_message = Some(format!("device handoff: {error}"));
return;
}
if let Err(error) = runtime.devices.claim_playback(&target_device_id) {
@@ -2243,6 +2225,27 @@ fn start_current_audio(
start_current_audio_from(state, runtime, StartAt::Position { ms }, paused);
}
/// Where the current item starts when another device decided it (a
/// handoff, a command of a controlling device, taking playback over here).
///
/// A podcast episode at position 0 resumes from its saved position: a
/// controlling device sends 0 for an ordinary Play, and the saved position
/// is at least as fresh. Any other position is the live position of the
/// handoff or seek.
fn remote_start(state: &AppState) -> StartAt {
let ms = (state.player.position_secs.max(0.0) * 1_000.0).round() as i64;
let episode = state
.player
.queue
.get(state.player.queue_pos)
.is_some_and(crate::library::models::TrackItem::is_podcast);
if episode && ms == 0 {
StartAt::Resume
} else {
StartAt::Position { ms }
}
}
fn start_current_audio_from(
state: &mut AppState,
runtime: &mut Runtime,
@@ -3352,14 +3355,8 @@ fn handle_playback_command(
) {
match command {
crate::devices::PlaybackCommand::SetState { state: wire, seek } => {
if queue_has_podcast_episodes(state) {
// The sender saw our episodes as private placeholders;
// applying its queue would replace them. Keep ours.
tracing::info!("ignored a remote playback command: the queue has podcast episodes");
state.status_message = Some(PODCAST_REMOTE_CONTROL_UNSUPPORTED.into());
publish_playback_snapshot(state, runtime);
return;
}
// Commands from devices below sync v4 never reach this point
// while the queue has podcast items (`DeviceSync`).
let old_current_key = state.player.current.as_ref().map(track_playback_key);
let old_playing = state.player.playing;
let old_paused = state.player.paused;
@@ -3377,12 +3374,7 @@ fn handle_playback_command(
}
let current_key = state.player.current.as_ref().map(track_playback_key);
if !old_playing || old_current_key != current_key {
start_current_audio(
state,
runtime,
state.player.position_secs,
state.player.paused,
);
start_current_audio_from(state, runtime, remote_start(state), state.player.paused);
push_media_metadata(state, runtime);
} else {
if seek {
@@ -3435,6 +3427,82 @@ fn handle_playback_command(
}
}
/// Shown when a Jam guest's change would drop, add or reveal the host's
/// private items.
const JAM_PRIVATE_ITEMS_KEPT: &str =
"Jam: ignored a guest's change that would remove or add podcast episodes";
/// A Jam guest's queue state mapped back onto this host's queue.
///
/// Guests see the host's podcast episodes as private placeholders
/// (`redact_for_jam`). Their placeholders become the host's episodes again
/// (`restore_jam_private_items`); a state that drops, duplicates or adds
/// private items is refused (`None`). Guests cannot seek in a private item:
/// while it stays current, the host's position is kept. The host keeps its
/// own volume.
fn jam_participant_state(
state: &AppState,
wire: crate::devices::PlaybackStateWire,
seek: bool,
) -> Option<(crate::devices::PlaybackStateWire, bool)> {
let host = playback_state_from_ui(state);
if !music_dht::device_sync::jam_command_allowed(&crate::devices::PlaybackCommand::SetState {
state: wire.clone(),
seek,
}) {
return None;
}
let mut restored = music_dht::device_sync::restore_jam_private_items(&host, wire)?;
restored.volume = state.player.volume;
let private_current = restored
.queue
.get(restored.queue_pos)
.filter(|track| track.requires_podcast_support());
let same_current = private_current.is_some()
&& restored.queue.get(restored.queue_pos) == host.queue.get(host.queue_pos);
if same_current {
restored.position_secs = host.position_secs;
return Some((restored, false));
}
Some((restored, seek))
}
/// Removes Jam private placeholders from the queue (a guest leaving).
fn drop_private_items(state: &mut AppState) {
let player = &mut state.player;
let before = player
.queue
.iter()
.take(player.queue_pos)
.filter(|track| crate::devices::is_private_track_item(track))
.count();
let current_private = player
.queue
.get(player.queue_pos)
.is_some_and(crate::devices::is_private_track_item);
player
.queue
.retain(|track| !crate::devices::is_private_track_item(track));
player.queue_pos = player
.queue_pos
.saturating_sub(before)
.min(player.queue.len().saturating_sub(1));
player.play_next_end = None;
player.original_order = None;
player.prefetched_pos = None;
if current_private
|| player
.current
.as_ref()
.is_some_and(crate::devices::is_private_track_item)
{
player.current = None;
player.playing = false;
player.paused = false;
player.position_secs = 0.0;
}
}
fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent) {
let Some(event) = podcast_runtime::handle_event(state, runtime, event) else {
return;
@@ -3636,6 +3704,11 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}
crate::jam::JamRole::None => {
if state.device_playback.role == state::DevicePlaybackRole::Jam {
if !state.device_playback.jam_host {
// The host's private placeholders are not this
// device's queue items.
drop_private_items(state);
}
state.device_playback.role = state::DevicePlaybackRole::Active;
state.device_playback.jam_host = false;
}
@@ -3655,12 +3728,16 @@ fn handle_app_event(state: &mut AppState, runtime: &mut Runtime, event: AppEvent
}
AppEvent::JamCommand(command) => {
let command = match command {
crate::devices::PlaybackCommand::SetState {
state: mut wire,
seek,
} => {
wire.volume = state.player.volume;
crate::devices::PlaybackCommand::SetState { state: wire, seek }
crate::devices::PlaybackCommand::SetState { state: wire, seek } => {
match jam_participant_state(state, wire, seek) {
Some((wire, seek)) => {
crate::devices::PlaybackCommand::SetState { state: wire, seek }
}
None => {
state.status_message = Some(JAM_PRIVATE_ITEMS_KEPT.into());
return;
}
}
}
crate::devices::PlaybackCommand::ActiveChanged { .. } => {
state.status_message =
@@ -4677,3 +4754,160 @@ mod status_message_tests {
assert_eq!(join_status_messages(None, None), None);
}
}
#[cfg(test)]
mod playback_bridge_tests {
use super::*;
use crate::app::podcast_fixtures::episode_track;
use crate::devices::{PlaybackStateWire, PlaybackTrack, PlaybackTrackExt};
use crate::library::models::TrackItem;
use music_dht::device_sync::PlaybackSource;
fn music(id: i64) -> TrackItem {
TrackItem {
id,
title: format!("song {id}"),
track_number: None,
disc_number: None,
duration_seconds: 200.0,
artists: vec![],
featured_artists: vec![],
release_id: 1,
release_title: "release".into(),
release_year: None,
cover_path: None,
file_path: format!("/music/{id}"),
content_id: Some(format!("b3:{id:064x}")),
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
podcast: None,
}
}
fn mixed_state() -> AppState {
let mut state = AppState::default();
state.player.queue = vec![music(1), episode_track(1), music(2), episode_track(2)];
state.player.queue_pos = 1;
state.player.current = Some(episode_track(1));
state.player.playing = true;
state.player.paused = true;
state.player.position_secs = 754.5;
state
}
fn keys(queue: &[TrackItem]) -> Vec<String> {
queue.iter().map(state::track_key).collect()
}
#[test]
fn a_mixed_queue_crosses_the_wire_with_its_episodes_position_and_pause() {
let sender = mixed_state();
let wire = playback_state_from_ui(&sender);
assert_eq!(wire.playback_rate, None);
assert!(matches!(
wire.queue[1].source,
Some(PlaybackSource::PodcastEpisode(_))
));
assert_eq!(wire.queue[0].source, None, "music stays untyped (v3 shape)");
let json = serde_json::to_string(&wire).unwrap();
let received: PlaybackStateWire = serde_json::from_str(&json).unwrap();
let mut receiver = AppState::default();
// Even a local-only source mode never drops episodes.
receiver.global.filters.source_mode = crate::config::settings::LibrarySourceMode::Local;
apply_playback_state_to_ui(&mut receiver, &received, None);
assert_eq!(keys(&receiver.player.queue), keys(&sender.player.queue));
assert_eq!(receiver.player.queue_pos, 1);
assert_eq!(
receiver.player.current.as_ref().map(state::track_key),
Some(state::track_key(&episode_track(1)))
);
assert!(receiver.player.paused);
assert_eq!(receiver.player.position_secs, 754.5);
assert_eq!(
receiver.player.queue[1].podcast_episode_ref(),
episode_track(1).podcast_episode_ref()
);
// Taken over there, the episode continues at the handed-off
// position; an episode handed over at 0 resumes its saved one.
assert_eq!(remote_start(&receiver), StartAt::Position { ms: 754_500 });
receiver.player.position_secs = 0.0;
assert_eq!(remote_start(&receiver), StartAt::Resume);
receiver.player.queue_pos = 0;
assert_eq!(remote_start(&receiver), StartAt::Position { ms: 0 });
}
#[test]
fn jam_guests_see_placeholders_and_their_commands_keep_the_hosts_episodes() {
let host = mixed_state();
let published = music_dht::device_sync::redact_for_jam(playback_state_from_ui(&host));
let json = serde_json::to_string(&published).unwrap();
for secret in ["Episode 1", "Episode 2", "example.test", "Show"] {
assert!(!json.contains(secret), "{secret} leaked to Jam: {json}");
}
// The guest shows (and sends back) numbered private items.
let mut guest = AppState::default();
apply_playback_state_to_ui(&mut guest, &published, None);
assert!(crate::devices::is_private_track_item(
&guest.player.queue[1]
));
assert_ne!(
state::track_key(&guest.player.queue[1]),
state::track_key(&guest.player.queue[3])
);
// It moves a placeholder and skips to the last item.
guest.player.queue.swap(2, 3);
guest.player.queue_pos = 3;
let command = playback_state_from_ui(&guest);
assert!(command.queue[2].is_private_placeholder());
let (restored, _) = jam_participant_state(&host, command.clone(), true).unwrap();
assert_eq!(
restored.queue[2].podcast_episode_ref(),
episode_track(2).podcast_episode_ref()
);
assert_eq!(
restored.queue[3].content_id.as_deref(),
music(2).content_id.as_deref()
);
// Dropping, adding or duplicating private items is refused.
let mut dropped = command.clone();
dropped.queue.remove(1);
assert!(jam_participant_state(&host, dropped, false).is_none());
let mut injected = command.clone();
injected
.queue
.push(PlaybackTrack::from_track(&episode_track(9)));
assert!(jam_participant_state(&host, injected, false).is_none());
let mut duplicated = command;
duplicated.queue.push(PlaybackTrack::private_placeholder());
assert!(jam_participant_state(&host, duplicated, false).is_none());
// Guests cannot seek in the host's private episode.
let mut seek = published.clone();
seek.position_secs = 3.0;
let (restored, seek) = jam_participant_state(&host, seek, true).unwrap();
assert!(!seek);
assert_eq!(restored.position_secs, host.player.position_secs);
}
#[test]
fn a_guest_leaving_a_jam_drops_the_hosts_placeholders() {
let mut guest = AppState::default();
let published =
music_dht::device_sync::redact_for_jam(playback_state_from_ui(&mixed_state()));
apply_playback_state_to_ui(&mut guest, &published, None);
guest.player.queue_pos = 2;
guest.player.current = guest.player.queue.get(2).cloned();
drop_private_items(&mut guest);
assert_eq!(keys(&guest.player.queue), keys(&[music(1), music(2)]));
assert_eq!(guest.player.queue_pos, 1);
assert!(guest.player.current.is_some());
}
}
+7 -1
View File
@@ -1500,8 +1500,14 @@ pub fn playlist_tracks(state: &AppState, id: i64) -> Option<Vec<&TrackItem>> {
}
}
/// Whether the library source mode lets a queue item stay in a received
/// queue. Only pending federated music depends on it: podcast episodes
/// (streamed from their publisher) and Jam private placeholders are never
/// dropped, or a received queue would lose them.
pub(crate) fn track_allowed_by_source_mode(state: &AppState, track: &TrackItem) -> bool {
state.global.filters.source_mode.includes_network() || !track.is_fed_pending()
track.is_podcast()
|| state.global.filters.source_mode.includes_network()
|| !track.is_fed_pending()
}
/// A *release* under the cursor (artist-view tile/row or a search release).
+35 -11
View File
@@ -168,19 +168,43 @@ fn select(state: &mut AppState) -> Option<Effect> {
// ---------------------------------------------------------------------------
// Playback
/// Episodes play on this device only for now: a device that controls
/// another one would hand them over as private placeholders (sync protocol
/// v3 cannot carry them). Says so and returns `false` in that case.
/// Whether podcast episodes may be added to the queue that plays.
///
/// On this device, always. A device controlling another one sends the
/// queue there, so that device must speak sync v4 (an older one would drop
/// the episodes). A Jam guest never adds episodes to the host's queue.
/// Says why and returns `false` otherwise.
pub fn episodes_play_here(state: &mut AppState) -> bool {
if state.device_playback.is_control() {
state.status_message = Some(
"podcasts: playback is on another device; episodes play only on this device \
(take playback over here first)"
.into(),
);
return false;
use crate::app::state::DevicePlaybackRole;
match state.device_playback.role {
DevicePlaybackRole::Jam if !state.device_playback.jam_host => {
state.status_message =
Some("podcasts: Jam guests cannot add podcast episodes to the host's queue".into());
false
}
DevicePlaybackRole::Control => {
let target = state.device_playback.active_device_id.clone();
let version = target.as_deref().and_then(|target| {
state
.federation
.devices
.as_ref()?
.devices
.iter()
.find(|row| row.device_id == target)
.map(|row| row.protocol_version)
});
if version.is_some_and(music_dht::device_sync::supports_podcasts) {
return true;
}
state.status_message = Some(format!(
"podcasts: {} needs a Furumi update to play podcast episodes",
state.device_playback.active_label()
));
false
}
_ => true,
}
true
}
/// Enter on an episode: play it now, right after the current item, keeping
+32 -6
View File
@@ -2000,8 +2000,8 @@ mod podcast_queue {
assert!(state.popup.is_none(), "episode metadata is not editable");
assert_eq!(update(&mut state, Action::DownloadSelected), None);
// No content id, no share link, no music history, private on the
// v3 wire.
// No content id, no share link, no music history; on the wire an
// explicit podcast source, never a music item.
let episode = episode_track(1);
assert_eq!(track_content_id(&episode), None);
assert_eq!(crate::share::track_content_id(&episode), None);
@@ -2009,8 +2009,8 @@ mod podcast_queue {
let wire = <crate::devices::PlaybackTrack as crate::devices::PlaybackTrackExt>::from_track(
&episode,
);
assert_eq!(wire.title, music_dht::device_sync::PRIVATE_ITEM_TITLE);
assert!(wire.artist_names.is_empty() && wire.release_title.is_empty());
assert_eq!(wire.podcast_episode_ref(), episode.podcast_episode_ref());
assert!(wire.file_path.is_empty());
assert_eq!((wire.id, wire.content_id, wire.fed), (0, None, None));
// Shift-J opens the podcast instead of a music release.
@@ -2103,7 +2103,7 @@ mod podcast_queue {
}
#[test]
fn episodes_can_be_queued_but_not_while_another_device_plays() {
fn episodes_are_queued_for_v4_outputs_only() {
let mut state = episodes_tab(&[None, None]);
assert_eq!(
update(&mut state, Action::QueueAddLast),
@@ -2118,16 +2118,42 @@ mod podcast_queue {
keys(&[episode_track(1), episode_track(2)])
);
// Controlling a device that has not reported sync v4.
state.device_playback.role = crate::app::state::DevicePlaybackRole::Control;
state.device_playback.active_device_id = Some("dev_old".into());
state.device_playback.active_device_name = Some("Old laptop".into());
let row = |version| crate::devices::DeviceStatusRow {
device_id: "dev_old".into(),
name: "Old laptop".into(),
protocol_version: version,
..Default::default()
};
state.federation.devices = Some(crate::devices::DeviceSyncStatus {
devices: vec![row(3)],
..Default::default()
});
assert_eq!(update(&mut state, Action::QueueAddNext), None);
assert_eq!(update(&mut state, Action::Select), None);
assert_eq!(state.player.queue.len(), 2);
assert_eq!(
state.status_message.as_deref(),
Some("podcasts: Old laptop needs a Furumi update to play podcast episodes")
);
// Once it reports v4, the queue goes there with the episodes.
state.federation.devices.as_mut().unwrap().devices = vec![row(4)];
assert!(update(&mut state, Action::QueueAddNext).is_some());
assert_eq!(state.player.queue.len(), 3);
// A Jam guest never adds episodes to the host's queue.
state.device_playback.role = crate::app::state::DevicePlaybackRole::Jam;
state.device_playback.jam_host = false;
assert_eq!(update(&mut state, Action::QueueAddNext), None);
assert!(
state
.status_message
.as_deref()
.unwrap()
.contains("another device")
.contains("Jam guests")
);
}
+140 -2
View File
@@ -144,16 +144,91 @@ struct PodcastLink {
/// Converts queue items to and from the shared wire form
/// ([`PlaybackTrack`]). The wire types themselves are the shared
/// `music_dht::device_sync` definitions; this client keeps no copies.
///
/// A podcast episode travels with its explicit source
/// (`PlaybackSource::PodcastEpisode`), never as a music item. Peers below
/// protocol v4 do not get such a queue at all (`playback_allowed_for_peer`).
pub trait PlaybackTrackExt {
/// Wire form of a queue item. Device-local paths are never sent.
fn from_track(track: &TrackItem) -> Self;
/// Queue item for a wire track received from another device.
/// Queue item for a wire track received from another device. A Jam
/// private placeholder becomes [`private_track_item`]`(0)`; callers
/// that keep a queue number them ([`track_items_from_wire`]).
fn to_track_item(&self) -> TrackItem;
}
/// Ids of the "private item" queue entries that stand for a Jam host's
/// podcast episodes on a guest: `PRIVATE_ITEM_ID_BASE - k` for the k-th, so
/// each has its own queue key. Process-local; never sent (they go back on
/// the wire as `PlaybackSource::Private`).
const PRIVATE_ITEM_ID_BASE: i64 = -(1 << 62);
const PRIVATE_ITEM_ID_SPAN: i64 = 1 << 32;
/// Queue entry for the k-th Jam private placeholder: no title but
/// [`music_dht::device_sync::PRIVATE_ITEM_TITLE`], no URL, not playable.
pub fn private_track_item(k: usize) -> TrackItem {
TrackItem {
id: PRIVATE_ITEM_ID_BASE - (k as i64 % PRIVATE_ITEM_ID_SPAN),
title: music_dht::device_sync::PRIVATE_ITEM_TITLE.to_string(),
track_number: None,
disc_number: None,
duration_seconds: 0.0,
artists: Vec::new(),
featured_artists: Vec::new(),
release_id: TrackItem::NOT_A_LIBRARY_ROW,
release_title: String::new(),
release_year: None,
file_path: String::new(),
content_id: None,
cover_path: None,
audio_format: None,
audio_bitrate: None,
audio_sample_rate: None,
audio_bit_depth: None,
file_size_bytes: None,
play_count: 0,
fed: None,
podcast: None,
}
}
/// Whether a queue entry is a Jam private placeholder.
pub fn is_private_track_item(track: &TrackItem) -> bool {
track.podcast.is_none()
&& track.fed.is_none()
&& track.content_id.is_none()
&& track.id <= PRIVATE_ITEM_ID_BASE
&& track.id > PRIVATE_ITEM_ID_BASE - PRIVATE_ITEM_ID_SPAN
&& track.title == music_dht::device_sync::PRIVATE_ITEM_TITLE
}
/// Queue entries for a received queue, with `resolve_music` deciding music
/// items (a library copy, for example). Podcast episodes keep their typed
/// reference; Jam private placeholders are numbered in queue order.
pub fn track_items_from_wire(
queue: &[PlaybackTrack],
mut resolve_music: impl FnMut(&PlaybackTrack) -> TrackItem,
) -> Vec<TrackItem> {
let mut private = 0;
queue
.iter()
.map(|track| match TrackItem::from_playback_track(track) {
furumi_library::models::PlaybackItem::Music => resolve_music(track),
furumi_library::models::PlaybackItem::PodcastEpisode(item) => *item,
furumi_library::models::PlaybackItem::Private => {
private += 1;
private_track_item(private - 1)
}
})
.collect()
}
impl PlaybackTrackExt for PlaybackTrack {
fn from_track(track: &TrackItem) -> Self {
if track.is_podcast() {
if let Some(episode) = &track.podcast {
return Self::podcast_episode(episode.clone());
}
if is_private_track_item(track) {
return Self::private_placeholder();
}
Self {
@@ -192,6 +267,11 @@ impl PlaybackTrackExt for PlaybackTrack {
}
fn to_track_item(&self) -> TrackItem {
match TrackItem::from_playback_track(self) {
furumi_library::models::PlaybackItem::Music => {}
furumi_library::models::PlaybackItem::PodcastEpisode(item) => return *item,
furumi_library::models::PlaybackItem::Private => return private_track_item(0),
}
let refs = |names: &[String]| -> Vec<ArtistRef> {
names
.iter()
@@ -1838,6 +1918,31 @@ impl DeviceSync {
let Some(authority) = authority else {
return Ok(());
};
// A peer below v4 does not know podcast items: while this queue has
// any, its state would silently drop them. Checked before the
// ownership engine sees the command.
let peer_version = self.peer_protocol_version(origin)?;
let local = lock(&self.playback)
.local
.as_ref()
.map(|snapshot| snapshot.state.clone());
if let Some(local) = local
&& !music_dht::device_sync::playback_command_allowed_from_peer(&local, peer_version)
{
tracing::info!(
origin = %short_id(origin),
peer_version,
"ignored a playback command from a device without podcast support"
);
if let Some(tx) = lock(&self.event_tx).as_ref() {
let _ = tx.send(AppEvent::StatusMessage(format!(
"ignored playback control from {}: it needs a Furumi update to keep the \
podcast episodes in this queue",
self.device_label(origin)
)));
}
return Ok(());
}
let handoff = matches!(command, PlaybackCommand::ActiveChanged { .. });
if !handoff && target_device_id != identity.device_id {
return Ok(());
@@ -2873,6 +2978,39 @@ impl DeviceSync {
/// podcast items and the peer is below v4 (`playback_allowed_for_peer`).
/// Episodes are never stripped to make the state fit: an old client
/// would forward the shortened queue and lose them for every device.
/// Refuses to hand a queue with podcast items to a device below v4
/// ("that device needs an update"), before ownership changes.
pub fn ensure_playback_supported_by(
&self,
device_id: &str,
state: &PlaybackStateWire,
) -> Result<()> {
let version = self.peer_protocol_version(device_id)?;
anyhow::ensure!(
music_dht::device_sync::playback_allowed_for_peer(state, version),
"{} needs a Furumi update to play podcast episodes (device sync v{}); update \
Furumi there, or remove the episodes from the queue",
self.device_label(device_id),
music_dht::device_sync::PODCAST_PROTOCOL_VERSION
);
Ok(())
}
/// Display name of a device, or a short id.
fn device_label(&self, device_id: &str) -> String {
lock(&self.conn)
.query_row(
"SELECT name FROM sync_devices WHERE device_id = ?1",
[device_id],
|row| row.get::<_, String>(0),
)
.optional()
.ok()
.flatten()
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| short_id(device_id))
}
fn local_playback_snapshot_for(&self, peer_version: u16) -> Option<PlaybackSnapshot> {
lock(&self.playback).local.clone().filter(|snapshot| {
music_dht::device_sync::playback_allowed_for_peer(&snapshot.state, peer_version)
+174
View File
@@ -612,3 +612,177 @@ fn podcast_snapshot_sections_shrink_to_fit_the_line_limit() {
// The music part is never cut for podcast state.
assert_eq!(message_snapshot(&mut message).likes.len(), 70_000);
}
fn state_with(queue: Vec<PlaybackTrack>, position_secs: f64) -> PlaybackStateWire {
PlaybackStateWire {
queue,
queue_pos: 0,
playing: true,
paused: true,
idle_since_ms: None,
position_secs,
volume: 80,
shuffle: false,
repeat: PlaybackRepeat::Off,
playback_rate: None,
}
}
fn publish(device: &Device, state: PlaybackStateWire) {
device.sync.publish_playback(PlaybackSnapshot {
device_id: device.id.clone(),
device_name: "A".into(),
active: true,
updated_at_ms: now_ms(),
state,
coordination: None,
});
}
fn music_wire() -> PlaybackTrack {
let mut track = PlaybackTrack::private_placeholder();
track.title = "Song".into();
track.content_id = Some(format!("b3:{}", "d".repeat(64)));
track.source = None;
track
}
#[test]
fn a_handoff_between_v4_devices_carries_the_episode_and_its_position() {
let a = device();
let mut b = device();
pair(&a, &b);
subscribe(&a);
let episode = episode_ref(6);
let session = start(&a, &episode, 0);
checkpoint(&a, &session, 1_000_000);
let mut queued = TrackItem::podcast_episode(episode.clone());
queued.podcast.as_mut().unwrap().progress_generation = Some(session.generation);
let state = state_with(
vec![PlaybackTrack::from_track(&queued), music_wire()],
1_000.5,
);
a.sync
.ensure_playback_supported_by(&b.id, &state)
.expect("B speaks v4");
a.sync.claim_playback(&a.id).unwrap();
a.sync
.record_playback_command(
&b.id,
PlaybackCommand::ActiveChanged {
active_device_id: b.id.clone(),
active_device_name: "B".into(),
state,
},
)
.unwrap();
deliver(&a, &b);
let mut handed = None;
while let Ok(event) = b.events.try_recv() {
if let AppEvent::PlaybackCommand {
command: PlaybackCommand::ActiveChanged { state, .. },
..
} = event
{
handed = Some(state);
}
}
let handed = handed.expect("the handoff reaches B's player");
assert_eq!(handed.position_secs, 1_000.5);
assert!(handed.paused);
assert_eq!(handed.playback_rate, None);
let items = track_items_from_wire(&handed.queue, PlaybackTrack::to_track_item);
let item = items[0].podcast_episode_ref().expect("still an episode");
assert_eq!(item.episode_id, episode.episode_id);
assert_eq!(item.audio_url, episode.audio_url);
assert_eq!(item.progress_generation, Some(session.generation));
assert!(!items[1].is_podcast());
}
#[test]
fn a_podcast_queue_is_not_handed_to_or_replaced_by_a_v3_device() {
let mut a = device();
a.sync.apply_device_trusted("dev_old", 1).unwrap();
a.sync
.apply_device_profile(
&DeviceProfileWire {
device_id: "dev_old".into(),
name: "Old laptop".into(),
client_version: "0.3.5".into(),
protocol_version: 3,
endpoint_id: String::new(),
endpoint_ticket: String::new(),
revoked: false,
revoke_cutoff_seq: None,
updated_at_ms: 1,
},
false,
VersionReport::SelfReported(Some(3)),
)
.unwrap();
let with_episode = state_with(
vec![music_wire(), PlaybackTrack::podcast_episode(episode_ref(7))],
12.0,
);
// Handoff to it: refused with the reason, before ownership changes.
let error = a
.sync
.ensure_playback_supported_by("dev_old", &with_episode)
.unwrap_err()
.to_string();
assert!(
error.contains("Old laptop needs a Furumi update"),
"{error}"
);
a.sync
.ensure_playback_supported_by("dev_old", &state_with(vec![music_wire()], 0.0))
.expect("music-only queues go anywhere");
// Its handoff to itself while this queue has an episode is ignored.
let mut old = Engine::new(
"dev_old".into(),
PlaybackConfig::default(),
Default::default(),
0,
);
old.transfer("dev_old", 0);
let stamp = old.stamp().unwrap();
let take_over = PlaybackCommand::ActiveChanged {
active_device_id: "dev_old".into(),
active_device_name: "Old laptop".into(),
state: state_with(vec![music_wire()], 0.0),
};
a.sync.claim_playback(&a.id).unwrap();
publish(&a, with_episode);
a.sync
.apply_playback_command(&a.id, &take_over, Some(&stamp), "dev_old", "dev_old:5")
.unwrap();
let mut commands = 0;
let mut messages = Vec::new();
while let Ok(event) = a.events.try_recv() {
match event {
AppEvent::PlaybackCommand { .. } => commands += 1,
AppEvent::StatusMessage(message) => messages.push(message),
_ => {}
}
}
assert_eq!(commands, 0);
assert!(messages[0].contains("Old laptop"), "{messages:?}");
assert_eq!(
a.sync
.with_playback_engine(|engine| engine.owner().map(str::to_owned))
.unwrap()
.as_deref(),
Some(a.id.as_str())
);
// Without episodes in the queue it is an ordinary handoff.
publish(&a, state_with(vec![music_wire()], 0.0));
a.sync
.apply_playback_command(&a.id, &take_over, Some(&stamp), "dev_old", "dev_old:6")
.unwrap();
assert!(
std::iter::from_fn(|| a.events.try_recv().ok())
.any(|event| matches!(event, AppEvent::PlaybackCommand { .. }))
);
}
+50 -11
View File
@@ -225,10 +225,16 @@ impl JamManager {
JamStatus::default()
}
/// Publishes the host's playback to participants. Podcast episodes are
/// private: participants get opaque placeholders (`redact_for_jam`),
/// never their titles, feeds or URLs.
pub fn publish_host_playback(&self, snapshot: PlaybackSnapshot) {
let mut state = lock(&self.state);
if state.host.invite.is_some() {
state.host.playback = Some(snapshot);
state.host.playback = Some(PlaybackSnapshot {
state: music_dht::device_sync::redact_for_jam(snapshot.state),
..snapshot
});
}
}
@@ -374,7 +380,15 @@ async fn serve_one(mut stream: ByteStream, manager: Arc<JamManager>) -> Result<(
acknowledged.push(command.command_id.clone());
if state.host.seen_commands.insert(command.command_id.clone()) {
state.host.seen_order.push_back(command.command_id.clone());
let _ = manager.event_tx.send(AppEvent::JamCommand(command.command));
// Participants cannot add podcast episodes to the
// host queue; placeholders are mapped back by the
// host (`restore_jam_private_items`).
if music_dht::device_sync::jam_command_allowed(&command.command) {
let _ =
manager.event_tx.send(AppEvent::JamCommand(command.command));
} else {
tracing::info!("ignored a Jam command that adds podcast episodes");
}
}
}
while state.host.seen_order.len() > 4096 {
@@ -656,8 +670,14 @@ mod tests {
.join(&invite, "dev_guest".into(), "Guest".into())
.unwrap();
// The host plays a private podcast episode.
let episode = crate::app::podcast_fixtures::episode_track(1)
.podcast
.unwrap();
let playback_state = crate::devices::PlaybackStateWire {
queue: Vec::new(),
queue: vec![crate::devices::PlaybackTrack::podcast_episode(
episode.clone(),
)],
queue_pos: 0,
playing: false,
paused: false,
@@ -691,12 +711,27 @@ mod tests {
.unwrap();
assert_eq!(playback.device_id, "dev_host");
assert_eq!(playback.state.volume, 73);
// Guests get an opaque placeholder: no title, feed or URL.
assert!(playback.state.queue[0].is_private_placeholder());
let seen = serde_json::to_string(&playback).unwrap();
assert!(!seen.contains(&episode.audio_url) && !seen.contains(&episode.episode_title));
// A guest cannot add an episode to the host's queue; its ordinary
// command (with the placeholder) still arrives.
guest
.submit_command(PlaybackCommand::SetState {
state: crate::devices::PlaybackStateWire {
queue: vec![crate::devices::PlaybackTrack::podcast_episode(episode)],
..playback_state.clone()
},
seek: false,
})
.unwrap();
guest
.submit_command(PlaybackCommand::SetState {
state: crate::devices::PlaybackStateWire {
paused: true,
..playback_state
..playback.state
},
seek: false,
})
@@ -711,13 +746,17 @@ mod tests {
})
.await
.unwrap();
assert!(matches!(
command,
PlaybackCommand::SetState {
state: crate::devices::PlaybackStateWire { paused: true, .. },
seek: false
}
));
let PlaybackCommand::SetState {
state: received,
seek: false,
} = command
else {
panic!("expected the guest's set_state");
};
// The command that adds an episode was sent first; had it been
// forwarded, it would have arrived first.
assert!(received.paused);
assert!(received.queue[0].is_private_placeholder());
server.abort();
host_drain.abort();