/api/podcasts now lists subscriptions with counters and fetch state, subscribes by feed URL (fetched first; nothing is stored for a URL that is not a public feed), shows a podcast with its seasons and history, pages and searches episodes, and runs the explicit progress actions (start over, played, unplayed) and unsubscribe/subscribe again. The web player gets two endpoints: playback returns the audio source and the resume position and, when the browser starts playing, writes a new listening session as an explicit action above the carried handoff generation; progress stores checkpoints, pause, stop and handoff at the session generation, a seek as an explicit action, completes the episode once at the end or within the completion tail, and records the listening session. Handlers delegate to podcasts::api, which the new Postgres test drives directly. Podcast queue items are no longer marked unavailable in browser JSON and carry the episode artwork. The temporary dead-code allowance of the podcast module is gone; helpers used only by tests are cfg(test) and complete_session gave way to complete_if_current. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
711 lines
28 KiB
Rust
711 lines
28 KiB
Rust
//! Lossless queue items shared by the browser player, device sync and the
|
|
//! persisted playback state.
|
|
//!
|
|
//! The browser queue holds plain track JSON objects. Library tracks of this
|
|
//! server keep their usual shape. Every other item received from a trusted
|
|
//! device (unresolved federated music, podcast episodes, Jam private
|
|
//! placeholders) becomes an *external* item: display fields for the queue UI
|
|
//! plus the verbatim device-sync DTO under [`WIRE_TRACK_KEY`] and its explicit
|
|
//! [`PlaybackSource`] under [`SOURCE_KEY`]. Converting back to the wire uses
|
|
//! the verbatim DTO, so such items survive browser -> server -> peers ->
|
|
//! server -> browser unchanged. The web player plays podcast episodes
|
|
//! through `/api/podcasts/episodes/{id}/playback` (publisher URL or the
|
|
//! optional proxy); placeholders and unresolved federated music stay
|
|
//! unplayable here.
|
|
//!
|
|
//! Gating and Jam decisions are delegated to `music_dht::device_sync`; this
|
|
//! module only maps browser JSON onto the shared DTOs.
|
|
|
|
use music_dht::device_sync::{
|
|
PRIVATE_ITEM_TITLE, PlaybackCommand, PlaybackSource, PlaybackStateWire, PlaybackTrack,
|
|
jam_command_allowed, redact_for_jam, restore_jam_private_items,
|
|
};
|
|
use serde::{Deserialize, Serialize};
|
|
use serde_json::Value;
|
|
|
|
/// Browser track key holding the verbatim [`PlaybackTrack`] of an external item.
|
|
pub(crate) const WIRE_TRACK_KEY: &str = "wire_track";
|
|
/// Browser track key holding the explicit [`PlaybackSource`] of an external item.
|
|
pub(crate) const SOURCE_KEY: &str = "source";
|
|
/// Browser playback state key: `true` when the browser does not know the
|
|
/// position of its current item. That happens when it selects a podcast
|
|
/// episode it cannot play (Next, auto-advance, a click or a play command):
|
|
/// it is never told where the episode was left, and inventing 0 would
|
|
/// restart the episode for every device. The server then takes the
|
|
/// position from the episode's progress register.
|
|
pub(crate) const POSITION_UNKNOWN_KEY: &str = "position_unknown";
|
|
|
|
/// Reason shown for federated music that is not in this library.
|
|
pub(crate) const FED_UNAVAILABLE_REASON: &str = "Not available on this web player yet";
|
|
/// Reason shown for Jam placeholders of someone else's private item.
|
|
pub(crate) const PRIVATE_UNAVAILABLE_REASON: &str = "Private item of the Jam host";
|
|
|
|
/// Version of the typed queue stored in `furumusic__playback_state.queue_items_json`.
|
|
pub(crate) const STORED_QUEUE_VERSION: u16 = 1;
|
|
/// Upper bound of persisted queue items; larger queues keep only `queue_json`.
|
|
pub(crate) const MAX_STORED_QUEUE_ITEMS: usize = 10_000;
|
|
|
|
/// Browser JSON for a queue item that is not a library track of this server.
|
|
///
|
|
/// `content_id` is the normalized content id of a music item, when known.
|
|
/// The `id` is a negative placeholder that is stable for the item and its
|
|
/// queue position, so the browser can tell items apart; it never refers to a
|
|
/// library track.
|
|
pub(crate) fn external_track_json(
|
|
track: &PlaybackTrack,
|
|
index: usize,
|
|
content_id: Option<&str>,
|
|
) -> Value {
|
|
let mut json = match &track.source {
|
|
Some(PlaybackSource::PodcastEpisode(episode)) => serde_json::json!({
|
|
"id": placeholder_track_id(Some(episode.episode_id.as_str()), index),
|
|
"title": episode.episode_title,
|
|
"track_number": serde_json::Value::Null,
|
|
"disc_number": serde_json::Value::Null,
|
|
"duration_seconds": episode.duration_ms.unwrap_or(0).max(0) as f64 / 1_000.0,
|
|
"artists": artist_names_to_json(std::slice::from_ref(&episode.podcast_title)),
|
|
"featured_artists": [],
|
|
"release_id": 0,
|
|
"release_title": episode.podcast_title,
|
|
"release_year": serde_json::Value::Null,
|
|
// Artwork is loaded from the publisher, like the audio.
|
|
"cover_url": episode.image_url,
|
|
// The player asks `/api/podcasts/episodes/{id}/playback` for the
|
|
// audio source when it starts the episode.
|
|
"stream_url": "",
|
|
"uploader_name": "Podcast",
|
|
"audio_format": episode.mime,
|
|
"content_id": serde_json::Value::Null,
|
|
"unavailable": false,
|
|
}),
|
|
Some(PlaybackSource::Private) => serde_json::json!({
|
|
"id": placeholder_track_id(Some("private"), index),
|
|
"title": PRIVATE_ITEM_TITLE,
|
|
"track_number": serde_json::Value::Null,
|
|
"disc_number": serde_json::Value::Null,
|
|
"duration_seconds": 0.0,
|
|
"artists": [],
|
|
"featured_artists": [],
|
|
"release_id": 0,
|
|
"release_title": "",
|
|
"release_year": serde_json::Value::Null,
|
|
"cover_url": serde_json::Value::Null,
|
|
"stream_url": "",
|
|
"uploader_name": "",
|
|
"content_id": serde_json::Value::Null,
|
|
"unavailable": true,
|
|
"unavailable_reason": PRIVATE_UNAVAILABLE_REASON,
|
|
}),
|
|
Some(PlaybackSource::Music) | None => music_placeholder_json(track, index, content_id),
|
|
};
|
|
if let Some(object) = json.as_object_mut() {
|
|
if let Some(source) = &track.source
|
|
&& let Ok(source) = serde_json::to_value(source)
|
|
{
|
|
object.insert(SOURCE_KEY.to_string(), source);
|
|
}
|
|
if let Ok(wire) = serde_json::to_value(track) {
|
|
object.insert(WIRE_TRACK_KEY.to_string(), wire);
|
|
}
|
|
}
|
|
json
|
|
}
|
|
|
|
/// Display fields of unresolved federated music (unchanged from earlier
|
|
/// releases, which had no verbatim wire item).
|
|
fn music_placeholder_json(track: &PlaybackTrack, index: usize, content_id: Option<&str>) -> Value {
|
|
let artists = if !track.artist_names.is_empty() {
|
|
track.artist_names.clone()
|
|
} else if let Some(fed) = &track.fed {
|
|
fed.artist_names.clone()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let featured = if !track.featured_artist_names.is_empty() {
|
|
track.featured_artist_names.clone()
|
|
} else if let Some(fed) = &track.fed {
|
|
fed.featured_artist_names.clone()
|
|
} else {
|
|
Vec::new()
|
|
};
|
|
let title = track
|
|
.fed
|
|
.as_ref()
|
|
.map(|fed| fed.title.as_str())
|
|
.filter(|title| !title.trim().is_empty())
|
|
.unwrap_or(&track.title);
|
|
let release_title = track
|
|
.fed
|
|
.as_ref()
|
|
.and_then(|fed| fed.release_title.as_deref())
|
|
.filter(|title| !title.trim().is_empty())
|
|
.unwrap_or(&track.release_title);
|
|
let content_id = content_id
|
|
.map(ToString::to_string)
|
|
.or_else(|| track.content_id.clone())
|
|
.or_else(|| track.fed.as_ref().map(|fed| fed.content_id.clone()));
|
|
serde_json::json!({
|
|
"id": placeholder_track_id(content_id.as_deref(), index),
|
|
"title": title,
|
|
"track_number": track.track_number,
|
|
"disc_number": track.disc_number,
|
|
"duration_seconds": track.duration_seconds,
|
|
"artists": artist_names_to_json(&artists),
|
|
"featured_artists": artist_names_to_json(&featured),
|
|
"release_id": 0,
|
|
"release_title": release_title,
|
|
"release_year": track.release_year,
|
|
"cover_url": serde_json::Value::Null,
|
|
"stream_url": "",
|
|
"uploader_name": "Federation",
|
|
"audio_format": track.audio_format.clone(),
|
|
"audio_bitrate": track.audio_bitrate,
|
|
"audio_sample_rate": track.audio_sample_rate,
|
|
"audio_bit_depth": track.audio_bit_depth,
|
|
"file_size_bytes": track.file_size_bytes,
|
|
"content_id": content_id,
|
|
"unavailable": true,
|
|
"unavailable_reason": FED_UNAVAILABLE_REASON,
|
|
})
|
|
}
|
|
|
|
fn artist_names_to_json(names: &[String]) -> Vec<Value> {
|
|
names
|
|
.iter()
|
|
.enumerate()
|
|
.filter(|(_, name)| !name.trim().is_empty())
|
|
.map(|(index, name)| serde_json::json!({"id": -((index as i64) + 1), "name": name}))
|
|
.collect()
|
|
}
|
|
|
|
fn placeholder_track_id(seed: Option<&str>, index: usize) -> i64 {
|
|
let mut bytes = [0u8; 8];
|
|
let hash = blake3::hash(seed.unwrap_or("").as_bytes());
|
|
bytes.copy_from_slice(&hash.as_bytes()[..8]);
|
|
let value = i64::from_le_bytes(bytes).unsigned_abs() % 9_000_000_000_000;
|
|
-((value as i64) + index as i64 + 1)
|
|
}
|
|
|
|
/// The device-sync item carried by an external browser track.
|
|
///
|
|
/// Returns the verbatim [`WIRE_TRACK_KEY`] DTO when present. Otherwise a
|
|
/// browser item that only names a podcast or private [`SOURCE_KEY`] is
|
|
/// rebuilt with the shared constructors. Library tracks (and malformed
|
|
/// items) return `None` and keep the library mapping.
|
|
pub(crate) fn wire_track_from_browser_json(track: &Value) -> Option<PlaybackTrack> {
|
|
if let Some(wire) = track.get(WIRE_TRACK_KEY).filter(|wire| wire.is_object())
|
|
&& let Ok(wire) = serde_json::from_value::<PlaybackTrack>(wire.clone())
|
|
{
|
|
return Some(wire);
|
|
}
|
|
match serde_json::from_value::<PlaybackSource>(track.get(SOURCE_KEY)?.clone()).ok()? {
|
|
PlaybackSource::PodcastEpisode(episode) => Some(PlaybackTrack::podcast_episode(*episode)),
|
|
PlaybackSource::Private => Some(PlaybackTrack::private_placeholder()),
|
|
PlaybackSource::Music => None,
|
|
}
|
|
}
|
|
|
|
/// Whether a browser item is a podcast episode or a Jam placeholder.
|
|
pub(crate) fn browser_track_requires_podcast_support(track: &Value) -> bool {
|
|
wire_track_from_browser_json(track).is_some_and(|track| track.requires_podcast_support())
|
|
}
|
|
|
|
/// Wire-shaped view of browser tracks for the shared gating and Jam helpers.
|
|
///
|
|
/// External items are their verbatim DTOs. Library tracks become minimal
|
|
/// music items: the helpers only look at item sources and positions, so
|
|
/// this conversion needs no database lookups.
|
|
pub(crate) fn shadow_wire_state(tracks: &[Value], index: usize) -> PlaybackStateWire {
|
|
PlaybackStateWire {
|
|
queue: tracks
|
|
.iter()
|
|
.map(|track| wire_track_from_browser_json(track).unwrap_or_else(|| music_stub(track)))
|
|
.collect(),
|
|
queue_pos: index,
|
|
playing: false,
|
|
paused: true,
|
|
idle_since_ms: None,
|
|
position_secs: 0.0,
|
|
volume: 0,
|
|
shuffle: false,
|
|
repeat: Default::default(),
|
|
playback_rate: None,
|
|
}
|
|
}
|
|
|
|
fn music_stub(track: &Value) -> PlaybackTrack {
|
|
PlaybackTrack {
|
|
id: track.get("id").and_then(Value::as_i64).unwrap_or(0),
|
|
title: String::new(),
|
|
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,
|
|
source: None,
|
|
}
|
|
}
|
|
|
|
/// Browser tracks as shown to Jam participants.
|
|
///
|
|
/// Uses [`redact_for_jam`]: every podcast episode (and existing placeholder)
|
|
/// becomes the opaque private placeholder; music, order and position stay.
|
|
pub(crate) fn redact_tracks_for_jam(tracks: &[Value]) -> Vec<Value> {
|
|
let redacted = redact_for_jam(shadow_wire_state(tracks, 0));
|
|
tracks
|
|
.iter()
|
|
.zip(redacted.queue.iter())
|
|
.enumerate()
|
|
.map(|(index, (original, redacted))| {
|
|
if redacted.is_private_placeholder() {
|
|
external_track_json(redacted, index, None)
|
|
} else {
|
|
original.clone()
|
|
}
|
|
})
|
|
.collect()
|
|
}
|
|
|
|
/// Maps the private placeholders of a Jam participant's full queue back to
|
|
/// the host's items ([`restore_jam_private_items`]).
|
|
///
|
|
/// Returns `None` when the participant queue contains real podcast episodes
|
|
/// or drops, duplicates or injects private items; the command is then
|
|
/// rejected.
|
|
pub(crate) fn restore_jam_tracks(host: &[Value], participant: &[Value]) -> Option<Vec<Value>> {
|
|
let host_state = shadow_wire_state(host, 0);
|
|
let restored = restore_jam_private_items(&host_state, shadow_wire_state(participant, 0))?;
|
|
let mut host_private = host
|
|
.iter()
|
|
.zip(host_state.queue.iter())
|
|
.filter(|(_, wire)| wire.requires_podcast_support())
|
|
.map(|(json, _)| json);
|
|
let participant_state = shadow_wire_state(participant, 0);
|
|
let mut out = Vec::with_capacity(participant.len());
|
|
for ((json, before), after) in participant
|
|
.iter()
|
|
.zip(participant_state.queue.iter())
|
|
.zip(restored.queue.iter())
|
|
{
|
|
if before.is_private_placeholder() {
|
|
out.push(host_private.next()?.clone());
|
|
} else {
|
|
debug_assert_eq!(before, after);
|
|
out.push(json.clone());
|
|
}
|
|
}
|
|
Some(out)
|
|
}
|
|
|
|
/// Whether tracks sent by a Jam participant may enter the host queue at all
|
|
/// ([`jam_command_allowed`]): participants cannot add podcast episodes.
|
|
pub(crate) fn jam_tracks_allowed(tracks: &[Value]) -> bool {
|
|
jam_command_allowed(&PlaybackCommand::SetState {
|
|
state: shadow_wire_state(tracks, 0),
|
|
seek: false,
|
|
})
|
|
}
|
|
|
|
/// Typed playback queue persisted next to the legacy `queue_json`.
|
|
///
|
|
/// `queue_json` (a list of library track ids) is still written for rollback
|
|
/// to older releases. `legacy_queue`, `legacy_current_track_id` and
|
|
/// `legacy_queue_position` record the legacy columns written alongside this
|
|
/// value: when they no longer match the row (an older release or a
|
|
/// legacy-only writer changed the queue or moved to another track since),
|
|
/// readers ignore the typed value and fall back to the legacy columns.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
pub(crate) struct StoredQueue {
|
|
/// Shape version, [`STORED_QUEUE_VERSION`].
|
|
pub(crate) version: u16,
|
|
/// Index of the current item in `items`.
|
|
#[serde(default)]
|
|
pub(crate) position: usize,
|
|
/// Queue items in order.
|
|
#[serde(default)]
|
|
pub(crate) items: Vec<StoredQueueItem>,
|
|
/// `queue_json` ids written together with this value.
|
|
#[serde(default)]
|
|
pub(crate) legacy_queue: Vec<i64>,
|
|
/// `current_track_id` written together with this value.
|
|
#[serde(default)]
|
|
pub(crate) legacy_current_track_id: Option<i64>,
|
|
/// `queue_position` written together with this value (`None`: unknown,
|
|
/// the value is not used).
|
|
#[serde(default)]
|
|
pub(crate) legacy_queue_position: Option<i32>,
|
|
}
|
|
|
|
/// Legacy queue columns of a `furumusic__playback_state` row.
|
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
|
pub(crate) struct LegacyColumns {
|
|
/// `queue_json`: library track ids.
|
|
pub(crate) queue: Vec<i64>,
|
|
/// `current_track_id`.
|
|
pub(crate) current_track_id: Option<i64>,
|
|
/// `queue_position`.
|
|
pub(crate) queue_position: i32,
|
|
}
|
|
|
|
/// One persisted queue item.
|
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
#[serde(tag = "kind", rename_all = "snake_case")]
|
|
pub(crate) enum StoredQueueItem {
|
|
/// Library track of this server.
|
|
Library {
|
|
/// Local track id.
|
|
track_id: i64,
|
|
},
|
|
/// Any other item, kept verbatim with its explicit `source`.
|
|
External {
|
|
/// Device-sync queue item.
|
|
track: Box<PlaybackTrack>,
|
|
},
|
|
}
|
|
|
|
impl StoredQueue {
|
|
/// Builds the persisted value; `None` when the queue exceeds the bound.
|
|
///
|
|
/// Jam private placeholders are dropped: they stand for the Jam host's
|
|
/// items, never for items of this user's own queue.
|
|
pub(crate) fn new(
|
|
items: Vec<StoredQueueItem>,
|
|
position: usize,
|
|
legacy: LegacyColumns,
|
|
) -> Option<Self> {
|
|
if items.len() > MAX_STORED_QUEUE_ITEMS {
|
|
return None;
|
|
}
|
|
let mut stored = Self {
|
|
version: STORED_QUEUE_VERSION,
|
|
position,
|
|
items,
|
|
legacy_queue: Vec::new(),
|
|
legacy_current_track_id: None,
|
|
legacy_queue_position: None,
|
|
};
|
|
stored.retain_items(|item| match item {
|
|
StoredQueueItem::Library { .. } => true,
|
|
StoredQueueItem::External { track } => !track.is_private_placeholder(),
|
|
});
|
|
stored.set_legacy(legacy);
|
|
Some(stored)
|
|
}
|
|
|
|
/// Reads the typed column, preferring it over the legacy columns only
|
|
/// when it has a known version and was written together with exactly
|
|
/// these legacy values.
|
|
pub(crate) fn from_columns(typed: Option<&Value>, legacy: &LegacyColumns) -> Option<Self> {
|
|
let stored = serde_json::from_value::<Self>(typed?.clone()).ok()?;
|
|
(stored.version == STORED_QUEUE_VERSION
|
|
&& stored.legacy_queue == legacy.queue
|
|
&& stored.legacy_current_track_id == legacy.current_track_id
|
|
&& stored.legacy_queue_position == Some(legacy.queue_position)
|
|
&& stored.items.len() <= MAX_STORED_QUEUE_ITEMS)
|
|
.then_some(stored)
|
|
}
|
|
|
|
/// Removes library tracks rejected by `keep` and records the new legacy
|
|
/// columns. The current position follows its item, or the item after it
|
|
/// when the current item was removed.
|
|
pub(crate) fn retain_library(&mut self, keep: impl Fn(i64) -> bool, legacy: LegacyColumns) {
|
|
self.retain_items(|item| match item {
|
|
StoredQueueItem::Library { track_id } => keep(*track_id),
|
|
StoredQueueItem::External { .. } => true,
|
|
});
|
|
self.set_legacy(legacy);
|
|
}
|
|
|
|
fn retain_items(&mut self, keep: impl Fn(&StoredQueueItem) -> bool) {
|
|
let original_position = self.position;
|
|
let mut position = self.position;
|
|
let mut index = 0;
|
|
self.items.retain(|item| {
|
|
let retained = keep(item);
|
|
if !retained && index < original_position {
|
|
position = position.saturating_sub(1);
|
|
}
|
|
index += 1;
|
|
retained
|
|
});
|
|
self.position = position.min(self.items.len().saturating_sub(1));
|
|
}
|
|
|
|
fn set_legacy(&mut self, legacy: LegacyColumns) {
|
|
self.legacy_queue = legacy.queue;
|
|
self.legacy_current_track_id = legacy.current_track_id;
|
|
self.legacy_queue_position = Some(legacy.queue_position);
|
|
}
|
|
}
|
|
|
|
/// A valid podcast episode reference for tests.
|
|
#[cfg(test)]
|
|
pub(crate) fn test_episode() -> music_dht::podcast::PodcastEpisodeRef {
|
|
use music_dht::podcast::{EpisodeId, FeedUrl, PodcastEpisodeRef, PodcastId};
|
|
let feed_url = FeedUrl::parse("https://podcasts.example/feed.xml?token=Ab").unwrap();
|
|
let podcast_id = PodcastId::from_feed_url(&feed_url);
|
|
let episode_id = EpisodeId::from_guid(&podcast_id, "episode-42").unwrap();
|
|
PodcastEpisodeRef {
|
|
podcast_id,
|
|
episode_id,
|
|
feed_url,
|
|
podcast_title: "Example Cast".into(),
|
|
episode_title: "Episode 42".into(),
|
|
audio_url: "https://cdn.example/ep42.mp3".into(),
|
|
mime: Some("audio/mpeg".into()),
|
|
duration_ms: Some(1_800_000),
|
|
published_at_ms: Some(1_700_000_000_000),
|
|
season: Some(2),
|
|
episode_number: Some(42),
|
|
image_url: None,
|
|
progress_generation: Some(7),
|
|
}
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use music_dht::podcast::EpisodeId;
|
|
|
|
fn episode() -> music_dht::podcast::PodcastEpisodeRef {
|
|
test_episode()
|
|
}
|
|
|
|
fn library(id: i64) -> Value {
|
|
serde_json::json!({"id": id, "title": format!("Track {id}"), "stream_url": format!("/api/player/stream/{id}")})
|
|
}
|
|
|
|
#[test]
|
|
fn podcast_item_round_trips_through_browser_json() {
|
|
let mut wire = PlaybackTrack::podcast_episode(episode());
|
|
wire.play_count = 3;
|
|
let json = external_track_json(&wire, 4, None);
|
|
// Playable on the web player (the source is resolved on play).
|
|
assert_eq!(json["unavailable"], false);
|
|
assert!(json.get("unavailable_reason").is_none());
|
|
assert_eq!(json["stream_url"], "");
|
|
assert_eq!(
|
|
json["cover_url"],
|
|
Value::Null,
|
|
"the test episode has no artwork"
|
|
);
|
|
assert_eq!(json["title"], "Episode 42");
|
|
assert_eq!(json[SOURCE_KEY]["kind"], "podcast_episode");
|
|
assert!(json["id"].as_i64().unwrap() < 0);
|
|
// The browser stores and echoes the object; the item is unchanged.
|
|
let echoed: Value = serde_json::from_str(&json.to_string()).unwrap();
|
|
assert_eq!(wire_track_from_browser_json(&echoed), Some(wire));
|
|
}
|
|
|
|
#[test]
|
|
fn private_and_unresolved_music_keep_their_wire_item() {
|
|
let private = PlaybackTrack::private_placeholder();
|
|
let json = external_track_json(&private, 0, None);
|
|
assert_eq!(json["title"], PRIVATE_ITEM_TITLE);
|
|
assert_eq!(json[SOURCE_KEY]["kind"], "private");
|
|
assert_eq!(wire_track_from_browser_json(&json), Some(private));
|
|
|
|
let mut music = PlaybackTrack::private_placeholder();
|
|
music.source = None;
|
|
music.title = "Remote song".into();
|
|
music.content_id = Some(format!("b3:{}", "a".repeat(64)));
|
|
let json = external_track_json(&music, 1, music.content_id.as_deref());
|
|
assert!(json.get(SOURCE_KEY).is_none());
|
|
assert_eq!(json["unavailable_reason"], FED_UNAVAILABLE_REASON);
|
|
assert_eq!(wire_track_from_browser_json(&json), Some(music));
|
|
}
|
|
|
|
#[test]
|
|
fn library_tracks_are_not_external() {
|
|
assert_eq!(wire_track_from_browser_json(&library(5)), None);
|
|
let mut music_source = library(6);
|
|
music_source[SOURCE_KEY] = serde_json::json!({"kind": "music"});
|
|
assert_eq!(wire_track_from_browser_json(&music_source), None);
|
|
}
|
|
|
|
#[test]
|
|
fn source_only_items_use_shared_constructors() {
|
|
let json = serde_json::json!({
|
|
"id": -1,
|
|
SOURCE_KEY: serde_json::to_value(PlaybackSource::PodcastEpisode(Box::new(episode()))).unwrap(),
|
|
});
|
|
assert_eq!(
|
|
wire_track_from_browser_json(&json),
|
|
Some(PlaybackTrack::podcast_episode(episode()))
|
|
);
|
|
// A malformed verbatim item falls back to the explicit source.
|
|
let mut tampered = json.clone();
|
|
tampered[WIRE_TRACK_KEY] = serde_json::json!({"id": "x"});
|
|
assert_eq!(
|
|
wire_track_from_browser_json(&tampered),
|
|
Some(PlaybackTrack::podcast_episode(episode()))
|
|
);
|
|
}
|
|
|
|
#[test]
|
|
fn jam_redaction_hides_episodes_and_restores_them_in_order() {
|
|
let first = external_track_json(&PlaybackTrack::podcast_episode(episode()), 1, None);
|
|
let mut other = episode();
|
|
other.episode_title = "Episode 43".into();
|
|
other.episode_id = EpisodeId::from_guid(&other.podcast_id, "episode-43").unwrap();
|
|
let second = external_track_json(&PlaybackTrack::podcast_episode(other), 3, None);
|
|
let host = vec![library(1), first.clone(), library(2), second.clone()];
|
|
|
|
let redacted = redact_tracks_for_jam(&host);
|
|
assert_eq!(redacted[0], host[0]);
|
|
assert_eq!(redacted[1]["title"], PRIVATE_ITEM_TITLE);
|
|
let leaked = serde_json::to_string(&redacted).unwrap();
|
|
assert!(!leaked.contains("Episode 4") && !leaked.contains("podcasts.example"));
|
|
assert!(!leaked.contains("cdn.example") && !leaked.contains("Example Cast"));
|
|
|
|
// The participant reorders music and moves a placeholder.
|
|
let participant = vec![
|
|
redacted[3].clone(),
|
|
library(2),
|
|
redacted[1].clone(),
|
|
library(1),
|
|
];
|
|
let restored = restore_jam_tracks(&host, &participant).unwrap();
|
|
assert_eq!(
|
|
restored,
|
|
vec![first.clone(), library(2), second, library(1)]
|
|
);
|
|
|
|
// Dropping, duplicating or injecting private items is rejected.
|
|
assert!(restore_jam_tracks(&host, &[library(1), redacted[1].clone()]).is_none());
|
|
assert!(restore_jam_tracks(&host, &[first.clone(), redacted[1].clone()]).is_none());
|
|
assert!(!jam_tracks_allowed(std::slice::from_ref(&first)));
|
|
assert!(jam_tracks_allowed(&[library(9)]));
|
|
}
|
|
|
|
fn legacy(queue: &[i64], current_track_id: Option<i64>, queue_position: i32) -> LegacyColumns {
|
|
LegacyColumns {
|
|
queue: queue.to_vec(),
|
|
current_track_id,
|
|
queue_position,
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn stored_queue_prefers_typed_value_only_while_legacy_ids_match() {
|
|
let items = vec![
|
|
StoredQueueItem::Library { track_id: 3 },
|
|
StoredQueueItem::External {
|
|
track: Box::new(PlaybackTrack::podcast_episode(episode())),
|
|
},
|
|
StoredQueueItem::Library { track_id: 4 },
|
|
];
|
|
// The episode is current: the browser wrote its placeholder id.
|
|
let written = legacy(&[3, -11, 4], Some(-11), 1);
|
|
let stored = StoredQueue::new(items, 1, written.clone()).unwrap();
|
|
let value = serde_json::to_value(&stored).unwrap();
|
|
assert_eq!(value["version"], 1);
|
|
assert_eq!(value["items"][1]["kind"], "external");
|
|
assert_eq!(
|
|
value["items"][1]["track"]["source"]["kind"],
|
|
"podcast_episode"
|
|
);
|
|
assert_eq!(
|
|
StoredQueue::from_columns(Some(&value), &written),
|
|
Some(stored.clone())
|
|
);
|
|
// A rollback release rewrote queue_json: fall back to it.
|
|
assert_eq!(
|
|
StoredQueue::from_columns(Some(&value), &legacy(&[3, 4], Some(4), 1)),
|
|
None
|
|
);
|
|
// A rollback release kept the ids but moved to another track (Next
|
|
// or a click): the typed position is stale, fall back as well.
|
|
assert_eq!(
|
|
StoredQueue::from_columns(Some(&value), &legacy(&[3, -11, 4], Some(4), 2)),
|
|
None
|
|
);
|
|
assert_eq!(
|
|
StoredQueue::from_columns(Some(&value), &legacy(&[3, -11, 4], Some(-11), 0)),
|
|
None
|
|
);
|
|
// Values without the recorded current item are not trusted.
|
|
let mut unknown = value.clone();
|
|
unknown
|
|
.as_object_mut()
|
|
.unwrap()
|
|
.remove("legacy_queue_position");
|
|
assert_eq!(StoredQueue::from_columns(Some(&unknown), &written), None);
|
|
let mut future = value.clone();
|
|
future["version"] = serde_json::json!(2);
|
|
assert_eq!(StoredQueue::from_columns(Some(&future), &written), None);
|
|
assert_eq!(StoredQueue::from_columns(None, &written), None);
|
|
}
|
|
|
|
#[test]
|
|
fn stored_queue_never_keeps_jam_placeholders() {
|
|
let items = vec![
|
|
StoredQueueItem::Library { track_id: 3 },
|
|
StoredQueueItem::External {
|
|
track: Box::new(PlaybackTrack::private_placeholder()),
|
|
},
|
|
StoredQueueItem::External {
|
|
track: Box::new(PlaybackTrack::podcast_episode(episode())),
|
|
},
|
|
StoredQueueItem::Library { track_id: 4 },
|
|
];
|
|
let stored = StoredQueue::new(items.clone(), 3, legacy(&[3, 4], Some(4), 1)).unwrap();
|
|
assert_eq!(
|
|
stored.items,
|
|
vec![items[0].clone(), items[2].clone(), items[3].clone()]
|
|
);
|
|
assert_eq!(stored.position, 2);
|
|
// A current placeholder hands the position to the next item.
|
|
let stored = StoredQueue::new(items.clone(), 1, legacy(&[3, 4], None, 0)).unwrap();
|
|
assert_eq!(stored.position, 1);
|
|
assert_eq!(stored.items[1], items[2]);
|
|
}
|
|
|
|
#[test]
|
|
fn stored_queue_cleanup_keeps_external_items_and_position() {
|
|
let items = vec![
|
|
StoredQueueItem::Library { track_id: 3 },
|
|
StoredQueueItem::External {
|
|
track: Box::new(PlaybackTrack::podcast_episode(episode())),
|
|
},
|
|
StoredQueueItem::Library { track_id: 4 },
|
|
];
|
|
let mut stored = StoredQueue::new(items.clone(), 1, legacy(&[3, 4], None, 0)).unwrap();
|
|
stored.retain_library(|id| id != 3, legacy(&[4], None, 0));
|
|
assert_eq!(stored.items, items[1..].to_vec());
|
|
assert_eq!(stored.position, 0);
|
|
assert_eq!(stored.legacy_queue, vec![4]);
|
|
// The cleanup's new legacy columns are what readers compare with.
|
|
let value = serde_json::to_value(&stored).unwrap();
|
|
assert_eq!(
|
|
StoredQueue::from_columns(Some(&value), &legacy(&[4], None, 0)),
|
|
Some(stored)
|
|
);
|
|
|
|
let mut current_removed =
|
|
StoredQueue::new(items.clone(), 2, legacy(&[3, 4], Some(4), 1)).unwrap();
|
|
current_removed.retain_library(|id| id != 4, legacy(&[3], None, 0));
|
|
assert_eq!(current_removed.position, 1);
|
|
assert!(
|
|
StoredQueue::new(
|
|
vec![items[0].clone(); MAX_STORED_QUEUE_ITEMS + 1],
|
|
0,
|
|
LegacyColumns::default()
|
|
)
|
|
.is_none()
|
|
);
|
|
}
|
|
}
|