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(()) };