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:
Yuriy Panov committed 2026-10-15 15:30:59 +06:00
1 parent 03aa180840
commit 99f795b500
7 files changed
+257 -94

No files matched your search

+71 -36
View File
@@ -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(()) };
+8
View File
@@ -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
View File
@@ -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]