Musyx Mobile: Android TV player for Yandex Music
Kotlin, Compose for TV and Media3 port of the desktop Musyx, with device-code sign-in, Home, My Wave, search, collection, detail pages, Now Playing with queue and lyrics, and settings for streaming quality, appearance, font size (small, medium, large) and language. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
46610d95fa
217 files changed
+26144
No files matched your search
@@ -0,0 +1,375 @@
|
||||
//! My Wave and other radio stations ("rotor"), plus listening reports.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use yamuse::models as y;
|
||||
|
||||
use crate::models::{Track, cover_url};
|
||||
|
||||
/// The personal station behind "My Wave".
|
||||
pub const MY_WAVE: &str = "user:onyourwave";
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Mood {
|
||||
#[default]
|
||||
Any,
|
||||
Energetic,
|
||||
Cheerful,
|
||||
Calm,
|
||||
Sad,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Character {
|
||||
#[default]
|
||||
Default,
|
||||
Favourite,
|
||||
Unfamiliar,
|
||||
Popular,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum Language {
|
||||
#[default]
|
||||
Any,
|
||||
Russian,
|
||||
Foreign,
|
||||
}
|
||||
|
||||
impl Mood {
|
||||
pub const ALL: [Mood; 5] = [Mood::Any, Mood::Energetic, Mood::Cheerful, Mood::Calm, Mood::Sad];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Mood::Any => "Any",
|
||||
Mood::Energetic => "Energetic",
|
||||
Mood::Cheerful => "Cheerful",
|
||||
Mood::Calm => "Calm",
|
||||
Mood::Sad => "Sad",
|
||||
}
|
||||
}
|
||||
|
||||
fn to_yamuse(self) -> yamuse::MoodEnergy {
|
||||
match self {
|
||||
Mood::Any => yamuse::MoodEnergy::All,
|
||||
Mood::Energetic => yamuse::MoodEnergy::Active,
|
||||
Mood::Cheerful => yamuse::MoodEnergy::Fun,
|
||||
Mood::Calm => yamuse::MoodEnergy::Calm,
|
||||
Mood::Sad => yamuse::MoodEnergy::Sad,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_api(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
Some("active") => Mood::Energetic,
|
||||
Some("fun") => Mood::Cheerful,
|
||||
Some("calm") => Mood::Calm,
|
||||
Some("sad") => Mood::Sad,
|
||||
_ => Mood::Any,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Character {
|
||||
pub const ALL: [Character; 4] =
|
||||
[Character::Default, Character::Favourite, Character::Unfamiliar, Character::Popular];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Character::Default => "Any",
|
||||
Character::Favourite => "Favourite",
|
||||
Character::Unfamiliar => "Unfamiliar",
|
||||
Character::Popular => "Popular",
|
||||
}
|
||||
}
|
||||
|
||||
fn to_yamuse(self) -> yamuse::Diversity {
|
||||
match self {
|
||||
Character::Default => yamuse::Diversity::Default,
|
||||
Character::Favourite => yamuse::Diversity::Favorite,
|
||||
Character::Unfamiliar => yamuse::Diversity::Discover,
|
||||
Character::Popular => yamuse::Diversity::Popular,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_api(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
Some("favorite") => Character::Favourite,
|
||||
Some("discover") => Character::Unfamiliar,
|
||||
Some("popular") => Character::Popular,
|
||||
_ => Character::Default,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Language {
|
||||
pub const ALL: [Language; 3] = [Language::Any, Language::Russian, Language::Foreign];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Language::Any => "Any",
|
||||
Language::Russian => "Russian",
|
||||
Language::Foreign => "Foreign",
|
||||
}
|
||||
}
|
||||
|
||||
fn to_yamuse(self) -> yamuse::StationLanguage {
|
||||
match self {
|
||||
Language::Any => yamuse::StationLanguage::Any,
|
||||
Language::Russian => yamuse::StationLanguage::Russian,
|
||||
Language::Foreign => yamuse::StationLanguage::NotRussian,
|
||||
}
|
||||
}
|
||||
|
||||
fn from_api(s: Option<&str>) -> Self {
|
||||
match s {
|
||||
Some("russian") => Language::Russian,
|
||||
Some("not-russian") => Language::Foreign,
|
||||
_ => Language::Any,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub struct WaveSettings {
|
||||
pub mood: Mood,
|
||||
pub character: Character,
|
||||
pub language: Language,
|
||||
}
|
||||
|
||||
impl WaveSettings {
|
||||
pub(crate) fn from_api(s: &y::StationSettings) -> Self {
|
||||
Self {
|
||||
mood: Mood::from_api(s.mood_energy.as_deref()),
|
||||
character: Character::from_api(s.diversity.as_deref()),
|
||||
language: Language::from_api(s.language.as_deref()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn to_yamuse(self) -> (yamuse::MoodEnergy, yamuse::Diversity, yamuse::StationLanguage) {
|
||||
(self.mood.to_yamuse(), self.character.to_yamuse(), self.language.to_yamuse())
|
||||
}
|
||||
}
|
||||
|
||||
/// A station to start: My Wave, a genre, an activity, an era.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Station {
|
||||
/// `type:tag`, e.g. `genre:rock`.
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub color: Option<String>,
|
||||
icon_uri: Option<String>,
|
||||
}
|
||||
|
||||
impl Station {
|
||||
pub(crate) fn from_yamuse(r: y::StationResult) -> Option<Self> {
|
||||
let s = r.station?;
|
||||
let id = s.id?.as_string()?;
|
||||
let icon = s.icon.as_ref();
|
||||
Some(Self {
|
||||
id,
|
||||
name: r.custom_name.or(s.name).unwrap_or_else(|| "Station".into()),
|
||||
color: icon.and_then(|i| i.background_color.clone()).filter(|c| c.starts_with('#')),
|
||||
icon_uri: icon.and_then(|i| i.image_url.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn icon_url(&self, size: u32) -> Option<String> {
|
||||
cover_url(self.icon_uri.as_deref(), size)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
/// 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
|
||||
}
|
||||
}
|
||||
|
||||
/// Listening events a station learns from.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum WaveEvent {
|
||||
Started,
|
||||
TrackStarted { track_id: String },
|
||||
TrackFinished { track_id: String, played: Duration },
|
||||
Skipped { track_id: String, played: Duration },
|
||||
}
|
||||
|
||||
/// A finished or abandoned listen, for the user's history and the artists' counts.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct PlayReport {
|
||||
pub track_id: String,
|
||||
pub album_id: Option<i64>,
|
||||
pub length: Duration,
|
||||
pub played: Duration,
|
||||
pub end_position: Duration,
|
||||
/// Where it was played from, e.g. `musyx-wave` or `musyx-list`.
|
||||
pub from: String,
|
||||
}
|
||||
|
||||
/// `2026-10-15T15:20:01.042Z`, the only format `/play-audio` accepts.
|
||||
pub(crate) fn iso_millis(t: std::time::SystemTime) -> String {
|
||||
let ms = t.duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_millis()) as i64;
|
||||
let (secs, millis) = (ms.div_euclid(1000), ms.rem_euclid(1000));
|
||||
let (days, tod) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
|
||||
// Howard Hinnant's days-to-civil.
|
||||
let z = days + 719_468;
|
||||
let era = z.div_euclid(146_097);
|
||||
let doe = z.rem_euclid(146_097);
|
||||
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||
let mp = (5 * doy + 2) / 153;
|
||||
let day = doy - (153 * mp + 2) / 5 + 1;
|
||||
let month = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||
format!(
|
||||
"{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{millis:03}Z",
|
||||
tod / 3600,
|
||||
(tod % 3600) / 60,
|
||||
tod % 60
|
||||
)
|
||||
}
|
||||
|
||||
/// `"123"` and `"123:456"` both mean track 123; uploads have no numeric id.
|
||||
pub(crate) fn numeric_id(id: &str) -> Option<i64> {
|
||||
id.split(':').next()?.parse().ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn settings_round_trip_through_api_strings() {
|
||||
let s = WaveSettings::from_api(&y::StationSettings {
|
||||
mood_energy: Some("calm".into()),
|
||||
diversity: Some("discover".into()),
|
||||
language: Some("not-russian".into()),
|
||||
..Default::default()
|
||||
});
|
||||
assert_eq!(s, WaveSettings { mood: Mood::Calm, character: Character::Unfamiliar, language: Language::Foreign });
|
||||
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(
|
||||
r##"{"station":{"id":{"type":"genre","tag":"rock"},"name":"Рок",
|
||||
"icon":{"backgroundColor":"#ff4444","imageUrl":"avatars.yandex.net/x/%%"}}}"##,
|
||||
)
|
||||
.unwrap();
|
||||
let s = Station::from_yamuse(r).unwrap();
|
||||
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"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_millis_always_has_three_fraction_digits() {
|
||||
use std::time::{Duration, UNIX_EPOCH};
|
||||
assert_eq!(iso_millis(UNIX_EPOCH), "1970-01-01T00:00:00.000Z");
|
||||
let t = UNIX_EPOCH + Duration::from_millis(1_792_078_801_042);
|
||||
assert_eq!(iso_millis(t), "2026-10-15T15:40:01.042Z");
|
||||
let leap = UNIX_EPOCH + Duration::from_secs(951_782_400); // 2000-02-29
|
||||
assert_eq!(iso_millis(leap), "2000-02-29T00:00:00.000Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_ids() {
|
||||
assert_eq!(numeric_id("123"), Some(123));
|
||||
assert_eq!(numeric_id("123:456"), Some(123));
|
||||
assert_eq!(numeric_id("abc-upload"), None);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user