From e7713269f28a228a8f88cbfbff08d625c49fffa9 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 20:41:11 +0200 Subject: [PATCH] Use the shared device-sync wire types The private copies of the device-sync wire types are replaced by music_dht::device_sync. Golden tests keep the furumi-tui 0.3.x types verbatim and check that v3 messages serialize byte for byte the same. Co-Authored-By: Claude Opus 5.5 --- src/app/mod.rs | 2 + src/app/update_tests.rs | 4 +- src/devices.rs | 638 ++++------------------ src/devices/fixtures/v3_hello.golden.json | 1 + src/devices/interop_tests.rs | 5 +- src/devices/tests.rs | 28 +- src/devices/wire_compat_tests.rs | 533 ++++++++++++++++++ src/jam.rs | 1 + 8 files changed, 679 insertions(+), 533 deletions(-) create mode 100644 src/devices/fixtures/v3_hello.golden.json create mode 100644 src/devices/wire_compat_tests.rs diff --git a/src/app/mod.rs b/src/app/mod.rs index d05ff2f..e6aad6b 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -27,6 +27,7 @@ use tokio::sync::mpsc; use tokio::time::MissedTickBehavior; use crate::config::keymap::{KeyResolution, Keymap}; +use crate::devices::PlaybackTrackExt as _; use crate::library::Library; use crate::player; use crate::podcasts::playback::StartAt; @@ -707,6 +708,7 @@ fn playback_state_from_ui(state: &AppState) -> crate::devices::PlaybackStateWire volume: state.player.volume, shuffle: state.player.shuffle, repeat: playback_repeat_to_wire(state.player.repeat), + playback_rate: None, } } diff --git a/src/app/update_tests.rs b/src/app/update_tests.rs index 352cf3b..4bc18cc 100644 --- a/src/app/update_tests.rs +++ b/src/app/update_tests.rs @@ -2005,7 +2005,9 @@ mod podcast_queue { assert_eq!(track_content_id(&episode), None); assert_eq!(crate::share::track_content_id(&episode), None); assert_eq!(crate::share::track_share_link(&episode), None); - let wire = crate::devices::PlaybackTrack::from_track(&episode); + let wire = ::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.id, wire.content_id, wire.fed), (0, None, None)); diff --git a/src/devices.rs b/src/devices.rs index ae86388..6417329 100644 --- a/src/devices.rs +++ b/src/devices.rs @@ -8,7 +8,6 @@ use music_dht::playback::{Checkpoint, CommandStamp, Config as PlaybackConfig, Engine}; use std::collections::{BTreeMap, BTreeSet}; use std::path::PathBuf; -use std::str::FromStr; use std::sync::Arc; use std::time::Duration; @@ -16,11 +15,18 @@ use anyhow::{Context as _, Result}; use furumi_library::podcasts::{ OpStamp as PodcastOpStamp, PodcastLocalOp, StampSource as PodcastStampSource, }; -use music_dht::device_sync::{ListenEvent, ListenTrackMetadata}; +use music_dht::device_sync::{ + DeviceProfileWire, InviteWire, ListenEvent, ListenTrackMetadata, SnapshotLike, + SnapshotLikeTombstone, SnapshotPlaylist, SnapshotPlaylistItem, SnapshotPlaylistItemTombstone, + SnapshotPlaylistTombstone, SyncOpWire, SyncSnapshot, WireMessage, encode_invite, finish_send, + hash_secret, random_hex, read_msg, ticket_endpoint_id, +}; +pub use music_dht::device_sync::{ + PlaybackCommand, PlaybackRepeat, PlaybackSnapshot, PlaybackStateWire, PlaybackTrack, + SyncOpPayload, SyncedFedTrack, +}; use music_dht::{ByteStream, MusicDhtService, NetworkId, PeerTicket, SecretKey, StreamAcceptor}; use rusqlite::{Connection, OptionalExtension, params}; -use serde::{Deserialize, Serialize}; -use tokio::io::{AsyncRead, AsyncReadExt}; use crate::app::event::AppEvent; use crate::library::Library; @@ -34,7 +40,6 @@ const PAIRING_WAIT_MS: i64 = 5 * 60 * 1000; const PAIRING_RETRY_DELAY: Duration = Duration::from_secs(1); const RESPONSE_DRAIN_TIMEOUT: Duration = Duration::from_secs(2); const SYNC_INTERVAL: Duration = Duration::from_secs(2); -const MAX_LINE: usize = 8 * 1024 * 1024; /// Playback control is ephemeral. Keeping old full-queue commands in a new /// peer's catch-up batch can make the initial pairing frame arbitrarily large. const PLAYBACK_COMMAND_TTL_MS: i64 = 5 * 60 * 1_000; @@ -95,78 +100,18 @@ pub struct DeviceSync { playback: Arc>, } -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] -#[serde(rename_all = "snake_case")] -pub enum PlaybackRepeat { - #[default] - Off, - One, - All, +/// 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. +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. + fn to_track_item(&self) -> TrackItem; } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct PlaybackTrack { - pub id: i64, - pub title: String, - pub track_number: Option, - pub disc_number: Option, - pub duration_seconds: f64, - #[serde(default)] - pub artist_names: Vec, - #[serde(default)] - pub featured_artist_names: Vec, - pub release_id: i64, - pub release_title: String, - pub release_year: Option, - /// Legacy compatibility only. Paths are device-local, so playback sync - /// must resolve tracks from content/federation identifiers instead. - #[serde(default)] - pub file_path: String, - pub content_id: Option, - pub audio_format: Option, - pub audio_bitrate: Option, - pub audio_sample_rate: Option, - pub audio_bit_depth: Option, - pub file_size_bytes: Option, - #[serde(default)] - pub play_count: i64, - #[serde(default)] - pub fed: Option, -} - -impl PlaybackTrack { - fn portable_placeholder_id(&self) -> i64 { - let key = self - .content_id - .as_deref() - .and_then(music_dht::normalize_content_id) - .map(|content_id| format!("content:{content_id}")) - .or_else(|| { - self.fed - .as_ref() - .map(|fed| fed.content_id.as_str()) - .and_then(music_dht::normalize_content_id) - .map(|content_id| format!("content:{content_id}")) - }) - .or_else(|| { - self.fed - .as_ref() - .map(|fed| format!("fed:{}:{}", fed.owner, fed.item_id)) - }) - .unwrap_or_else(|| { - format!( - "remote:{}:{}:{}:{}", - self.id, self.title, self.release_title, self.duration_seconds - ) - }); - let hash = blake3::hash(key.as_bytes()); - let mut bytes = [0u8; 8]; - bytes.copy_from_slice(&hash.as_bytes()[..8]); - let positive = (i64::from_be_bytes(bytes) & i64::MAX).max(1); - -positive - } - - pub fn from_track(track: &TrackItem) -> Self { +impl PlaybackTrackExt for PlaybackTrack { + fn from_track(track: &TrackItem) -> Self { if track.is_podcast() { return Self::private_placeholder(); } @@ -201,42 +146,11 @@ impl PlaybackTrack { file_size_bytes: track.file_size_bytes, play_count: track.play_count, fed: track.fed.as_ref().and_then(SyncedFedTrack::from_fed), + source: None, } } - /// What peers see in place of a podcast episode. - /// - /// This wire version (protocol 3) has no typed item source, so an - /// episode cannot be described without passing it off as music or - /// leaking its private title and URL (to Jam guests in particular). It - /// is sent as the shared "private item" placeholder instead: not - /// playable, no identity. Typed podcast items for peers that support - /// them come with sync protocol v4. - pub fn private_placeholder() -> Self { - Self { - id: 0, - title: music_dht::device_sync::PRIVATE_ITEM_TITLE.to_string(), - track_number: None, - disc_number: None, - duration_seconds: 0.0, - artist_names: Vec::new(), - featured_artist_names: Vec::new(), - release_id: 0, - release_title: String::new(), - release_year: None, - file_path: String::new(), - content_id: None, - audio_format: None, - audio_bitrate: None, - audio_sample_rate: None, - audio_bit_depth: None, - file_size_bytes: None, - play_count: 0, - fed: None, - } - } - - pub fn to_track_item(&self) -> TrackItem { + fn to_track_item(&self) -> TrackItem { let refs = |names: &[String]| -> Vec { names .iter() @@ -247,7 +161,7 @@ impl PlaybackTrack { .collect() }; TrackItem { - id: self.portable_placeholder_id(), + id: portable_placeholder_id(self), title: self.title.clone(), track_number: self.track_number, disc_number: self.disc_number, @@ -272,242 +186,48 @@ impl PlaybackTrack { } } -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct PlaybackStateWire { - #[serde(default)] - pub queue: Vec, - #[serde(default)] - pub queue_pos: usize, - pub playing: bool, - pub paused: bool, - #[serde(default)] - pub idle_since_ms: Option, - pub position_secs: f64, - #[serde(default)] - pub volume: u8, - pub shuffle: bool, - pub repeat: PlaybackRepeat, +/// Process-local negative id of a music item received from another device, +/// derived from its portable identity (content id, then federated source). +fn portable_placeholder_id(track: &PlaybackTrack) -> i64 { + let key = track + .content_id + .as_deref() + .and_then(music_dht::normalize_content_id) + .map(|content_id| format!("content:{content_id}")) + .or_else(|| { + track + .fed + .as_ref() + .map(|fed| fed.content_id.as_str()) + .and_then(music_dht::normalize_content_id) + .map(|content_id| format!("content:{content_id}")) + }) + .or_else(|| { + track + .fed + .as_ref() + .map(|fed| format!("fed:{}:{}", fed.owner, fed.item_id)) + }) + .unwrap_or_else(|| { + format!( + "remote:{}:{}:{}:{}", + track.id, track.title, track.release_title, track.duration_seconds + ) + }); + let hash = blake3::hash(key.as_bytes()); + let mut bytes = [0u8; 8]; + bytes.copy_from_slice(&hash.as_bytes()[..8]); + let positive = (i64::from_be_bytes(bytes) & i64::MAX).max(1); + -positive } -pub type PlaybackSnapshot = music_dht::playback::Snapshot; -pub type PlaybackCommand = music_dht::playback::Command; - -#[derive(Debug, Clone, Default)] -struct PlaybackShared { - engine: Option, - engine_group: String, - local: Option, - remote: BTreeMap, +/// Converts federated tracks to and from the synced metadata form. +trait SyncedFedTrackExt: Sized { + fn from_fed(fed: &crate::federation::FedTrack) -> Option; + fn to_fed_track(&self) -> crate::federation::FedTrack; } -#[derive(Debug, Clone)] -struct LocalIdentity { - device_id: String, - group_id: String, - name: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct InviteWire { - v: u16, - #[serde(rename = "t")] - ticket: String, - #[serde(rename = "d")] - device_id: String, - #[serde(rename = "i")] - invite_id: String, - #[serde(rename = "s")] - secret: String, - #[serde(rename = "e")] - expires_at_ms: i64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct DeviceProfileWire { - device_id: String, - name: String, - client_version: String, - protocol_version: u16, - endpoint_id: String, - endpoint_ticket: String, - #[serde(default)] - revoked: bool, - #[serde(default)] - revoke_cutoff_seq: Option, - #[serde(default)] - updated_at_ms: i64, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SyncOpWire { - op_id: String, - origin_device_id: String, - seq: i64, - hlc_ms: i64, - payload: SyncOpPayload, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "kind", rename_all = "snake_case")] -pub enum SyncOpPayload { - TrackLikeSet { - content_id: String, - liked: bool, - #[serde(default)] - fed: Option, - }, - PlaylistCreated { - playlist_id: String, - title: String, - }, - PlaylistRenamed { - playlist_id: String, - title: String, - }, - PlaylistDeleted { - playlist_id: String, - }, - PlaylistTrackAdded { - playlist_id: String, - content_id: String, - position: i64, - #[serde(default)] - fed: Option, - }, - PlaylistTrackRemoved { - playlist_id: String, - content_id: String, - }, - DeviceProfileSet { - name: String, - client_version: String, - endpoint_ticket: String, - endpoint_id: String, - }, - DeviceTrusted { - target_device_id: String, - }, - DeviceRevoked { - target_device_id: String, - target_max_seq_seen: i64, - }, - PlaybackCommand { - target_device_id: String, - command: PlaybackCommand, - #[serde(default)] - authority: Option, - }, - ListenRecorded { - event: ListenEvent, - }, -} - -impl SyncOpPayload { - fn is_tombstone(&self) -> bool { - matches!( - self, - SyncOpPayload::TrackLikeSet { liked: false, .. } - | SyncOpPayload::PlaylistDeleted { .. } - | SyncOpPayload::PlaylistTrackRemoved { .. } - | SyncOpPayload::DeviceRevoked { .. } - ) - } -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -struct SyncSnapshot { - #[serde(default)] - likes: Vec, - #[serde(default)] - unlikes: Vec, - #[serde(default)] - playlists: Vec, - #[serde(default)] - deleted_playlists: Vec, - #[serde(default)] - removed_playlist_items: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SnapshotLike { - content_id: String, - hlc_ms: i64, - op_id: String, - #[serde(default)] - fed: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SnapshotLikeTombstone { - content_id: String, - hlc_ms: i64, - op_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SnapshotPlaylist { - playlist_id: String, - title: String, - hlc_ms: i64, - op_id: String, - #[serde(default)] - items: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SnapshotPlaylistTombstone { - playlist_id: String, - hlc_ms: i64, - op_id: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SnapshotPlaylistItem { - content_id: String, - position: i64, - hlc_ms: i64, - op_id: String, - #[serde(default)] - fed: Option, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -struct SnapshotPlaylistItemTombstone { - playlist_id: String, - content_id: String, - hlc_ms: i64, - op_id: String, -} - -enum PairAttempt { - Accepted(String), - Pending, - Denied(String), -} - -struct PairingStatus { - status: String, - use_requester_group: bool, -} - -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct SyncedFedTrack { - item_id: String, - owner: String, - title: String, - #[serde(default)] - artist_names: Vec, - #[serde(default)] - featured_artist_names: Vec, - year: Option, - duration_seconds: Option, - content_id: String, - release_title: Option, - track_number: Option, - disc_number: Option, -} - -impl SyncedFedTrack { +impl SyncedFedTrackExt for SyncedFedTrack { fn from_fed(fed: &crate::federation::FedTrack) -> Option { let content_id = fed .content_id @@ -546,71 +266,30 @@ impl SyncedFedTrack { } } -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(tag = "type", rename_all = "snake_case")] -enum WireMessage { - PairRequest { - invite_id: String, - secret: String, - profile: DeviceProfileWire, - #[serde(default)] - group_id: Option, - #[serde(default)] - group_active_devices: usize, - #[serde(default)] - devices: Vec, - vector: BTreeMap, - ops: Vec, - snapshot: SyncSnapshot, - #[serde(default)] - playback: Option, - }, - PairResponse { - accepted: bool, - #[serde(default)] - pending: bool, - #[serde(default)] - error: Option, - #[serde(default)] - group_id: Option, - #[serde(default)] - profile: Option, - #[serde(default)] - devices: Vec, - #[serde(default)] - vector: BTreeMap, - #[serde(default)] - ops: Vec, - #[serde(default)] - snapshot: SyncSnapshot, - #[serde(default)] - playback: Option, - }, - Hello { - group_id: String, - profile: DeviceProfileWire, - devices: Vec, - vector: BTreeMap, - ops: Vec, - snapshot: SyncSnapshot, - #[serde(default)] - playback: Option, - }, - SyncResponse { - accepted: bool, - #[serde(default)] - error: Option, - #[serde(default)] - devices: Vec, - #[serde(default)] - vector: BTreeMap, - #[serde(default)] - ops: Vec, - #[serde(default)] - snapshot: SyncSnapshot, - #[serde(default)] - playback: Option, - }, +#[derive(Debug, Clone, Default)] +struct PlaybackShared { + engine: Option, + engine_group: String, + local: Option, + remote: BTreeMap, +} + +#[derive(Debug, Clone)] +struct LocalIdentity { + device_id: String, + group_id: String, + name: String, +} + +enum PairAttempt { + Accepted(String), + Pending, + Denied(String), +} + +struct PairingStatus { + status: String, + use_requester_group: bool, } fn lock(mutex: &std::sync::Mutex) -> std::sync::MutexGuard<'_, T> { @@ -833,6 +512,7 @@ impl DeviceSync { client_version: CLIENT_VERSION.to_string(), endpoint_ticket: ticket.to_string(), endpoint_id, + protocol_version: None, })?; } Ok(()) @@ -869,9 +549,9 @@ impl DeviceSync { invite_id, secret, expires_at_ms, + protocol_version: None, }; - let bytes = serde_json::to_vec(&payload)?; - Ok(format!("frid://i/{}", base64url_encode(&bytes))) + Ok(encode_invite(&payload)?) } pub async fn connect_invite( @@ -1774,6 +1454,7 @@ impl DeviceSync { client_version, endpoint_ticket, endpoint_id, + .. } => { let profile = DeviceProfileWire { device_id: op.origin_device_id.clone(), @@ -1818,6 +1499,13 @@ impl DeviceSync { SyncOpPayload::ListenRecorded { event } => self .library .apply_listen_event(event, &op.origin_device_id)?, + // Podcast operations (protocol v4) are kept in the log; this + // client does not apply or relay them yet. + SyncOpPayload::PodcastSubscriptionSet { .. } + | SyncOpPayload::PodcastShareSet { .. } + | SyncOpPayload::PodcastFeedAliasesAdded { .. } + | SyncOpPayload::PodcastProgressSet { .. } + | SyncOpPayload::PodcastListenRecorded { .. } => false, }; Ok(changed) } @@ -2568,6 +2256,7 @@ impl DeviceSync { playlists, deleted_playlists, removed_playlist_items, + ..SyncSnapshot::default() }) } @@ -2926,11 +2615,7 @@ impl PodcastLogStamps<'_> { }; let op = op.into_wire(seq); let payload = serde_json::to_value(&op.payload)?; - let kind = payload - .get("kind") - .and_then(serde_json::Value::as_str) - .unwrap_or("podcast_unknown") - .to_string(); + let kind = payload_kind(&op.payload); conn.execute( "INSERT OR IGNORE INTO sync_ops (op_id, origin_device_id, seq, kind, payload_json, hlc_ms, @@ -3669,6 +3354,11 @@ fn payload_kind(payload: &SyncOpPayload) -> &'static str { SyncOpPayload::DeviceRevoked { .. } => "device_revoked", SyncOpPayload::PlaybackCommand { .. } => "playback_command", SyncOpPayload::ListenRecorded { .. } => "listen_recorded", + SyncOpPayload::PodcastSubscriptionSet { .. } => "podcast_subscription_set", + SyncOpPayload::PodcastShareSet { .. } => "podcast_share_set", + SyncOpPayload::PodcastFeedAliasesAdded { .. } => "podcast_feed_aliases_added", + SyncOpPayload::PodcastProgressSet { .. } => "podcast_progress_set", + SyncOpPayload::PodcastListenRecorded { .. } => "podcast_listen_recorded", } } @@ -3829,55 +3519,21 @@ fn peer_ack_floor_label(conn: &Connection) -> Result { } async fn write_msg(stream: &mut ByteStream, message: &WireMessage) -> Result<()> { - let mut payload = serde_json::to_vec(message)?; - payload.push(b'\n'); - stream.send.write_all(&payload).await?; - Ok(()) -} - -async fn finish_send(stream: &mut ByteStream) -> Result<()> { - stream.send.finish()?; + music_dht::device_sync::write_msg(stream, message).await?; Ok(()) } async fn finish_response(stream: &mut ByteStream) -> Result<()> { - stream.send.finish()?; - let _ = tokio::time::timeout(RESPONSE_DRAIN_TIMEOUT, stream.send.stopped()).await; + music_dht::device_sync::finish_response(stream, RESPONSE_DRAIN_TIMEOUT).await?; Ok(()) } -async fn read_msg(stream: &mut ByteStream) -> Result { - let line = read_line(&mut stream.recv).await?; - Ok(serde_json::from_slice(&line)?) -} - -async fn read_line(reader: &mut R) -> Result> { - let mut out = Vec::new(); - loop { - let mut byte = [0u8; 1]; - let read = reader.read(&mut byte).await?; - if read == 0 { - break; - } - if byte[0] == b'\n' { - break; - } - out.push(byte[0]); - if out.len() > MAX_LINE { - anyhow::bail!("protocol line is too large"); - } - } - Ok(out) -} - fn parse_invite(value: &str) -> Result { - let Some(token) = value.trim().strip_prefix("frid://i/") else { - anyhow::bail!("usage: :connect frid://i/"); - }; - let bytes = base64url_decode(token)?; - let invite: InviteWire = serde_json::from_slice(&bytes)?; - anyhow::ensure!(invite.v == 1, "unsupported invite version"); - Ok(invite) + anyhow::ensure!( + value.trim().starts_with("frid://i/"), + "usage: :connect frid://i/" + ); + Ok(music_dht::device_sync::parse_invite(value)?) } pub fn invite_network_id(value: &str) -> Result { @@ -3889,28 +3545,10 @@ pub fn invite_network_id(value: &str) -> Result { Ok(ticket.network_id) } -fn hash_secret(secret: &str) -> String { - blake3::hash(secret.as_bytes()).to_hex().to_string() -} - -fn random_hex(bytes: usize) -> String { - let key = SecretKey::generate(); - let mut seed = key.to_bytes().to_vec(); - while seed.len() < bytes { - seed.extend_from_slice(blake3::hash(&seed).as_bytes()); - } - hex_encode(&seed[..bytes]) -} - fn hex_encode(bytes: &[u8]) -> String { bytes.iter().map(|byte| format!("{byte:02x}")).collect() } -fn ticket_endpoint_id(ticket: &str) -> Option { - let ticket = PeerTicket::from_str(ticket).ok()?; - Some(ticket.endpoint_id().to_string()) -} - fn default_device_name(device_id: &str) -> String { let host = std::env::var("HOSTNAME") .or_else(|_| std::env::var("COMPUTERNAME")) @@ -3924,59 +3562,6 @@ fn short_id(value: &str) -> String { value.chars().take(10).collect() } -fn base64url_encode(bytes: &[u8]) -> String { - const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - let mut out = String::new(); - let mut i = 0; - while i < bytes.len() { - let b0 = bytes[i]; - let b1 = bytes.get(i + 1).copied().unwrap_or(0); - let b2 = bytes.get(i + 2).copied().unwrap_or(0); - out.push(TABLE[(b0 >> 2) as usize] as char); - out.push(TABLE[(((b0 & 0b0000_0011) << 4) | (b1 >> 4)) as usize] as char); - if i + 1 < bytes.len() { - out.push(TABLE[(((b1 & 0b0000_1111) << 2) | (b2 >> 6)) as usize] as char); - } - if i + 2 < bytes.len() { - out.push(TABLE[(b2 & 0b0011_1111) as usize] as char); - } - i += 3; - } - out -} - -fn base64url_decode(value: &str) -> Result> { - fn val(byte: u8) -> Option { - match byte { - b'A'..=b'Z' => Some(byte - b'A'), - b'a'..=b'z' => Some(byte - b'a' + 26), - b'0'..=b'9' => Some(byte - b'0' + 52), - b'-' => Some(62), - b'_' => Some(63), - _ => None, - } - } - let bytes = value.as_bytes(); - let mut out = Vec::new(); - let mut i = 0; - while i < bytes.len() { - let a = val(bytes[i]).context("invalid base64url invite")?; - let b = val(*bytes.get(i + 1).context("truncated base64url invite")?) - .context("invalid base64url invite")?; - let c = bytes.get(i + 2).and_then(|byte| val(*byte)); - let d = bytes.get(i + 3).and_then(|byte| val(*byte)); - out.push((a << 2) | (b >> 4)); - if let Some(c) = c { - out.push(((b & 0b0000_1111) << 4) | (c >> 2)); - if let Some(d) = d { - out.push(((c & 0b0000_0011) << 6) | d); - } - } - i += 4; - } - Ok(out) -} - #[cfg(test)] #[path = "devices/tests.rs"] mod tests; @@ -3984,6 +3569,9 @@ mod tests; #[cfg(test)] mod interop_tests; +#[cfg(test)] +mod wire_compat_tests; + fn playback_clock() -> u64 { static START: std::sync::OnceLock = std::sync::OnceLock::new(); START diff --git a/src/devices/fixtures/v3_hello.golden.json b/src/devices/fixtures/v3_hello.golden.json new file mode 100644 index 0000000..ad7622e --- /dev/null +++ b/src/devices/fixtures/v3_hello.golden.json @@ -0,0 +1 @@ +{"type":"hello","group_id":"grp_1","profile":{"device_id":"tui_a","name":"TUI","client_version":"0.3.4","protocol_version":3,"endpoint_id":"e","endpoint_ticket":"t","revoked":false,"revoke_cutoff_seq":null,"updated_at_ms":5},"devices":[{"device_id":"tui_a","name":"TUI","client_version":"0.3.4","protocol_version":3,"endpoint_id":"e","endpoint_ticket":"t","revoked":false,"revoke_cutoff_seq":null,"updated_at_ms":5},{"device_id":"web_b","name":"TUI","client_version":"0.3.4","protocol_version":3,"endpoint_id":"e","endpoint_ticket":"t","revoked":false,"revoke_cutoff_seq":null,"updated_at_ms":5}],"vector":{"tui_a":12,"web_b":4},"ops":[{"op_id":"tui_a:1","origin_device_id":"tui_a","seq":1,"hlc_ms":1700000000001,"payload":{"kind":"track_like_set","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","liked":true,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}}},{"op_id":"tui_a:2","origin_device_id":"tui_a","seq":2,"hlc_ms":1700000000002,"payload":{"kind":"playlist_created","playlist_id":"pl","title":"Mix"}},{"op_id":"tui_a:3","origin_device_id":"tui_a","seq":3,"hlc_ms":1700000000003,"payload":{"kind":"playlist_renamed","playlist_id":"pl","title":"Mix 2"}},{"op_id":"tui_a:4","origin_device_id":"tui_a","seq":4,"hlc_ms":1700000000004,"payload":{"kind":"playlist_track_added","playlist_id":"pl","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","position":0,"fed":null}},{"op_id":"tui_a:5","origin_device_id":"tui_a","seq":5,"hlc_ms":1700000000005,"payload":{"kind":"playlist_track_removed","playlist_id":"pl","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111"}},{"op_id":"tui_a:6","origin_device_id":"tui_a","seq":6,"hlc_ms":1700000000006,"payload":{"kind":"playlist_deleted","playlist_id":"pl"}},{"op_id":"tui_a:7","origin_device_id":"tui_a","seq":7,"hlc_ms":1700000000007,"payload":{"kind":"device_profile_set","name":"TUI","client_version":"0.3.4","endpoint_ticket":"t","endpoint_id":"e"}},{"op_id":"tui_a:8","origin_device_id":"tui_a","seq":8,"hlc_ms":1700000000008,"payload":{"kind":"device_trusted","target_device_id":"web_b"}},{"op_id":"tui_a:9","origin_device_id":"tui_a","seq":9,"hlc_ms":1700000000009,"payload":{"kind":"device_revoked","target_device_id":"old","target_max_seq_seen":3}},{"op_id":"tui_a:10","origin_device_id":"tui_a","seq":10,"hlc_ms":1700000000010,"payload":{"kind":"playback_command","target_device_id":"web_b","command":{"kind":"set_state","state":{"queue":[{"id":7,"title":"Song","track_number":1,"disc_number":null,"duration_seconds":180.5,"artist_names":["A"],"featured_artist_names":["B"],"release_id":3,"release_title":"Album","release_year":2001,"file_path":"","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","audio_format":"flac","audio_bitrate":900,"audio_sample_rate":44100,"audio_bit_depth":16,"file_size_bytes":12345,"play_count":2,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}},{"id":0,"title":"Remote","track_number":null,"disc_number":null,"duration_seconds":0.0,"artist_names":[],"featured_artist_names":[],"release_id":0,"release_title":"","release_year":null,"file_path":"","content_id":null,"audio_format":null,"audio_bitrate":null,"audio_sample_rate":null,"audio_bit_depth":null,"file_size_bytes":null,"play_count":0,"fed":null}],"queue_pos":1,"playing":true,"paused":false,"idle_since_ms":null,"position_secs":42.5,"volume":73,"shuffle":true,"repeat":"all"},"seek":true},"authority":{"version":1,"claim":{"counter":3,"issuer":"tui_a","owner":"tui_a"},"sequence":9}}},{"op_id":"tui_a:11","origin_device_id":"tui_a","seq":11,"hlc_ms":1700000000011,"payload":{"kind":"playback_command","target_device_id":"web_b","command":{"kind":"active_changed","active_device_id":"web_b","active_device_name":"WEB","state":{"queue":[{"id":7,"title":"Song","track_number":1,"disc_number":null,"duration_seconds":180.5,"artist_names":["A"],"featured_artist_names":["B"],"release_id":3,"release_title":"Album","release_year":2001,"file_path":"","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","audio_format":"flac","audio_bitrate":900,"audio_sample_rate":44100,"audio_bit_depth":16,"file_size_bytes":12345,"play_count":2,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}},{"id":0,"title":"Remote","track_number":null,"disc_number":null,"duration_seconds":0.0,"artist_names":[],"featured_artist_names":[],"release_id":0,"release_title":"","release_year":null,"file_path":"","content_id":null,"audio_format":null,"audio_bitrate":null,"audio_sample_rate":null,"audio_bit_depth":null,"file_size_bytes":null,"play_count":0,"fed":null}],"queue_pos":1,"playing":true,"paused":false,"idle_since_ms":null,"position_secs":42.5,"volume":73,"shuffle":true,"repeat":"all"}},"authority":null}},{"op_id":"tui_a:12","origin_device_id":"tui_a","seq":12,"hlc_ms":1700000000012,"payload":{"kind":"listen_recorded","event":{"listen_id":"l1","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","started_at_ms":1,"listened_ms":60000,"track_duration_ms":180000,"ended_reason":"finished","track":{"title":"Song","artist_names":["A"],"featured_artist_names":[],"release_title":null}}}}],"snapshot":{"likes":[{"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","hlc_ms":1,"op_id":"tui_a:1","fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}}],"unlikes":[{"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","hlc_ms":2,"op_id":"tui_a:2"}],"playlists":[{"playlist_id":"pl","title":"Mix","hlc_ms":3,"op_id":"tui_a:3","items":[{"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","position":0,"hlc_ms":4,"op_id":"tui_a:4","fed":null}]}],"deleted_playlists":[{"playlist_id":"gone","hlc_ms":5,"op_id":"tui_a:5"}],"removed_playlist_items":[{"playlist_id":"pl","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","hlc_ms":6,"op_id":"tui_a:6"}]},"playback":{"device_id":"tui_a","device_name":"TUI","active":true,"updated_at_ms":9,"state":{"queue":[{"id":7,"title":"Song","track_number":1,"disc_number":null,"duration_seconds":180.5,"artist_names":["A"],"featured_artist_names":["B"],"release_id":3,"release_title":"Album","release_year":2001,"file_path":"","content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","audio_format":"flac","audio_bitrate":900,"audio_sample_rate":44100,"audio_bit_depth":16,"file_size_bytes":12345,"play_count":2,"fed":{"item_id":"item","owner":"owner","title":"Song","artist_names":["A"],"featured_artist_names":[],"year":2001,"duration_seconds":180,"content_id":"b3:1111111111111111111111111111111111111111111111111111111111111111","release_title":"Album","track_number":1,"disc_number":1}},{"id":0,"title":"Remote","track_number":null,"disc_number":null,"duration_seconds":0.0,"artist_names":[],"featured_artist_names":[],"release_id":0,"release_title":"","release_year":null,"file_path":"","content_id":null,"audio_format":null,"audio_bitrate":null,"audio_sample_rate":null,"audio_bit_depth":null,"file_size_bytes":null,"play_count":0,"fed":null}],"queue_pos":1,"playing":true,"paused":false,"idle_since_ms":null,"position_secs":42.5,"volume":73,"shuffle":true,"repeat":"all"},"coordination":{"version":1,"claim":{"counter":3,"issuer":"tui_a","owner":"tui_a"},"heartbeat":4,"available":true,"playing":true}}} diff --git a/src/devices/interop_tests.rs b/src/devices/interop_tests.rs index 4c7c802..95bf5ca 100644 --- a/src/devices/interop_tests.rs +++ b/src/devices/interop_tests.rs @@ -61,7 +61,10 @@ async fn localhost_web_peer() { bytes.push(b'\n'); stream.write_all(&bytes).await.unwrap(); let response: WireMessage = - serde_json::from_slice(&read_line(&mut stream).await.unwrap()).unwrap(); + serde_json::from_slice( + &music_dht::device_sync::read_line(&mut stream).await.unwrap(), + ) + .unwrap(); let WireMessage::SyncResponse { accepted: true, playback: Some(snapshot), diff --git a/src/devices/tests.rs b/src/devices/tests.rs index 286e97b..cc5d67f 100644 --- a/src/devices/tests.rs +++ b/src/devices/tests.rs @@ -229,6 +229,7 @@ fn empty_playback_state() -> PlaybackStateWire { volume: 80, shuffle: false, repeat: PlaybackRepeat::Off, + playback_rate: None, } } @@ -424,12 +425,25 @@ fn test_fed_track(content_id: &str) -> crate::federation::FedTrack { } #[test] -fn base64url_round_trip_without_padding() { - for input in [b"".as_slice(), b"a", b"ab", b"abc", b"abcdef"] { - let encoded = base64url_encode(input); - assert!(!encoded.contains('=')); - assert_eq!(base64url_decode(&encoded).unwrap(), input); - } +fn invites_round_trip_through_the_shared_encoding() { + let invite = InviteWire { + v: 1, + ticket: "ticket".into(), + device_id: "dev_a".into(), + invite_id: "inv".into(), + secret: "s3cr3t".into(), + expires_at_ms: 10, + protocol_version: None, + }; + let link = encode_invite(&invite).unwrap(); + assert!(!link.contains('=')); + assert_eq!(parse_invite(&link).unwrap(), invite); + assert!( + parse_invite("frid://x/abc") + .unwrap_err() + .to_string() + .contains(":connect") + ); } #[test] @@ -566,6 +580,7 @@ fn playback_command_is_targeted_and_deduplicated() { volume: 42, shuffle: false, repeat: PlaybackRepeat::Off, + playback_rate: None, }, seek: false, }; @@ -622,6 +637,7 @@ fn playback_commands_are_caught_up_only_by_their_target_while_fresh() { volume: 42, shuffle: false, repeat: PlaybackRepeat::Off, + playback_rate: None, }, seek: false, }; diff --git a/src/devices/wire_compat_tests.rs b/src/devices/wire_compat_tests.rs new file mode 100644 index 0000000..4aad9ed --- /dev/null +++ b/src/devices/wire_compat_tests.rs @@ -0,0 +1,533 @@ +//! Golden wire-compatibility tests: the shared `music_dht::device_sync` +//! types this client now uses must serialize v3 content byte-for-byte like +//! the private copies of furumi-tui 0.3.x (kept verbatim in `legacy` +//! below), so 0.3.x clients and furumi-web 0.12.x keep interoperating. + +use super::*; + +/// Private wire types of furumi-tui 0.3.x (`src/devices.rs` before sync +/// v4), copied verbatim apart from visibility, `PartialEq` and doc comments. +#[allow(dead_code)] +pub(super) mod legacy { + use music_dht::device_sync::ListenEvent; + use music_dht::playback::CommandStamp; + use serde::{Deserialize, Serialize}; + use std::collections::BTreeMap; + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct InviteWire { + pub v: u16, + #[serde(rename = "t")] + pub ticket: String, + #[serde(rename = "d")] + pub device_id: String, + #[serde(rename = "i")] + pub invite_id: String, + #[serde(rename = "s")] + pub secret: String, + #[serde(rename = "e")] + pub expires_at_ms: i64, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct DeviceProfileWire { + pub device_id: String, + pub name: String, + pub client_version: String, + pub protocol_version: u16, + pub endpoint_id: String, + pub endpoint_ticket: String, + #[serde(default)] + pub revoked: bool, + #[serde(default)] + pub revoke_cutoff_seq: Option, + #[serde(default)] + pub updated_at_ms: i64, + } + + #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] + pub struct SyncedFedTrack { + pub item_id: String, + pub owner: String, + pub title: String, + #[serde(default)] + pub artist_names: Vec, + #[serde(default)] + pub featured_artist_names: Vec, + pub year: Option, + pub duration_seconds: Option, + pub content_id: String, + pub release_title: Option, + pub track_number: Option, + pub disc_number: Option, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct PlaybackTrack { + pub id: i64, + pub title: String, + pub track_number: Option, + pub disc_number: Option, + pub duration_seconds: f64, + #[serde(default)] + pub artist_names: Vec, + #[serde(default)] + pub featured_artist_names: Vec, + pub release_id: i64, + pub release_title: String, + pub release_year: Option, + #[serde(default)] + pub file_path: String, + pub content_id: Option, + pub audio_format: Option, + pub audio_bitrate: Option, + pub audio_sample_rate: Option, + pub audio_bit_depth: Option, + pub file_size_bytes: Option, + #[serde(default)] + pub play_count: i64, + #[serde(default)] + pub fed: Option, + } + + #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] + #[serde(rename_all = "snake_case")] + pub enum PlaybackRepeat { + #[default] + Off, + One, + All, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct PlaybackStateWire { + #[serde(default)] + pub queue: Vec, + #[serde(default)] + pub queue_pos: usize, + pub playing: bool, + pub paused: bool, + #[serde(default)] + pub idle_since_ms: Option, + pub position_secs: f64, + #[serde(default)] + pub volume: u8, + pub shuffle: bool, + pub repeat: PlaybackRepeat, + } + + pub type PlaybackSnapshot = music_dht::playback::Snapshot; + pub type PlaybackCommand = music_dht::playback::Command; + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SyncOpWire { + pub op_id: String, + pub origin_device_id: String, + pub seq: i64, + pub hlc_ms: i64, + pub payload: SyncOpPayload, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + #[serde(tag = "kind", rename_all = "snake_case")] + pub enum SyncOpPayload { + TrackLikeSet { + content_id: String, + liked: bool, + #[serde(default)] + fed: Option, + }, + PlaylistCreated { + playlist_id: String, + title: String, + }, + PlaylistRenamed { + playlist_id: String, + title: String, + }, + PlaylistDeleted { + playlist_id: String, + }, + PlaylistTrackAdded { + playlist_id: String, + content_id: String, + position: i64, + #[serde(default)] + fed: Option, + }, + PlaylistTrackRemoved { + playlist_id: String, + content_id: String, + }, + DeviceProfileSet { + name: String, + client_version: String, + endpoint_ticket: String, + endpoint_id: String, + }, + DeviceTrusted { + target_device_id: String, + }, + DeviceRevoked { + target_device_id: String, + target_max_seq_seen: i64, + }, + PlaybackCommand { + target_device_id: String, + command: PlaybackCommand, + #[serde(default)] + authority: Option, + }, + ListenRecorded { + event: ListenEvent, + }, + } + + #[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)] + pub struct SyncSnapshot { + #[serde(default)] + pub likes: Vec, + #[serde(default)] + pub unlikes: Vec, + #[serde(default)] + pub playlists: Vec, + #[serde(default)] + pub deleted_playlists: Vec, + #[serde(default)] + pub removed_playlist_items: Vec, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SnapshotLike { + pub content_id: String, + pub hlc_ms: i64, + pub op_id: String, + #[serde(default)] + pub fed: Option, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SnapshotLikeTombstone { + pub content_id: String, + pub hlc_ms: i64, + pub op_id: String, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SnapshotPlaylist { + pub playlist_id: String, + pub title: String, + pub hlc_ms: i64, + pub op_id: String, + #[serde(default)] + pub items: Vec, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SnapshotPlaylistTombstone { + pub playlist_id: String, + pub hlc_ms: i64, + pub op_id: String, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SnapshotPlaylistItem { + pub content_id: String, + pub position: i64, + pub hlc_ms: i64, + pub op_id: String, + #[serde(default)] + pub fed: Option, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + pub struct SnapshotPlaylistItemTombstone { + pub playlist_id: String, + pub content_id: String, + pub hlc_ms: i64, + pub op_id: String, + } + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] + #[serde(tag = "type", rename_all = "snake_case")] + pub enum WireMessage { + PairRequest { + invite_id: String, + secret: String, + profile: DeviceProfileWire, + #[serde(default)] + group_id: Option, + #[serde(default)] + group_active_devices: usize, + #[serde(default)] + devices: Vec, + vector: BTreeMap, + ops: Vec, + snapshot: SyncSnapshot, + #[serde(default)] + playback: Option, + }, + PairResponse { + accepted: bool, + #[serde(default)] + pending: bool, + #[serde(default)] + error: Option, + #[serde(default)] + group_id: Option, + #[serde(default)] + profile: Option, + #[serde(default)] + devices: Vec, + #[serde(default)] + vector: BTreeMap, + #[serde(default)] + ops: Vec, + #[serde(default)] + snapshot: SyncSnapshot, + #[serde(default)] + playback: Option, + }, + Hello { + group_id: String, + profile: DeviceProfileWire, + devices: Vec, + vector: BTreeMap, + ops: Vec, + snapshot: SyncSnapshot, + #[serde(default)] + playback: Option, + }, + SyncResponse { + accepted: bool, + #[serde(default)] + error: Option, + #[serde(default)] + devices: Vec, + #[serde(default)] + vector: BTreeMap, + #[serde(default)] + ops: Vec, + #[serde(default)] + snapshot: SyncSnapshot, + #[serde(default)] + playback: Option, + }, + } +} + +const CONTENT_ID: &str = "b3:1111111111111111111111111111111111111111111111111111111111111111"; + +/// A v3 `hello` exercising every v3 operation kind, every snapshot section +/// and a coordinated playback snapshot (input order is irrelevant). +fn v3_hello_input() -> String { + let fed = serde_json::json!({ + "item_id": "item", "owner": "owner", "title": "Song", "artist_names": ["A"], + "featured_artist_names": [], "year": 2001, "duration_seconds": 180, + "content_id": CONTENT_ID, "release_title": "Album", "track_number": 1, "disc_number": 1, + }); + let track = serde_json::json!({ + "id": 7, "title": "Song", "track_number": 1, "disc_number": null, + "duration_seconds": 180.5, "artist_names": ["A"], "featured_artist_names": ["B"], + "release_id": 3, "release_title": "Album", "release_year": 2001, "file_path": "", + "content_id": CONTENT_ID, "audio_format": "flac", "audio_bitrate": 900, + "audio_sample_rate": 44100, "audio_bit_depth": 16, "file_size_bytes": 12345, + "play_count": 2, "fed": fed, + }); + let state = serde_json::json!({ + "queue": [track, {"id": 0, "title": "Remote", "track_number": null, "disc_number": null, + "duration_seconds": 0.0, "release_id": 0, "release_title": "", "release_year": null, + "content_id": null, "audio_format": null, "audio_bitrate": null, + "audio_sample_rate": null, "audio_bit_depth": null, "file_size_bytes": null}], + "queue_pos": 1, "playing": true, "paused": false, "idle_since_ms": null, + "position_secs": 42.5, "volume": 73, "shuffle": true, "repeat": "all", + }); + let claim = serde_json::json!({"counter": 3, "issuer": "tui_a", "owner": "tui_a"}); + let stamp = serde_json::json!({"version": 1, "claim": claim, "sequence": 9}); + let op = |seq: i64, payload: serde_json::Value| { + serde_json::json!({"op_id": format!("tui_a:{seq}"), "origin_device_id": "tui_a", + "seq": seq, "hlc_ms": 1_700_000_000_000i64 + seq, "payload": payload}) + }; + let profile = |id: &str| { + serde_json::json!({"device_id": id, "name": "TUI", "client_version": "0.3.4", + "protocol_version": 3, "endpoint_id": "e", "endpoint_ticket": "t", + "revoked": false, "revoke_cutoff_seq": null, "updated_at_ms": 5}) + }; + serde_json::json!({ + "type": "hello", + "group_id": "grp_1", + "profile": profile("tui_a"), + "devices": [profile("tui_a"), profile("web_b")], + "vector": {"tui_a": 12, "web_b": 4}, + "ops": [ + op(1, serde_json::json!({"kind": "track_like_set", "content_id": CONTENT_ID, "liked": true, "fed": fed})), + op(2, serde_json::json!({"kind": "playlist_created", "playlist_id": "pl", "title": "Mix"})), + op(3, serde_json::json!({"kind": "playlist_renamed", "playlist_id": "pl", "title": "Mix 2"})), + op(4, serde_json::json!({"kind": "playlist_track_added", "playlist_id": "pl", "content_id": CONTENT_ID, "position": 0, "fed": null})), + op(5, serde_json::json!({"kind": "playlist_track_removed", "playlist_id": "pl", "content_id": CONTENT_ID})), + op(6, serde_json::json!({"kind": "playlist_deleted", "playlist_id": "pl"})), + op(7, serde_json::json!({"kind": "device_profile_set", "name": "TUI", "client_version": "0.3.4", "endpoint_ticket": "t", "endpoint_id": "e"})), + op(8, serde_json::json!({"kind": "device_trusted", "target_device_id": "web_b"})), + op(9, serde_json::json!({"kind": "device_revoked", "target_device_id": "old", "target_max_seq_seen": 3})), + op(10, serde_json::json!({"kind": "playback_command", "target_device_id": "web_b", + "command": {"kind": "set_state", "state": state, "seek": true}, "authority": stamp})), + op(11, serde_json::json!({"kind": "playback_command", "target_device_id": "web_b", + "command": {"kind": "active_changed", "active_device_id": "web_b", "active_device_name": "WEB", "state": state}})), + op(12, serde_json::json!({"kind": "listen_recorded", "event": {"listen_id": "l1", + "content_id": CONTENT_ID, "started_at_ms": 1, "listened_ms": 60000, "track_duration_ms": 180000, + "ended_reason": "finished", "track": {"title": "Song", "artist_names": ["A"], "featured_artist_names": [], "release_title": null}}})), + ], + "snapshot": { + "likes": [{"content_id": CONTENT_ID, "hlc_ms": 1, "op_id": "tui_a:1", "fed": fed}], + "unlikes": [{"content_id": CONTENT_ID, "hlc_ms": 2, "op_id": "tui_a:2"}], + "playlists": [{"playlist_id": "pl", "title": "Mix", "hlc_ms": 3, "op_id": "tui_a:3", + "items": [{"content_id": CONTENT_ID, "position": 0, "hlc_ms": 4, "op_id": "tui_a:4", "fed": null}]}], + "deleted_playlists": [{"playlist_id": "gone", "hlc_ms": 5, "op_id": "tui_a:5"}], + "removed_playlist_items": [{"playlist_id": "pl", "content_id": CONTENT_ID, "hlc_ms": 6, "op_id": "tui_a:6"}], + }, + "playback": {"device_id": "tui_a", "device_name": "TUI", "active": true, "updated_at_ms": 9, + "state": state, "coordination": {"version": 1, "claim": claim, "heartbeat": 4, "available": true, "playing": true}}, + }) + .to_string() +} + +fn v3_other_inputs() -> Vec { + vec![ + r#"{"type":"sync_response","accepted":false,"error":"device is not trusted"}"#.into(), + r#"{"type":"pair_response","accepted":false,"pending":true,"error":"pairing pending"}"# + .into(), + serde_json::json!({"type": "pair_request", "invite_id": "i", "secret": "s", + "profile": {"device_id": "tui_a", "name": "TUI", "client_version": "0.3.4", + "protocol_version": 3, "endpoint_id": "e", "endpoint_ticket": "t"}, + "vector": {}, "ops": [], "snapshot": {}}) + .to_string(), + ] +} + +/// Parses `input` with the 0.3.x types and the shared types and checks +/// that both serialize to the same bytes, and that each side parses the +/// other's output. +fn assert_identical(input: &str) -> String { + let old: legacy::WireMessage = serde_json::from_str(input).unwrap(); + let new: WireMessage = serde_json::from_str(input).unwrap(); + let old_json = serde_json::to_string(&old).unwrap(); + let new_json = serde_json::to_string(&new).unwrap(); + assert_eq!(old_json, new_json); + assert_eq!( + serde_json::from_str::(&new_json).unwrap(), + old + ); + assert_eq!(serde_json::from_str::(&old_json).unwrap(), new); + new_json +} + +#[test] +fn v3_messages_serialize_like_furumi_tui_0_3() { + let hello = assert_identical(&v3_hello_input()); + let golden = concat!( + env!("CARGO_MANIFEST_DIR"), + "/src/devices/fixtures/v3_hello.golden.json" + ); + if std::env::var_os("FURUMI_BLESS_GOLDEN").is_some() { + // Only for a deliberate change of the v3 shape. + std::fs::write(golden, format!("{hello}\n")).unwrap(); + } + assert_eq!(hello, std::fs::read_to_string(golden).unwrap().trim_end()); + for input in v3_other_inputs() { + assert_identical(&input); + } +} + +#[test] +fn music_queue_items_keep_their_v3_shape() { + let track = TrackItem { + id: 7, + title: "Song".into(), + track_number: Some(1), + disc_number: None, + duration_seconds: 180.5, + artists: vec![ArtistRef { + id: 1, + name: "A".into(), + }], + featured_artists: Vec::new(), + release_id: 3, + release_title: "Album".into(), + release_year: Some(2001), + file_path: "/Users/me/Music/song.flac".into(), + content_id: Some(CONTENT_ID.into()), + cover_path: None, + audio_format: Some("flac".into()), + audio_bitrate: Some(900), + audio_sample_rate: Some(44_100), + audio_bit_depth: Some(16), + file_size_bytes: Some(12_345), + play_count: 2, + fed: None, + podcast: None, + }; + let wire = PlaybackTrack::from_track(&track); + let json = serde_json::to_string(&wire).unwrap(); + assert!( + !json.contains("source"), + "music items carry no source: {json}" + ); + let old: legacy::PlaybackTrack = serde_json::from_str(&json).unwrap(); + assert_eq!(serde_json::to_string(&old).unwrap(), json); +} + +#[test] +fn invites_from_older_clients_stay_readable() { + let old = legacy::InviteWire { + v: 1, + ticket: "ticket".into(), + device_id: "tui_a".into(), + invite_id: "inv".into(), + secret: "s3cr3t".into(), + expires_at_ms: 10, + }; + let old_json = serde_json::to_string(&old).unwrap(); + assert_eq!( + old_json, + r#"{"v":1,"t":"ticket","d":"tui_a","i":"inv","s":"s3cr3t","e":10}"# + ); + let shared: InviteWire = serde_json::from_str(&old_json).unwrap(); + assert_eq!( + shared.inviter_protocol_version(), + music_dht::device_sync::UNREPORTED_PROTOCOL_VERSION + ); + assert_eq!(serde_json::to_string(&shared).unwrap(), old_json); +} + +#[test] +fn v3_peers_cannot_parse_podcast_operations() { + // Why podcast operations must be gated: an unknown `kind` breaks the + // whole message for a 0.3.x peer, not one operation. + let mut hello: serde_json::Value = serde_json::from_str(&v3_hello_input()).unwrap(); + hello["ops"].as_array_mut().unwrap().push(serde_json::json!({ + "op_id": "tui_a:13", "origin_device_id": "tui_a", "seq": 13, "hlc_ms": 13, + "payload": {"kind": "podcast_share_set", + "podcast_id": music_dht::podcast::PodcastId::from_feed_url( + &music_dht::podcast::FeedUrl::parse("https://podcasts.example/feed.xml").unwrap()), + "shared": false, "generation": 1}, + })); + assert!(serde_json::from_value::(hello.clone()).is_err()); + assert!(serde_json::from_value::(hello).is_ok()); +} + +#[test] +fn v3_peers_would_drop_the_source_of_podcast_items() { + // Why podcast playback must be gated: older types ignore `source` and + // forward the episode as a broken music item. + let episode = crate::app::podcast_fixtures::episode_track(1) + .podcast + .unwrap(); + let wire = PlaybackTrack::podcast_episode(episode); + let json = serde_json::to_string(&wire).unwrap(); + assert!(json.contains(r#""source":{"kind":"podcast_episode""#)); + let old: legacy::PlaybackTrack = serde_json::from_str(&json).unwrap(); + let forwarded: PlaybackTrack = + serde_json::from_str(&serde_json::to_string(&old).unwrap()).unwrap(); + assert_eq!(forwarded.source, None); + assert_eq!(forwarded.id, 0); +} diff --git a/src/jam.rs b/src/jam.rs index b6bff7a..7522f35 100644 --- a/src/jam.rs +++ b/src/jam.rs @@ -666,6 +666,7 @@ mod tests { volume: 73, shuffle: false, repeat: crate::devices::PlaybackRepeat::Off, + playback_rate: None, }; host.publish_host_playback(PlaybackSnapshot { coordination: None,