fix: play stations through the rotor session API so feedback is accepted
The old /rotor/station/{id}/feedback endpoint answered every event,
radioStarted included, with "condition is not met". Stations now run
on /rotor/session: a session starts with seeds (My Wave settings travel
as settingMoodEnergy/Diversity/Language seeds), batches continue it with
recent track ids, and feedback posts JSON events with millisecond ISO
timestamps and trackId:albumId to /rotor/session/{id}/feedback.
- ym-api posts JSON itself (yamuse keeps its JSON POST private), with the
same client header; YmClient's Debug no longer prints anything
- Player keeps the session id, sends radioStarted with the first batch,
and starts a new session when settings change
This commit is contained in:
1 parent
03aa180840
commit
99f795b500
7 files changed
+257
-94
No files matched your search
@@ -55,9 +55,10 @@ async fn main() {
|
||||
Ok(s) => println!("wave settings: {s:?}"),
|
||||
Err(e) => println!("wave settings: ERROR {e}"),
|
||||
}
|
||||
match client.wave_tracks(ym_api::MY_WAVE, None).await {
|
||||
match client.wave_start(ym_api::MY_WAVE, None).await {
|
||||
Ok(b) => println!(
|
||||
"wave batch {:?}: {:?}",
|
||||
"wave session {:?} batch {:?}: {:?}",
|
||||
b.session_id,
|
||||
b.batch_id,
|
||||
b.tracks.iter().map(|t| format!("{} — {}", t.artist_line(), t.title)).collect::<Vec<_>>()
|
||||
),
|
||||
|
||||
@@ -681,18 +681,23 @@ impl App {
|
||||
.map(|(track_id, result)| Message::Player(player::Msg::Prefetched { track_id, result }))
|
||||
}
|
||||
Effect::SignedOut => Task::done(Message::SignOut),
|
||||
Effect::WaveFetch { station, after } => {
|
||||
Effect::WaveFetch { station, session_id, queue } => {
|
||||
let client = client.clone();
|
||||
// My Wave's settings ride along as seeds when a session starts.
|
||||
let settings = (station == MY_WAVE).then(|| self.wave.shown()).flatten();
|
||||
Task::future(async move {
|
||||
let result = client.wave_tracks(&station, after.as_deref()).await;
|
||||
let result = match session_id {
|
||||
Some(id) => client.wave_more(&id, &queue).await,
|
||||
None => client.wave_start(&station, settings).await,
|
||||
};
|
||||
Message::Player(player::Msg::WaveBatch { station, result })
|
||||
})
|
||||
}
|
||||
// Feedback and reports are fire-and-forget: a lost one only blunts recommendations.
|
||||
Effect::WaveFeedback { station, event, batch_id } => {
|
||||
Effect::WaveFeedback { session_id, event, batch_id } => {
|
||||
let client = client.clone();
|
||||
Task::future(async move {
|
||||
if let Err(e) = client.wave_feedback(&station, &event, batch_id.as_deref()).await {
|
||||
if let Err(e) = client.wave_feedback(&session_id, &event, batch_id.as_deref()).await {
|
||||
eprintln!("wave feedback {event:?} (batch {batch_id:?}): {e}");
|
||||
}
|
||||
})
|
||||
|
||||
@@ -19,6 +19,8 @@ const MAX_SKIPS: u8 = 3;
|
||||
const RESTART_AFTER: Duration = Duration::from_secs(3);
|
||||
/// Ask a station for more once this few tracks are left.
|
||||
const WAVE_LOW_WATER: usize = 2;
|
||||
/// Recent tracks sent with a request for more, so the station knows the context.
|
||||
const WAVE_CONTEXT: usize = 5;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Status {
|
||||
@@ -68,8 +70,9 @@ pub enum Effect {
|
||||
Prefetch { track_id: String },
|
||||
/// The token stopped working mid-session.
|
||||
SignedOut,
|
||||
WaveFetch { station: String, after: Option<String> },
|
||||
WaveFeedback { station: String, event: WaveEvent, batch_id: Option<String> },
|
||||
/// Start a session (`session_id: None`) or continue one; `queue` is recent `full_id`s.
|
||||
WaveFetch { station: String, session_id: Option<String>, queue: Vec<String> },
|
||||
WaveFeedback { session_id: String, event: WaveEvent, batch_id: Option<String> },
|
||||
Report(PlayReport),
|
||||
}
|
||||
|
||||
@@ -77,6 +80,8 @@ pub enum Effect {
|
||||
#[derive(Debug, Clone)]
|
||||
struct Wave {
|
||||
station: String,
|
||||
/// Set by the first batch; feedback can't be sent before it.
|
||||
session_id: Option<String>,
|
||||
/// The batch each queued track came in; feedback must name the track's own batch.
|
||||
batches: std::collections::HashMap<String, String>,
|
||||
fetching: bool,
|
||||
@@ -215,27 +220,26 @@ impl Player {
|
||||
self.send(Command::Stop);
|
||||
self.wave = Some(Wave {
|
||||
station: station.clone(),
|
||||
session_id: None,
|
||||
batches: Default::default(),
|
||||
fetching: true,
|
||||
waiting: true,
|
||||
});
|
||||
effects.push(Effect::WaveFeedback { station: station.clone(), event: WaveEvent::Started, batch_id: None });
|
||||
effects.push(Effect::WaveFetch { station, after: None });
|
||||
effects.push(Effect::WaveFetch { station, session_id: None, queue: Vec::new() });
|
||||
return effects;
|
||||
}
|
||||
Msg::WaveBatch { station, result } => return self.on_batch(station, result),
|
||||
Msg::WaveRestart => {
|
||||
let after = self.track().map(|t| t.id.clone());
|
||||
// Settings are seeds of a session, so new settings mean a new session.
|
||||
let queue: Vec<String> = self.track().map(Track::full_id).into_iter().collect();
|
||||
let Some(wave) = &mut self.wave else { return vec![] };
|
||||
if let Some(queue) = &mut self.queue {
|
||||
queue.clear_upcoming();
|
||||
if let Some(q) = &mut self.queue {
|
||||
q.clear_upcoming();
|
||||
}
|
||||
self.prefetched = None;
|
||||
if wave.fetching {
|
||||
return vec![];
|
||||
}
|
||||
wave.session_id = None;
|
||||
wave.fetching = true;
|
||||
return vec![Effect::WaveFetch { station: wave.station.clone(), after }];
|
||||
return vec![Effect::WaveFetch { station: wave.station.clone(), session_id: None, queue }];
|
||||
}
|
||||
Msg::Toggle => match self.status {
|
||||
Status::Playing => {
|
||||
@@ -343,11 +347,13 @@ impl Player {
|
||||
self.status = Status::Playing;
|
||||
self.skips = 0;
|
||||
let mut effects = Vec::new();
|
||||
if let Some(id) = self.track().map(|t| t.id.clone()) {
|
||||
if let Some(wave) = &self.wave {
|
||||
if let Some((id, full_id)) = self.track().map(|t| (t.id.clone(), t.full_id())) {
|
||||
if let Some(wave) = &self.wave
|
||||
&& let Some(session_id) = wave.session_id.clone()
|
||||
{
|
||||
effects.push(Effect::WaveFeedback {
|
||||
station: wave.station.clone(),
|
||||
event: WaveEvent::TrackStarted { track_id: id.clone() },
|
||||
session_id,
|
||||
event: WaveEvent::TrackStarted { track_id: full_id },
|
||||
batch_id: wave.batches.get(&id).cloned(),
|
||||
});
|
||||
}
|
||||
@@ -423,14 +429,17 @@ impl Player {
|
||||
end_position: played,
|
||||
from: if self.wave.is_some() { "musyx-wave".into() } else { "musyx-desktop".into() },
|
||||
})];
|
||||
if let Some(wave) = &self.wave {
|
||||
if let Some(wave) = &self.wave
|
||||
&& let Some(session_id) = wave.session_id.clone()
|
||||
{
|
||||
let batch_id = wave.batches.get(&id).cloned();
|
||||
let track_id = track.full_id();
|
||||
let event = if finished {
|
||||
WaveEvent::TrackFinished { track_id: id, played }
|
||||
WaveEvent::TrackFinished { track_id, played }
|
||||
} else {
|
||||
WaveEvent::Skipped { track_id: id, played }
|
||||
WaveEvent::Skipped { track_id, played }
|
||||
};
|
||||
effects.push(Effect::WaveFeedback { station: wave.station.clone(), event, batch_id });
|
||||
effects.push(Effect::WaveFeedback { session_id, event, batch_id });
|
||||
}
|
||||
effects
|
||||
}
|
||||
@@ -442,7 +451,11 @@ impl Player {
|
||||
return vec![];
|
||||
}
|
||||
wave.fetching = true;
|
||||
vec![Effect::WaveFetch { station: wave.station.clone(), after: Some(queue.last().id.clone()) }]
|
||||
vec![Effect::WaveFetch {
|
||||
station: wave.station.clone(),
|
||||
session_id: wave.session_id.clone(),
|
||||
queue: queue.tail(WAVE_CONTEXT).map(Track::full_id).collect(),
|
||||
}]
|
||||
}
|
||||
|
||||
fn on_batch(&mut self, station: String, result: Result<WaveBatch, Error>) -> Vec<Effect> {
|
||||
@@ -470,8 +483,20 @@ impl Player {
|
||||
wave.batches.insert(track.id.clone(), batch_id.clone());
|
||||
}
|
||||
}
|
||||
// The first batch of a session opens it: tell the station the radio started.
|
||||
let mut effects = Vec::new();
|
||||
if wave.session_id.is_none()
|
||||
&& let Some(session_id) = batch.session_id.clone()
|
||||
{
|
||||
wave.session_id = Some(session_id.clone());
|
||||
effects.push(Effect::WaveFeedback {
|
||||
session_id,
|
||||
event: WaveEvent::Started,
|
||||
batch_id: batch.batch_id.clone(),
|
||||
});
|
||||
}
|
||||
let waiting = std::mem::replace(&mut wave.waiting, false);
|
||||
match &mut self.queue {
|
||||
let next = match &mut self.queue {
|
||||
None => {
|
||||
self.queue = Queue::new(batch.tracks, 0, false);
|
||||
self.load_current()
|
||||
@@ -484,7 +509,9 @@ impl Player {
|
||||
self.prefetch_next()
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
effects.extend(next);
|
||||
effects
|
||||
}
|
||||
|
||||
fn load_current(&mut self) -> Vec<Effect> {
|
||||
@@ -724,13 +751,16 @@ mod tests {
|
||||
fn wave_with(n: usize) -> Player {
|
||||
let mut p = Player::default();
|
||||
let effects = p.update(Msg::PlayWave { station: "user:onyourwave".into() });
|
||||
assert!(matches!(
|
||||
effects.as_slice(),
|
||||
[Effect::WaveFeedback { event: WaveEvent::Started, .. }, Effect::WaveFetch { after: None, .. }]
|
||||
));
|
||||
let batch = WaveBatch { tracks: (0..n).map(|i| track(&format!("w{i}"), 100)).collect(), batch_id: Some("b1".into()) };
|
||||
assert!(matches!(effects.as_slice(), [Effect::WaveFetch { session_id: None, .. }]), "{effects:?}");
|
||||
let batch = WaveBatch {
|
||||
session_id: Some("s1".into()),
|
||||
tracks: (0..n).map(|i| track(&format!("w{i}"), 100)).collect(),
|
||||
batch_id: Some("b1".into()),
|
||||
};
|
||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||
let Some(Effect::Fetch { generation, .. }) = effects.first().cloned() else { panic!("{effects:?}") };
|
||||
assert!(matches!(&effects[0],
|
||||
Effect::WaveFeedback { session_id, event: WaveEvent::Started, batch_id: Some(b) } if session_id == "s1" && b == "b1"));
|
||||
let Some(Effect::Fetch { generation, .. }) = effects.get(1).cloned() else { panic!("{effects:?}") };
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
p
|
||||
}
|
||||
@@ -761,8 +791,9 @@ mod tests {
|
||||
p.update(Msg::Fetched { generation, result: Ok(audio()) });
|
||||
let effects = loaded(&mut p);
|
||||
assert!(
|
||||
effects.iter().any(|e| matches!(e, Effect::WaveFetch { after: Some(last), .. } if last == "w2")),
|
||||
"one left, so ask for more after the last queued: {effects:?}"
|
||||
effects.iter().any(|e| matches!(e,
|
||||
Effect::WaveFetch { session_id: Some(s), queue, .. } if s == "s1" && queue.last().map(String::as_str) == Some("w2"))),
|
||||
"one left, so ask the session for more with recent tracks: {effects:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -770,7 +801,7 @@ mod tests {
|
||||
fn feedback_names_each_tracks_own_batch() {
|
||||
let mut p = wave_with(2);
|
||||
loaded(&mut p);
|
||||
let more = WaveBatch { tracks: vec![track("n0", 10)], batch_id: Some("b2".into()) };
|
||||
let more = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("n0", 10)], batch_id: Some("b2".into()) };
|
||||
p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(more) });
|
||||
let effects = p.update(Msg::Next);
|
||||
assert!(effects.iter().any(|e| matches!(e,
|
||||
@@ -786,15 +817,24 @@ mod tests {
|
||||
let effects = p.update(Msg::Engine(Event::Ended { generation }));
|
||||
assert!(effects.iter().any(|e| matches!(e, Effect::WaveFeedback { event: WaveEvent::TrackFinished { .. }, .. })));
|
||||
assert_eq!(p.status(), Status::Loading, "a wave doesn't end");
|
||||
let batch = WaveBatch { tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) };
|
||||
let batch = WaveBatch { session_id: Some("s1".into()), tracks: vec![track("w9", 50)], batch_id: Some("b2".into()) };
|
||||
let effects = p.update(Msg::WaveBatch { station: "user:onyourwave".into(), result: Ok(batch) });
|
||||
assert!(matches!(effects.first(), Some(Effect::Fetch { track_id, .. }) if track_id == "w9"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_settings_start_a_new_session() {
|
||||
let mut p = wave_with(3);
|
||||
loaded(&mut p);
|
||||
let effects = p.update(Msg::WaveRestart);
|
||||
assert!(matches!(effects.as_slice(), [Effect::WaveFetch { session_id: None, queue, .. }] if queue == &["w0"]));
|
||||
assert_eq!(p.queue().unwrap().upcoming().count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_for_another_station_are_ignored() {
|
||||
let mut p = wave_with(2);
|
||||
let batch = WaveBatch { tracks: vec![track("x", 10)], batch_id: None };
|
||||
let batch = WaveBatch { session_id: None, tracks: vec![track("x", 10)], batch_id: None };
|
||||
assert!(p.update(Msg::WaveBatch { station: "genre:rock".into(), result: Ok(batch) }).is_empty());
|
||||
assert_eq!(p.queue().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
@@ -126,9 +126,10 @@ impl<T> Queue<T> {
|
||||
self.items.len()
|
||||
}
|
||||
|
||||
/// The item that plays last.
|
||||
pub fn last(&self) -> &T {
|
||||
&self.items[*self.order.last().expect("queues are never empty")]
|
||||
/// The last `n` items of the play order, oldest first.
|
||||
pub fn tail(&self, n: usize) -> impl Iterator<Item = &T> {
|
||||
let start = self.order.len().saturating_sub(n);
|
||||
self.order[start..].iter().map(move |&i| &self.items[i])
|
||||
}
|
||||
|
||||
/// Adds items to the end of the play order (radio batches arriving).
|
||||
|
||||
+71
-36
@@ -8,6 +8,7 @@ use crate::library::{
|
||||
use crate::discover::{ChartEntry, Genre, Home, SearchKind, SearchResults};
|
||||
use crate::models::{Stream, Track, best_variant};
|
||||
use crate::wave::{PlayReport, Station, WaveBatch, WaveEvent, WaveSettings, iso_millis, numeric_id};
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// How many featured podcasts to resolve.
|
||||
@@ -71,9 +72,17 @@ impl Account {
|
||||
}
|
||||
|
||||
/// An authenticated API client. Cheap to clone.
|
||||
#[derive(Debug, Clone)]
|
||||
#[derive(Clone)]
|
||||
pub struct YmClient {
|
||||
inner: yamuse::Client,
|
||||
/// Kept for the few JSON endpoints yamuse doesn't expose. Never printed.
|
||||
token: Option<Arc<str>>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for YmClient {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("YmClient").finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl YmClient {
|
||||
@@ -84,12 +93,12 @@ impl YmClient {
|
||||
let status = inner.refresh_account().await?;
|
||||
let account = Account::from_status(status)
|
||||
.ok_or_else(|| Error::Unauthorized("account status has no user".into()))?;
|
||||
Ok((Self { inner }, account))
|
||||
Ok((Self { inner, token: Some(credentials.access_token.as_str().into()) }, account))
|
||||
}
|
||||
|
||||
/// A client with no token, for previews and tests. Every account call fails.
|
||||
pub fn unauthenticated() -> Result<Self> {
|
||||
Ok(Self { inner: yamuse::Client::anonymous()? })
|
||||
Ok(Self { inner: yamuse::Client::anonymous()?, token: None })
|
||||
}
|
||||
|
||||
/// The user's liked tracks, newest like first, with full metadata.
|
||||
@@ -322,44 +331,70 @@ impl YmClient {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The next tracks of a station. Pass the last track played as `after` to
|
||||
/// continue the sequence; `None` starts fresh.
|
||||
pub async fn wave_tracks(&self, station: &str, after: Option<&str>) -> Result<WaveBatch> {
|
||||
let queue = after.and_then(numeric_id);
|
||||
Ok(WaveBatch::from_yamuse(self.inner.rotor_station_tracks(station, queue).await?))
|
||||
/// Starts a station session. My Wave's settings travel as extra seeds.
|
||||
pub async fn wave_start(&self, station: &str, settings: Option<WaveSettings>) -> Result<WaveBatch> {
|
||||
let mut seeds = vec![station.to_owned()];
|
||||
seeds.extend(settings.map(WaveSettings::seeds).unwrap_or_default());
|
||||
let body = serde_json::json!({ "seeds": seeds, "includeTracksInResponse": true });
|
||||
Ok(WaveBatch::from_session(&self.post_json("/rotor/session/new", &body).await?))
|
||||
}
|
||||
|
||||
/// Tells a station what happened, so the next batch fits better.
|
||||
pub async fn wave_feedback(&self, station: &str, event: &WaveEvent, batch_id: Option<&str>) -> Result<()> {
|
||||
use yamuse::RotorFeedback as F;
|
||||
let mut report = yamuse::RotorFeedbackReport {
|
||||
batch_id: batch_id.map(str::to_owned),
|
||||
..Default::default()
|
||||
};
|
||||
let kind = match event {
|
||||
WaveEvent::Started => {
|
||||
report.from = Some("musyx-wave".into());
|
||||
F::RadioStarted
|
||||
}
|
||||
WaveEvent::TrackStarted { track_id } => {
|
||||
report.track_id = numeric_id(track_id);
|
||||
F::TrackStarted
|
||||
}
|
||||
WaveEvent::TrackFinished { track_id, played } => {
|
||||
report.track_id = numeric_id(track_id);
|
||||
report.total_played_seconds = Some(played.as_secs_f64());
|
||||
F::TrackFinished
|
||||
}
|
||||
WaveEvent::Skipped { track_id, played } => {
|
||||
report.track_id = numeric_id(track_id);
|
||||
report.total_played_seconds = Some(played.as_secs_f64());
|
||||
F::Skip
|
||||
}
|
||||
};
|
||||
self.inner.rotor_feedback(station, kind, &report).await?;
|
||||
/// The next batch of a session. `queue` is the recently queued tracks (`full_id`s).
|
||||
pub async fn wave_more(&self, session_id: &str, queue: &[String]) -> Result<WaveBatch> {
|
||||
let body = serde_json::json!({ "queue": queue });
|
||||
let path = format!("/rotor/session/{session_id}/tracks");
|
||||
let mut batch = WaveBatch::from_session(&self.post_json(&path, &body).await?);
|
||||
batch.session_id.get_or_insert_with(|| session_id.to_owned());
|
||||
Ok(batch)
|
||||
}
|
||||
|
||||
/// Tells a session what happened, so the next batch fits better.
|
||||
pub async fn wave_feedback(&self, session_id: &str, event: &WaveEvent, batch_id: Option<&str>) -> Result<()> {
|
||||
let now = iso_millis(std::time::SystemTime::now());
|
||||
let mut body = serde_json::json!({ "event": event.to_json(&now) });
|
||||
if let Some(batch) = batch_id {
|
||||
body["batchId"] = batch.into();
|
||||
}
|
||||
if matches!(event, WaveEvent::Started) {
|
||||
body["from"] = "musyx-wave".into();
|
||||
}
|
||||
self.post_json(&format!("/rotor/session/{session_id}/feedback"), &body).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// POSTs JSON with the same identity headers yamuse sends, returning `result`.
|
||||
async fn post_json(&self, path: &str, body: &serde_json::Value) -> Result<serde_json::Value> {
|
||||
let token = self.token.as_deref().ok_or_else(|| Error::Unauthorized("not signed in".into()))?;
|
||||
let response = self
|
||||
.inner
|
||||
.transport()
|
||||
.http()
|
||||
.post(format!("{}{path}", self.inner.base_url()))
|
||||
.header("Authorization", format!("OAuth {token}"))
|
||||
.header("X-Yandex-Music-Client", yamuse::transport::CLIENT_HEADER)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(body.to_string())
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::Network(e.to_string()))?;
|
||||
let status = response.status().as_u16();
|
||||
let text = response.text().await.map_err(|e| Error::Network(e.to_string()))?;
|
||||
let value: serde_json::Value = serde_json::from_str(&text).unwrap_or(serde_json::Value::Null);
|
||||
match status {
|
||||
200..=299 => Ok(value.get("result").cloned().unwrap_or(value)),
|
||||
401 | 403 => Err(Error::Unauthorized(format!("{path}: {status}"))),
|
||||
500.. => Err(Error::Network(format!("{path}: {status}"))),
|
||||
_ => {
|
||||
let message = value
|
||||
.pointer("/error/message")
|
||||
.or_else(|| value.pointer("/error/name"))
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or(&text);
|
||||
Err(Error::Api(format!("{path}: {status} {message}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a listen in the user's history. Tracks without numeric ids are skipped.
|
||||
pub async fn report_play(&self, report: &PlayReport) -> Result<()> {
|
||||
let Some(track_id) = numeric_id(&report.track_id) else { return Ok(()) };
|
||||
|
||||
@@ -70,6 +70,14 @@ impl Track {
|
||||
Self::from_yamuse(raw).ok_or_else(|| crate::Error::Api("track has no id".into()))
|
||||
}
|
||||
|
||||
/// `trackId:albumId`, the form station feedback and queues use.
|
||||
pub fn full_id(&self) -> String {
|
||||
match &self.album {
|
||||
Some(album) if !self.id.contains(':') => format!("{}:{}", self.id, album.id),
|
||||
_ => self.id.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// "Artist A, Artist B", or "Unknown artist".
|
||||
pub fn artist_line(&self) -> String {
|
||||
crate::library::join_names(&self.artists)
|
||||
|
||||
+89
-16
@@ -146,9 +146,7 @@ impl WaveSettings {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_yamuse(
|
||||
self,
|
||||
) -> (yamuse::MoodEnergy, yamuse::Diversity, yamuse::StationLanguage) {
|
||||
pub(crate) fn to_yamuse(self) -> (yamuse::MoodEnergy, yamuse::Diversity, yamuse::StationLanguage) {
|
||||
(self.mood.to_yamuse(), self.character.to_yamuse(), self.language.to_yamuse())
|
||||
}
|
||||
}
|
||||
@@ -181,19 +179,77 @@ impl Station {
|
||||
}
|
||||
}
|
||||
|
||||
/// One batch of station tracks; the batch id goes back with feedback.
|
||||
/// One batch of station tracks. Feedback names the session and the batch.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct WaveBatch {
|
||||
pub session_id: Option<String>,
|
||||
pub tracks: Vec<Track>,
|
||||
pub batch_id: Option<String>,
|
||||
}
|
||||
|
||||
impl WaveBatch {
|
||||
pub(crate) fn from_yamuse(r: y::StationTracksResult) -> Self {
|
||||
Self {
|
||||
tracks: r.sequence.into_iter().filter_map(|s| s.track.and_then(Track::from_yamuse)).collect(),
|
||||
batch_id: r.batch_id,
|
||||
/// From a `/rotor/session/...` result: `{radioSessionId, batchId, sequence: [{track}]}`.
|
||||
pub(crate) fn from_session(v: &serde_json::Value) -> Self {
|
||||
let tracks = v
|
||||
.get("sequence")
|
||||
.and_then(|s| s.as_array())
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|item| item.get("track"))
|
||||
.filter_map(|t| serde_json::from_value::<y::Track>(t.clone()).ok())
|
||||
.filter_map(Track::from_yamuse)
|
||||
.collect();
|
||||
let text = |k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_owned);
|
||||
Self { session_id: text("radioSessionId"), tracks, batch_id: text("batchId") }
|
||||
}
|
||||
}
|
||||
|
||||
impl WaveSettings {
|
||||
/// Settings as session seeds (`settingMoodEnergy:calm`…); defaults add nothing.
|
||||
pub(crate) fn seeds(self) -> Vec<String> {
|
||||
let mut seeds = Vec::new();
|
||||
let mood = match self.mood {
|
||||
Mood::Any => None,
|
||||
Mood::Energetic => Some("active"),
|
||||
Mood::Cheerful => Some("fun"),
|
||||
Mood::Calm => Some("calm"),
|
||||
Mood::Sad => Some("sad"),
|
||||
};
|
||||
let diversity = match self.character {
|
||||
Character::Default => None,
|
||||
Character::Favourite => Some("favorite"),
|
||||
Character::Unfamiliar => Some("discover"),
|
||||
Character::Popular => Some("popular"),
|
||||
};
|
||||
let language = match self.language {
|
||||
Language::Any => None,
|
||||
Language::Russian => Some("russian"),
|
||||
Language::Foreign => Some("not-russian"),
|
||||
};
|
||||
seeds.extend(mood.map(|m| format!("settingMoodEnergy:{m}")));
|
||||
seeds.extend(diversity.map(|d| format!("settingDiversity:{d}")));
|
||||
seeds.extend(language.map(|l| format!("settingLanguage:{l}")));
|
||||
seeds
|
||||
}
|
||||
}
|
||||
|
||||
impl WaveEvent {
|
||||
/// The session feedback body's `event` object.
|
||||
pub(crate) fn to_json(&self, now: &str) -> serde_json::Value {
|
||||
let (kind, track, played) = match self {
|
||||
WaveEvent::Started => ("radioStarted", None, None),
|
||||
WaveEvent::TrackStarted { track_id } => ("trackStarted", Some(track_id), None),
|
||||
WaveEvent::TrackFinished { track_id, played } => ("trackFinished", Some(track_id), Some(played)),
|
||||
WaveEvent::Skipped { track_id, played } => ("skip", Some(track_id), Some(played)),
|
||||
};
|
||||
let mut event = serde_json::json!({ "type": kind, "timestamp": now });
|
||||
if let Some(track) = track {
|
||||
event["trackId"] = track.clone().into();
|
||||
}
|
||||
if let Some(played) = played {
|
||||
event["totalPlayedSeconds"] = played.as_secs_f64().into();
|
||||
}
|
||||
event
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,6 +318,31 @@ mod tests {
|
||||
assert_eq!(WaveSettings::from_api(&y::StationSettings::default()), WaveSettings::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn settings_become_seeds() {
|
||||
assert!(WaveSettings::default().seeds().is_empty());
|
||||
let s = WaveSettings { mood: Mood::Calm, character: Character::Unfamiliar, language: Language::Russian };
|
||||
assert_eq!(s.seeds(), ["settingMoodEnergy:calm", "settingDiversity:discover", "settingLanguage:russian"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn feedback_events_serialise_like_the_official_clients() {
|
||||
let skip = WaveEvent::Skipped { track_id: "1:2".into(), played: Duration::from_millis(1500) };
|
||||
assert_eq!(
|
||||
skip.to_json("T"),
|
||||
serde_json::json!({"type": "skip", "timestamp": "T", "trackId": "1:2", "totalPlayedSeconds": 1.5})
|
||||
);
|
||||
assert_eq!(WaveEvent::Started.to_json("T"), serde_json::json!({"type": "radioStarted", "timestamp": "T"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_batch_parses() {
|
||||
let v = serde_json::json!({"radioSessionId": "s1", "batchId": "b1",
|
||||
"sequence": [{"type": "track", "track": {"id": "7", "title": "A"}}, {"type": "ad"}]});
|
||||
let b = WaveBatch::from_session(&v);
|
||||
assert_eq!((b.session_id.as_deref(), b.batch_id.as_deref(), b.tracks.len()), (Some("s1"), Some("b1"), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn station_and_batch_convert() {
|
||||
let r: y::StationResult = serde_json::from_str(
|
||||
@@ -273,14 +354,6 @@ mod tests {
|
||||
assert_eq!(s.id, "genre:rock");
|
||||
assert_eq!(s.color.as_deref(), Some("#ff4444"));
|
||||
assert_eq!(s.icon_url(200).as_deref(), Some("https://avatars.yandex.net/x/200x200"));
|
||||
|
||||
let b: y::StationTracksResult = serde_json::from_str(
|
||||
r#"{"batchId":"b1","sequence":[{"type":"track","track":{"id":5,"title":"A"}},{"type":"ad"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let batch = WaveBatch::from_yamuse(b);
|
||||
assert_eq!(batch.tracks.len(), 1);
|
||||
assert_eq!(batch.batch_id.as_deref(), Some("b1"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
Reference in new issue
Block a user