feat(opendeck): preview and reroll radio from liked tracks
This commit is contained in:
1 parent
cc1176a160
commit
c911cb63e3
21 files changed
+1423
-70
No files matched your search
+34
-3
@@ -73,6 +73,7 @@ pub(crate) fn published(state: &AppState, revision: u64) -> crate::control::Publ
|
||||
snapshot: Snapshot {
|
||||
api_version: API_VERSION,
|
||||
spectrum_supported: true,
|
||||
liked_radio_supported: true,
|
||||
revision,
|
||||
updated_at_ms: now.max(0) as u64,
|
||||
role: match state.device_playback.role {
|
||||
@@ -136,6 +137,13 @@ pub(super) enum Intent {
|
||||
Action(Action),
|
||||
Transfer(Device),
|
||||
Radio,
|
||||
PickLikedRadioSeed {
|
||||
exclude: Option<String>,
|
||||
replace_request_id: Option<String>,
|
||||
},
|
||||
StartLikedRadio {
|
||||
seed_key: String,
|
||||
},
|
||||
SetLiked {
|
||||
track: Box<crate::federation::FedTrack>,
|
||||
liked: bool,
|
||||
@@ -145,7 +153,10 @@ pub(super) enum Intent {
|
||||
pub(super) fn intent(state: &AppState, command: Command) -> Result<Intent, String> {
|
||||
if !matches!(
|
||||
command,
|
||||
Command::Transfer { .. } | Command::Artwork { .. } | Command::SetLiked { .. }
|
||||
Command::Transfer { .. }
|
||||
| Command::Artwork { .. }
|
||||
| Command::SetLiked { .. }
|
||||
| Command::PickLikedRadioSeed { .. }
|
||||
) {
|
||||
super::remote_playback::available(state)?;
|
||||
}
|
||||
@@ -163,6 +174,14 @@ pub(super) fn intent(state: &AppState, command: Command) -> Result<Intent, Strin
|
||||
Command::ToggleShuffle => Intent::Action(Action::ToggleShuffle),
|
||||
Command::CycleRepeat => Intent::Action(Action::CycleRepeat),
|
||||
Command::StartRadio => Intent::Radio,
|
||||
Command::PickLikedRadioSeed {
|
||||
exclude,
|
||||
replace_request_id,
|
||||
} => Intent::PickLikedRadioSeed {
|
||||
exclude,
|
||||
replace_request_id,
|
||||
},
|
||||
Command::StartLikedRadio { seed_key } => Intent::StartLikedRadio { seed_key },
|
||||
Command::SetLiked { track_key, liked } => Intent::SetLiked {
|
||||
track: Box::new(super::likes::target(state, &track_key)?),
|
||||
liked,
|
||||
@@ -222,7 +241,17 @@ pub(super) fn dispatch(
|
||||
super::likes::set(runtime, *track, liked, request.reply);
|
||||
return;
|
||||
}
|
||||
Ok(Intent::Radio) => super::radio::start(state, runtime),
|
||||
Ok(Intent::Radio) => super::radio::start(state, runtime, None, request.id),
|
||||
Ok(Intent::PickLikedRadioSeed {
|
||||
exclude,
|
||||
replace_request_id,
|
||||
}) => {
|
||||
super::radio::pick_liked(state, runtime, exclude, replace_request_id, request.reply);
|
||||
return;
|
||||
}
|
||||
Ok(Intent::StartLikedRadio { seed_key }) => {
|
||||
super::radio::start(state, runtime, Some(seed_key), request.id)
|
||||
}
|
||||
Ok(Intent::Action(action)) => {
|
||||
// Same state transitions, remote targeting and podcast checks as media keys.
|
||||
let id = state.device_playback.control.status.id;
|
||||
@@ -262,5 +291,7 @@ pub(super) fn dispatch(
|
||||
}
|
||||
}
|
||||
};
|
||||
let _ = request.reply.send(result);
|
||||
let _ = request
|
||||
.reply
|
||||
.send(result.map(|()| crate::control::Reply::Done));
|
||||
}
|
||||
+3
-3
@@ -2,7 +2,7 @@
|
||||
use std::collections::HashSet;
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
use tokio::sync::{mpsc, oneshot};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::event::AppEvent;
|
||||
use super::state::{self, AppState};
|
||||
@@ -93,7 +93,7 @@ pub(super) fn set(
|
||||
runtime: &Runtime,
|
||||
track: FedTrack,
|
||||
liked: bool,
|
||||
reply: oneshot::Sender<Result<(), String>>,
|
||||
reply: crate::control::ReplySender,
|
||||
) {
|
||||
in_background(runtime, move |library, devices, tx| {
|
||||
let write = set_in_library(library, devices, &track, liked, tx).map_err(err_string);
|
||||
@@ -106,7 +106,7 @@ pub(super) fn set(
|
||||
Err(error) => Err(error.clone()),
|
||||
};
|
||||
let _ = tx.send(AppEvent::LikesLoaded(ids));
|
||||
let _ = reply.send(write.and(saved));
|
||||
let _ = reply.send(write.and(saved).map(|()| crate::control::Reply::Done));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+226
-24
@@ -3,17 +3,21 @@
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use furumi_control_protocol::{Radio as Status, RadioState};
|
||||
use anyhow::Context as _;
|
||||
use furumi_control_protocol::{LikedRadioSeed, Radio as Status, RadioState};
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
use super::event::AppEvent;
|
||||
use super::state::{AppState, SimilaritySearchHit};
|
||||
use super::{Runtime, update};
|
||||
use crate::library::models::TrackItem;
|
||||
use crate::library::{LIKES_PLAYLIST_ID, Library, models::TrackItem};
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct Radio {
|
||||
pub status: Status,
|
||||
seed: String,
|
||||
from_likes: bool,
|
||||
original_track: Option<String>,
|
||||
owner: Option<String>,
|
||||
queue: Vec<String>,
|
||||
expected: Option<String>,
|
||||
@@ -40,28 +44,45 @@ fn busy(state: &AppState) -> bool {
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn begin(state: &mut AppState) -> Result<TrackItem, String> {
|
||||
pub(super) enum Seed {
|
||||
Current(Box<TrackItem>),
|
||||
Liked(String),
|
||||
}
|
||||
|
||||
pub(super) fn begin(
|
||||
state: &mut AppState,
|
||||
liked_key: Option<String>,
|
||||
request_id: String,
|
||||
) -> Result<Seed, String> {
|
||||
if busy(state) {
|
||||
return Err("Radio is already being prepared".into());
|
||||
}
|
||||
if !state.similarity.settings.enabled {
|
||||
return Err("Enable similarity search in Furumi Settings first".into());
|
||||
}
|
||||
let seed = state
|
||||
.player
|
||||
.current
|
||||
.clone()
|
||||
.ok_or("Play a music track before starting radio")?;
|
||||
if seed.is_podcast() {
|
||||
return Err("Similarity radio is available for music tracks only".into());
|
||||
}
|
||||
let (seed_key, seed) = if let Some(key) = liked_key {
|
||||
(key.clone(), Seed::Liked(key))
|
||||
} else {
|
||||
let track = state
|
||||
.player
|
||||
.current
|
||||
.as_ref()
|
||||
.ok_or("Play a music track before starting radio")?;
|
||||
if track.is_podcast() {
|
||||
return Err("Similarity radio is available for music tracks only".into());
|
||||
}
|
||||
(identity(track), Seed::Current(Box::new(track.clone())))
|
||||
};
|
||||
state.radio = Radio {
|
||||
status: Status {
|
||||
id: state.radio.status.id.wrapping_add(1),
|
||||
state: RadioState::Searching,
|
||||
error: None,
|
||||
request_id: Some(request_id),
|
||||
},
|
||||
seed: identity(&seed),
|
||||
seed: seed_key,
|
||||
from_likes: matches!(seed, Seed::Liked(_)),
|
||||
original_track: state.player.current.as_ref().map(identity),
|
||||
owner: state.device_playback.active_device_id.clone(),
|
||||
queue: queue_identity(state),
|
||||
expected: None,
|
||||
@@ -72,8 +93,114 @@ pub(super) fn begin(state: &mut AppState) -> Result<TrackItem, String> {
|
||||
Ok(seed)
|
||||
}
|
||||
|
||||
pub(super) fn start(state: &mut AppState, runtime: &mut Runtime) -> Result<(), String> {
|
||||
let seed = begin(state)?;
|
||||
// A controller's numeric row IDs are not the output's IDs.
|
||||
fn local_id(library: &Library, track: &TrackItem) -> anyhow::Result<Option<i64>> {
|
||||
if track.id >= 0 && track.fed.is_none() && !track.is_podcast() {
|
||||
return Ok(Some(track.id));
|
||||
}
|
||||
match super::state::track_content_id(track) {
|
||||
Some(content_id) => library.track_id_by_content_id(&content_id),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn choose_liked(
|
||||
library: &Library,
|
||||
profile: Option<&str>,
|
||||
exclude: Option<&str>,
|
||||
) -> anyhow::Result<LikedRadioSeed> {
|
||||
let mut tracks = library.playlist(LIKES_PLAYLIST_ID)?.tracks;
|
||||
anyhow::ensure!(!tracks.is_empty(), "Like a track first");
|
||||
let profile = profile.context("No similarity index is ready yet")?;
|
||||
tracks.shuffle(&mut rand::rng());
|
||||
// A shuffled traversal gives every eligible choice a chance. Keep the
|
||||
// previous one only as a fallback for libraries with one eligible like.
|
||||
let mut previous = None;
|
||||
for track in tracks {
|
||||
let Some(id) = local_id(library, &track)? else {
|
||||
continue;
|
||||
};
|
||||
if library.similarity_embedding(id, profile)?.is_none() {
|
||||
continue;
|
||||
}
|
||||
let seed = LikedRadioSeed {
|
||||
key: identity(&track),
|
||||
artist: track.artist_line(),
|
||||
title: track.title,
|
||||
};
|
||||
if exclude != Some(seed.key.as_str()) {
|
||||
return Ok(seed);
|
||||
}
|
||||
previous = Some(seed);
|
||||
}
|
||||
previous.context("No liked tracks in the local similarity index")
|
||||
}
|
||||
|
||||
// Rerolls may supersede only their own unfinished liked-radio search. Once
|
||||
// the queue has committed, ordinary playback owns it.
|
||||
pub(super) fn supersede(state: &mut AppState, request_id: &str) -> bool {
|
||||
if state.radio.from_likes
|
||||
&& state.radio.status.state == RadioState::Searching
|
||||
&& state.radio.status.request_id.as_deref() == Some(request_id)
|
||||
{
|
||||
state.radio.status.state = RadioState::Idle;
|
||||
state.radio.deadline = None;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn pick_liked(
|
||||
state: &mut AppState,
|
||||
runtime: &mut Runtime,
|
||||
exclude: Option<String>,
|
||||
replace_request_id: Option<String>,
|
||||
reply: crate::control::ReplySender,
|
||||
) {
|
||||
if replace_request_id
|
||||
.as_deref()
|
||||
.is_some_and(|id| supersede(state, id))
|
||||
&& let Some(previous) = runtime.radio_task.take()
|
||||
{
|
||||
previous.abort();
|
||||
}
|
||||
if busy(state) {
|
||||
let _ = reply.send(Err("Radio is already being prepared".into()));
|
||||
return;
|
||||
}
|
||||
if !state.similarity.settings.enabled {
|
||||
let _ = reply.send(Err(
|
||||
"Enable similarity search in Furumi Settings first".into()
|
||||
));
|
||||
return;
|
||||
}
|
||||
let library = Arc::clone(&runtime.library);
|
||||
let profile = runtime.similarity.status().active_profile;
|
||||
tokio::task::spawn_blocking(move || {
|
||||
let result = choose_liked(&library, profile.as_deref(), exclude.as_deref())
|
||||
.map(crate::control::Reply::LikedRadioSeed)
|
||||
.map_err(super::err_string);
|
||||
let _ = reply.send(result);
|
||||
});
|
||||
}
|
||||
|
||||
fn liked_track_id(library: &Library, key: &str) -> anyhow::Result<i64> {
|
||||
let track = library
|
||||
.playlist(LIKES_PLAYLIST_ID)?
|
||||
.tracks
|
||||
.into_iter()
|
||||
.find(|track| identity(track) == key)
|
||||
.context("This track is no longer liked")?;
|
||||
local_id(library, &track)?.context("This liked track is no longer available locally")
|
||||
}
|
||||
|
||||
pub(super) fn start(
|
||||
state: &mut AppState,
|
||||
runtime: &mut Runtime,
|
||||
liked_key: Option<String>,
|
||||
request_id: String,
|
||||
) -> Result<(), String> {
|
||||
let seed = begin(state, liked_key, request_id)?;
|
||||
if let Some(previous) = runtime.radio_task.take() {
|
||||
previous.abort();
|
||||
}
|
||||
@@ -88,14 +215,17 @@ pub(super) fn start(state: &mut AppState, runtime: &mut Runtime) -> Result<(), S
|
||||
runtime.radio_task = Some(tokio::spawn(async move {
|
||||
let work = async move {
|
||||
let (local, query) = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
|
||||
// A controller's numeric row IDs are not the output's IDs.
|
||||
let local_seed = if seed.id >= 0 && seed.fed.is_none() { seed.id } else {
|
||||
let content_id = seed.content_id.as_deref().ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?;
|
||||
library.track_by_content_id(content_id)?.ok_or_else(|| anyhow::anyhow!("Import and index this track locally before starting similarity radio"))?.id
|
||||
let local_seed = match seed {
|
||||
Seed::Current(track) => local_id(&library, &track)?.context(
|
||||
"Import and index this track locally before starting similarity radio",
|
||||
)?,
|
||||
Seed::Liked(key) => liked_track_id(&library, &key)?,
|
||||
};
|
||||
similarity.search_track(local_seed, 49)
|
||||
}).await.map_err(|error| format!("Radio search worker failed: {error}"))?
|
||||
.map_err(|error| format!("Radio search failed: {error:#}"))?;
|
||||
})
|
||||
.await
|
||||
.map_err(|error| format!("Radio search worker failed: {error}"))?
|
||||
.map_err(|error| format!("Radio search failed: {error:#}"))?;
|
||||
let mut hits: Vec<_> = local
|
||||
.into_iter()
|
||||
.map(|hit| SimilaritySearchHit::Local {
|
||||
@@ -149,7 +279,7 @@ pub(super) fn prepare(
|
||||
if id != state.radio.status.id || state.radio.status.state != RadioState::Searching {
|
||||
return false;
|
||||
}
|
||||
if !seed_current(state) {
|
||||
if !playback_unchanged(state) {
|
||||
fail(state, "Playback changed while radio was being prepared");
|
||||
return false;
|
||||
}
|
||||
@@ -206,8 +336,8 @@ pub(super) fn ready(
|
||||
}
|
||||
}
|
||||
|
||||
fn seed_current(state: &AppState) -> bool {
|
||||
state.player.current.as_ref().map(identity).as_ref() == Some(&state.radio.seed)
|
||||
fn playback_unchanged(state: &AppState) -> bool {
|
||||
state.player.current.as_ref().map(identity) == state.radio.original_track
|
||||
&& state.device_playback.active_device_id == state.radio.owner
|
||||
&& queue_identity(state) == state.radio.queue
|
||||
}
|
||||
@@ -264,7 +394,7 @@ pub(super) fn tick(state: &mut AppState, runtime: &mut Runtime) {
|
||||
if !busy(state) {
|
||||
return;
|
||||
}
|
||||
if state.radio.status.state == RadioState::Searching && !seed_current(state) {
|
||||
if state.radio.status.state == RadioState::Searching && !playback_unchanged(state) {
|
||||
fail(state, "Playback changed while radio was being prepared");
|
||||
} else if state.device_playback.active_device_id != state.radio.owner {
|
||||
fail(
|
||||
@@ -284,3 +414,75 @@ pub(super) fn tick(state: &mut AppState, runtime: &mut Runtime) {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn picks_only_indexed_likes_and_rechecks_the_exact_choice_on_start() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("library.sqlite3");
|
||||
let library = Library::open(&path).unwrap();
|
||||
assert!(choose_liked(&library, None, None).is_err());
|
||||
let db = rusqlite::Connection::open(&path).unwrap();
|
||||
db.execute("INSERT INTO releases (id, title) VALUES (1, 'Album')", [])
|
||||
.unwrap();
|
||||
for id in 1..=4 {
|
||||
db.execute("INSERT INTO tracks (id, title, release_id, file_path, content_id) VALUES (?1, ?2, 1, ?2, ?3)",
|
||||
rusqlite::params![id, format!("Song {id}"), format!("b3:{id:064x}")]).unwrap();
|
||||
}
|
||||
drop(db);
|
||||
library.set_synced_like(1, true, 1).unwrap();
|
||||
library.set_synced_like(3, true, 2).unwrap(); // No embedding for this track.
|
||||
let profile = "test-profile";
|
||||
library
|
||||
.ensure_similarity_profile(profile, "model", "1", "hash", "test", 1280)
|
||||
.unwrap();
|
||||
assert!(choose_liked(&library, Some(profile), None).is_err());
|
||||
let mut vector = vec![0.0; 1280];
|
||||
vector[0] = 1.0;
|
||||
for track in library.pending_similarity_tracks(profile).unwrap() {
|
||||
if track.id != 3 {
|
||||
library
|
||||
.store_similarity_embedding(&track, profile, &vector)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
let first = choose_liked(&library, Some(profile), None).unwrap();
|
||||
assert_eq!(first.title, "Song 1");
|
||||
assert_eq!(
|
||||
choose_liked(&library, Some(profile), Some(&first.key)).unwrap(),
|
||||
first
|
||||
);
|
||||
|
||||
// A liked entry learned from another device can use a local embedding
|
||||
// by content ID even before the library has reconciled the like rows.
|
||||
let remote_like = crate::federation::FedTrack {
|
||||
item_id: "peer-track".into(),
|
||||
owner: "peer".into(),
|
||||
own: false,
|
||||
title: "Remote title".into(),
|
||||
artist_names: vec!["Artist".into()],
|
||||
featured_artist_names: vec![],
|
||||
content_id: Some(format!("b3:{:064x}", 2)),
|
||||
release_title: None,
|
||||
year: None,
|
||||
duration_seconds: None,
|
||||
track_number: None,
|
||||
disc_number: None,
|
||||
};
|
||||
library.upsert_synced_fed_like(&remote_like, 3).unwrap();
|
||||
let second = choose_liked(&library, Some(profile), Some(&first.key)).unwrap();
|
||||
assert_eq!(second.title, remote_like.title);
|
||||
assert_eq!(second.artist, "Artist");
|
||||
assert_eq!(liked_track_id(&library, &second.key).unwrap(), 2);
|
||||
assert_eq!(
|
||||
choose_liked(&library, Some(profile), Some(&second.key)).unwrap(),
|
||||
first
|
||||
);
|
||||
library.remove_fed_like_by_content_id(&second.key).unwrap();
|
||||
assert!(liked_track_id(&library, &second.key).is_err());
|
||||
assert_eq!(liked_track_id(&library, &first.key).unwrap(), 1);
|
||||
}
|
||||
}
|
||||
+80
-8
@@ -474,7 +474,7 @@ fn radio_keeps_queue_until_collection_finishes_and_waits_for_audio_start() {
|
||||
use furumi_control_protocol::RadioState;
|
||||
let mut state = radio_state();
|
||||
let before: Vec<_> = state.player.queue.iter().map(|track| track.id).collect();
|
||||
crate::app::radio::begin(&mut state).unwrap();
|
||||
crate::app::radio::begin(&mut state, None, "radio".into()).unwrap();
|
||||
let id = state.radio.status.id;
|
||||
assert_eq!(state.radio.status.state, RadioState::Searching);
|
||||
assert_eq!(
|
||||
@@ -501,19 +501,91 @@ fn radio_keeps_queue_until_collection_finishes_and_waits_for_audio_start() {
|
||||
assert_eq!(state.radio.status.state, RadioState::Playing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn liked_radio_uses_the_selected_seed_from_idle_and_waits_for_playback() {
|
||||
use crate::app::radio;
|
||||
use furumi_control_protocol::RadioState;
|
||||
let mut state = radio_state();
|
||||
state.player.current = None;
|
||||
state.player.playing = false;
|
||||
state.player.queue.clear();
|
||||
radio::begin(&mut state, test_track(3).content_id, "from-idle".into()).unwrap();
|
||||
let id = state.radio.status.id;
|
||||
assert!(state.player.current.is_none());
|
||||
assert!(state.player.queue.is_empty());
|
||||
assert_eq!(state.radio.status.request_id.as_deref(), Some("from-idle"));
|
||||
assert!(radio::prepare(
|
||||
&mut state,
|
||||
id,
|
||||
Ok(vec![radio_hit(3, 0.99), radio_hit(4, 0.85)])
|
||||
));
|
||||
assert_eq!(
|
||||
state
|
||||
.player
|
||||
.queue
|
||||
.iter()
|
||||
.map(|track| track.id)
|
||||
.collect::<Vec<_>>(),
|
||||
[4]
|
||||
);
|
||||
assert_eq!(state.radio.status.state, RadioState::Starting);
|
||||
assert!(!radio::supersede(&mut state, "from-idle"));
|
||||
radio::started(&mut state);
|
||||
assert_eq!(state.radio.status.state, RadioState::Starting);
|
||||
state.player.current = Some(test_track(4));
|
||||
state.player.playing = true;
|
||||
radio::started(&mut state);
|
||||
assert_eq!(state.radio.status.state, RadioState::Playing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reroll_only_supersedes_the_matching_liked_search_and_preserves_newer_playback() {
|
||||
use crate::app::radio;
|
||||
let mut state = radio_state();
|
||||
radio::begin(&mut state, None, "regular".into()).unwrap();
|
||||
assert!(!radio::supersede(&mut state, "regular"));
|
||||
|
||||
let mut state = radio_state();
|
||||
radio::begin(&mut state, test_track(3).content_id, "first".into()).unwrap();
|
||||
let first = state.radio.status.id;
|
||||
assert!(!radio::supersede(&mut state, "another-client"));
|
||||
assert!(radio::supersede(&mut state, "first"));
|
||||
assert!(!radio::prepare(
|
||||
&mut state,
|
||||
first,
|
||||
Ok(vec![radio_hit(4, 0.9)])
|
||||
));
|
||||
radio::begin(&mut state, test_track(6).content_id, "second".into()).unwrap();
|
||||
let second = state.radio.status.id;
|
||||
assert!(!radio::prepare(
|
||||
&mut state,
|
||||
first,
|
||||
Ok(vec![radio_hit(5, 0.9)])
|
||||
));
|
||||
assert_eq!(state.player.current.as_ref().unwrap().id, 1);
|
||||
state.player.current = Some(test_track(2));
|
||||
assert!(!radio::prepare(
|
||||
&mut state,
|
||||
second,
|
||||
Ok(vec![radio_hit(7, 0.9)])
|
||||
));
|
||||
assert_eq!(state.player.current.unwrap().id, 2);
|
||||
assert_eq!(state.player.queue.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn radio_errors_empty_matches_and_stale_results_preserve_the_existing_queue() {
|
||||
use furumi_control_protocol::RadioState;
|
||||
for result in [Err("peer error".into()), Ok(vec![])] {
|
||||
let mut state = radio_state();
|
||||
crate::app::radio::begin(&mut state).unwrap();
|
||||
crate::app::radio::begin(&mut state, None, "radio".into()).unwrap();
|
||||
let id = state.radio.status.id;
|
||||
assert!(!crate::app::radio::prepare(&mut state, id, result));
|
||||
assert_eq!(state.player.queue[0].id, 1);
|
||||
assert_eq!(state.radio.status.state, RadioState::Failed);
|
||||
}
|
||||
let mut state = radio_state();
|
||||
crate::app::radio::begin(&mut state).unwrap();
|
||||
crate::app::radio::begin(&mut state, None, "radio".into()).unwrap();
|
||||
let id = state.radio.status.id;
|
||||
assert!(!crate::app::radio::prepare(
|
||||
&mut state,
|
||||
@@ -535,14 +607,14 @@ fn radio_errors_empty_matches_and_stale_results_preserve_the_existing_queue() {
|
||||
fn radio_rechecks_owner_and_requires_music_and_enabled_similarity() {
|
||||
let mut state = radio_state();
|
||||
state.similarity.settings.enabled = false;
|
||||
assert!(crate::app::radio::begin(&mut state).is_err());
|
||||
assert!(crate::app::radio::begin(&mut state, None, "radio".into()).is_err());
|
||||
state.similarity.settings.enabled = true;
|
||||
state.player.current = Some(crate::app::podcast_fixtures::episode_track(1));
|
||||
assert!(crate::app::radio::begin(&mut state).is_err());
|
||||
assert!(crate::app::radio::begin(&mut state, None, "radio".into()).is_err());
|
||||
state.player.current = Some(test_track(1));
|
||||
crate::app::radio::begin(&mut state).unwrap();
|
||||
crate::app::radio::begin(&mut state, None, "radio".into()).unwrap();
|
||||
let id = state.radio.status.id;
|
||||
assert!(crate::app::radio::begin(&mut state).is_err());
|
||||
assert!(crate::app::radio::begin(&mut state, None, "radio".into()).is_err());
|
||||
state.device_playback.active_device_id = Some("another".into());
|
||||
assert!(!crate::app::radio::prepare(
|
||||
&mut state,
|
||||
@@ -557,7 +629,7 @@ fn radio_remote_start_requires_the_output_report_and_advancing_position() {
|
||||
use crate::devices::PlaybackTrackExt as _;
|
||||
use furumi_control_protocol::RadioState;
|
||||
let mut state = radio_state();
|
||||
crate::app::radio::begin(&mut state).unwrap();
|
||||
crate::app::radio::begin(&mut state, None, "radio".into()).unwrap();
|
||||
let id = state.radio.status.id;
|
||||
let mut snapshot = crate::devices::PlaybackSnapshot {
|
||||
coordination: None,
|
||||
|
||||
+24
-6
@@ -8,7 +8,8 @@ use std::time::Duration;
|
||||
use anyhow::{Context as _, Result, bail, ensure};
|
||||
use base64::Engine as _;
|
||||
use furumi_control_protocol::{
|
||||
API_VERSION, ClientMessage, Command, Discovery, MAX_MESSAGE_BYTES, ServerMessage, Snapshot,
|
||||
API_VERSION, ClientMessage, Command, Discovery, LikedRadioSeed, MAX_MESSAGE_BYTES,
|
||||
ServerMessage, Snapshot,
|
||||
};
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
@@ -28,8 +29,17 @@ mod tests;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Request {
|
||||
pub id: String,
|
||||
pub command: Command,
|
||||
pub reply: oneshot::Sender<std::result::Result<(), String>>,
|
||||
pub reply: ReplySender,
|
||||
}
|
||||
|
||||
pub type ReplySender = oneshot::Sender<std::result::Result<Reply, String>>;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum Reply {
|
||||
Done,
|
||||
LikedRadioSeed(LikedRadioSeed),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
@@ -189,6 +199,7 @@ async fn broker(
|
||||
let (tx, rx) = oneshot::channel();
|
||||
let result = if events
|
||||
.send(crate::app::event::AppEvent::Control(Request {
|
||||
id: request.id.clone(),
|
||||
command: request.command.clone(),
|
||||
reply: tx,
|
||||
}))
|
||||
@@ -202,10 +213,17 @@ async fn broker(
|
||||
.and_then(|reply| reply.map_err(|_| "player unavailable".to_string()))
|
||||
.and_then(|result| result)
|
||||
};
|
||||
let result = ServerMessage::Result {
|
||||
id: request.id.clone(),
|
||||
accepted: result.is_ok(),
|
||||
error: result.err(),
|
||||
let result = match result {
|
||||
Ok(Reply::Done) => ServerMessage::Result {
|
||||
id: request.id.clone(),
|
||||
accepted: true,
|
||||
error: None,
|
||||
},
|
||||
Ok(Reply::LikedRadioSeed(seed)) => ServerMessage::LikedRadioSeed {
|
||||
id: request.id.clone(),
|
||||
seed,
|
||||
},
|
||||
Err(error) => failure(request.id.clone(), &error),
|
||||
};
|
||||
if recent.len() == 256 {
|
||||
recent.pop_front();
|
||||
|
||||
+59
-1
@@ -40,6 +40,23 @@ type TestConnection = (
|
||||
JoinHandle<()>,
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn older_local_snapshots_do_not_advertise_liked_radio() {
|
||||
let snapshot =
|
||||
crate::app::control::published(&crate::app::state::AppState::default(), 1).snapshot;
|
||||
let mut legacy = serde_json::to_value(snapshot).unwrap();
|
||||
assert_eq!(
|
||||
legacy
|
||||
.as_object_mut()
|
||||
.unwrap()
|
||||
.remove("liked_radio_supported"),
|
||||
Some(true.into())
|
||||
);
|
||||
let decoded: Snapshot = serde_json::from_value(legacy).unwrap();
|
||||
assert!(!decoded.liked_radio_supported);
|
||||
assert!(decoded.radio.request_id.is_none());
|
||||
}
|
||||
|
||||
async fn connect() -> TestConnection {
|
||||
connect_with(art::Covers::with(|_, _| Box::pin(async { None }))).await
|
||||
}
|
||||
@@ -149,6 +166,47 @@ async fn authenticated_session_streams_idle_state_and_routes_commands() {
|
||||
task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn retrying_a_liked_radio_pick_returns_the_same_preview_without_a_second_draw() {
|
||||
let (commands, queue) = mpsc::channel(8);
|
||||
let (events, mut event_rx) = mpsc::unbounded_channel();
|
||||
let task = tokio::spawn(broker(queue, events));
|
||||
let seed = LikedRadioSeed {
|
||||
key: "lib:7".into(),
|
||||
title: "One".into(),
|
||||
artist: "Two".into(),
|
||||
};
|
||||
for attempt in 0..2 {
|
||||
let (tx, rx) = oneshot::channel();
|
||||
commands
|
||||
.send(Queued {
|
||||
id: "pick".into(),
|
||||
command: Command::PickLikedRadioSeed {
|
||||
exclude: None,
|
||||
replace_request_id: None,
|
||||
},
|
||||
reply: tx,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
if attempt == 0 {
|
||||
let Some(crate::app::event::AppEvent::Control(request)) = event_rx.recv().await else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(request.id, "pick");
|
||||
request
|
||||
.reply
|
||||
.send(Ok(Reply::LikedRadioSeed(seed.clone())))
|
||||
.unwrap();
|
||||
}
|
||||
assert!(
|
||||
matches!(rx.await.unwrap(), ServerMessage::LikedRadioSeed { id, seed: picked } if id == "pick" && picked == seed)
|
||||
);
|
||||
}
|
||||
assert!(event_rx.try_recv().is_err());
|
||||
task.abort();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_ids_are_deduplicated_across_clients_and_payload_changes_rejected() {
|
||||
let (commands, queue) = mpsc::channel(8);
|
||||
@@ -166,7 +224,7 @@ async fn repeated_ids_are_deduplicated_across_clients_and_payload_changes_reject
|
||||
let crate::app::event::AppEvent::Control(event) = event_rx.recv().await.unwrap() else {
|
||||
panic!()
|
||||
};
|
||||
event.reply.send(Ok(())).unwrap();
|
||||
event.reply.send(Ok(Reply::Done)).unwrap();
|
||||
assert!(matches!(
|
||||
rx.await.unwrap(),
|
||||
ServerMessage::Result { accepted: true, .. }
|
||||
|
||||
Reference in new issue
Block a user