diff --git a/AGENTS.md b/AGENTS.md index 1061a48..1748afc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -12,7 +12,8 @@ The page engine and the controller come from Netflex TV (`fennec/netflex`); keep app.toml store manifest (id support.bluefox.spotify; permissions network, gpu, audio) src/main.rs window, glass layer (lists every exported [GlassRect]), images, controller src/spotify.rs librespot: session, Spotify Connect (Spirc), sign-in (zeroconf + pairing code), player; Cmd in, Event out -src/api.rs Spotify Web API (browsing, library, search, queue), token from the session; short GET cache, 429 retry +src/api.rs the objects pages use, and Api: Internal (normal) or Web (Web API, only with SPOTIFY_MOCK) +src/internal.rs Spotify's internal endpoints via the session: metadata, playlists, /collection/v2, recently played, search, queue command src/app.rs Controller: screen stack, keys, input/picker/toast, backdrop, sign-in screen, engine events, avatar src/nowplaying.rs Most szól: playback state, controls, seek, lyrics, queue src/page.rs the line-based page engine: lines (L) and chips (Ch) -> layout, focus, scroll, lazy images @@ -28,12 +29,17 @@ src/format.rs Hungarian texts: times, counts, dates src/task.rs blocking work on a thread, result on the UI thread ui/app.slint root: screen fades, one FocusScope -> Rust `key`, glass exports ui/page.slint LinePage: draws the lines Rust lays out (nav, now playing capsule, avatar, keyboard) -ui/nowplaying.slint the now playing screen and its panel (lyrics / queue) +ui/nowplaying.slint the now playing screen and its lyrics panel ui/signin.slint ConnectScreen (QR code + Spotify app), InputScreen, MessageScreen ui/icons.slint SpIcon: shuffle, repeat, heart, lyrics, queue, devices (+ sf-ui's icons) tools/mock_server.py stand-in Web API with made-up data (with SPOTIFY_MOCK=1: no librespot) ``` +The public Web API is not used against Spotify: librespot's client id gets 429 (rate limit) on every call. Browsing goes through `internal.rs`. + +``` +``` + ## Rules of this codebase - **Rust owns state and focus.** Slint only draws. Every key goes to `Controller::key`, except while an on-screen keyboard has the focus. diff --git a/Cargo.lock b/Cargo.lock index 2da5884..6098352 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6659,17 +6659,20 @@ dependencies = [ [[package]] name = "spotify-tv" -version = "0.1.0" +version = "0.1.1" dependencies = [ "anyhow", "env_logger", "futures-util", + "hyper", "librespot-connect", "librespot-core", "librespot-discovery", "librespot-metadata", "librespot-playback", + "librespot-protocol", "log", + "protobuf", "qrcode", "serde", "serde_json", diff --git a/Cargo.toml b/Cargo.toml index 9c3fd10..daf61b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "spotify-tv" description = "Spotify for Fennec OS: native TV client with Liquid Glass, Spotify Connect and librespot playback" -version = "0.1.0" +version = "0.1.1" edition = "2024" # sf-ui (and Slint) are GPL-3.0 on a TV box; librespot is MIT. license = "GPL-3.0-only" @@ -19,7 +19,11 @@ serde_json = "1" toml = "0.9" ureq = { version = "3", features = ["json"] } tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "signal"] } -futures-util = { version = "0.3", default-features = false } +futures-util = { version = "0.3", default-features = false, features = ["std"] } +# The internal endpoints (playlists, collection) speak protobuf. +librespot-protocol = "0.8" +protobuf = "3" +hyper = { version = "1", default-features = false } # The pairing QR code on the sign-in screen. qrcode = { version = "0.14", default-features = false } # Spotify: session, Connect (Spirc), zeroconf sign-in, playback. diff --git a/README.md b/README.md index 436fd87..bf0bbce 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,11 @@ Natív Spotify kliens Fennec OS-re (store app, `support.bluefox.spotify`). Spoti - **A Spotify appból:** ugyanazon a Wi-Fin a TV megjelenik a telefon eszközlistájában (zeroconf). Kiválasztva bejelentkezik. A belépés megmarad (`$HOME/.cache/spotify-tv`). -- **Képernyők:** Kezdőlap (legutóbb játszott, lejátszási listák a Kedvelt dalokkal, kedvenc előadók és dalok, elmentett albumok, új megjelenések), Keresés képernyő-billentyűzettel (dalok, előadók, albumok, listák, podcastok), Könyvtár (listák, albumok, előadók, podcastok), lejátszási lista / album / Kedvelt dalok / podcast oldal, előadó oldal, Beállítások. Jobb fent a bejelentkezett felhasználó képe. -- **Most szól:** nagy borító, tekerés, keverés, ismétlés (lista / szám), kedvelés, szinkronizált dalszöveg, lejátszási sor. A dalsorok „+” gombja: sorba tétel, kedvelés, album, előadó. +- **Képernyők:** Kezdőlap (legutóbb játszott, lejátszási listák a Kedvelt dalokkal, előadóid, elmentett albumok, podcastok), Keresés képernyő-billentyűzettel (dalok, előadók, albumok), Könyvtár (listák, albumok, előadók, podcastok), lejátszási lista / album / Kedvelt dalok / podcast oldal, előadó oldal, Beállítások. Jobb fent a bejelentkezett felhasználó képe. +- **Most szól:** nagy borító, tekerés, keverés, ismétlés (lista / szám), kedvelés, szinkronizált dalszöveg. A dalsorok „+” gombja: sorba tétel, kedvelés, album, előadó. - **Beállítások:** kijelentkezés, a TV neve (Connect), hangminőség (96 / 160 / 320 kbit/s), hangerő-kiegyenlítés, automatikus lejátszás, megjelenés (üveg / matt). -Böngészéshez a Spotify Web API-t használja, a librespot munkamenetéből kapott tokennel. A Spotify szerint ez nem hivatalos kliens. Ha változtatnak a protokollon, a librespot frissítéséig leállhat. +Böngészéshez a Spotify belső végpontjait használja (metaadatok, lejátszási listák, gyűjtemény, legutóbb játszott, keresés), ugyanazon a librespot munkameneten át, mint a lejátszás. A nyilvános Web API a librespot közös kliensazonosítóját folyamatosan 429-cel (túl sok kérés) utasítja el, ezért azt csak a mock szerver használja. A Spotify szerint ez nem hivatalos kliens. Ha változtatnak a protokollon, a librespot frissítéséig leállhat. ## Fejlesztés diff --git a/app.toml b/app.toml index d8c9ee4..e136e09 100644 --- a/app.toml +++ b/app.toml @@ -2,7 +2,7 @@ id = "support.bluefox.spotify" name = "Spotify" # Release versions only (1.2.3). Bump it (and Cargo.toml) for every release. -version = "0.1.0" +version = "0.1.1" kind = "exec" category = "Zene" description = "Zene és podcastok natívan, Spotify Connecttel: a telefonról is irányítható. Spotify Premium fiók kell hozzá." diff --git a/src/api.rs b/src/api.rs index f669f5d..20f2d5f 100644 --- a/src/api.rs +++ b/src/api.rs @@ -1,5 +1,10 @@ -//! Spotify Web API (api.spotify.com/v1): browsing, the library, search, the -//! queue. The access token comes from the librespot session (spotify::Engine). +//! The data behind the pages: Spotify's objects (as the Web API shapes them) +//! and `Api`, which gets them +//! - from Spotify's internal endpoints through the librespot session +//! (src/internal.rs): the normal case; +//! - from the Web API (`Web`, below) with SPOTIFY_MOCK: the mock server +//! (tools/mock_server.py). The real Web API rate-limits librespot's +//! client id to a standstill, so it is not used against Spotify. //! //! Every answer is parsed leniently (missing fields default), since Spotify's //! objects differ a bit between endpoints. GET answers are cached for a short @@ -252,6 +257,20 @@ pub struct Played { pub context: Option, } +/// Something a card can show: what "recently played" lists. +#[derive(Debug, Clone)] +pub enum Entity { + Album(Album), + Playlist(Playlist), + Artist(Artist), + Show(Show), + /// The liked songs. + Liked, +} + +/// An artist's page: the artist, popular tracks, albums, singles, appearances. +pub type ArtistPage = (Artist, Vec, Vec, Vec, Vec); + #[derive(Debug, Clone, Default)] pub struct SearchResult { pub tracks: Vec, @@ -313,15 +332,127 @@ pub fn enc(s: &str) -> String { /// Cheap to clone; usable from any thread (blocking calls). #[derive(Clone)] -pub struct Api { +pub enum Api { + Internal(crate::internal::Internal), + Web(Web), +} + +/// Calls the same method on whichever client this is. +macro_rules! both { + ($self:ident, $m:ident($($a:expr),*)) => { + match $self { + Api::Internal(i) => i.$m($($a),*), + Api::Web(w) => w.$m($($a),*), + } + }; +} + +impl Api { + pub fn new(engine: Engine) -> Api { + if std::env::var_os("SPOTIFY_MOCK").is_some() { Api::Web(Web::new(engine)) } else { Api::Internal(crate::internal::Internal::new(engine)) } + } + pub fn me(&self) -> Result { + both!(self, me()) + } + pub fn recent(&self) -> Result> { + both!(self, recent()) + } + pub fn my_playlists(&self, offset: u32) -> Result> { + both!(self, my_playlists(offset)) + } + pub fn liked(&self, offset: u32) -> Result> { + both!(self, liked(offset)) + } + pub fn saved_albums(&self, offset: u32) -> Result> { + both!(self, saved_albums(offset)) + } + pub fn saved_shows(&self, offset: u32) -> Result> { + both!(self, saved_shows(offset)) + } + pub fn followed_artists(&self, after: &str) -> Result<(Vec, Option)> { + both!(self, followed_artists(after)) + } + pub fn liked_contains(&self, ids: &[String]) -> Result> { + both!(self, liked_contains(ids)) + } + pub fn set_liked(&self, id: &str, on: bool) -> Result<()> { + both!(self, set_liked(id, on)) + } + pub fn album_saved(&self, id: &str) -> Result { + both!(self, album_saved(id)) + } + pub fn set_album_saved(&self, id: &str, on: bool) -> Result<()> { + both!(self, set_album_saved(id, on)) + } + pub fn show_saved(&self, id: &str) -> Result { + both!(self, show_saved(id)) + } + pub fn set_show_saved(&self, id: &str, on: bool) -> Result<()> { + both!(self, set_show_saved(id, on)) + } + pub fn following_artist(&self, id: &str) -> Result { + both!(self, following_artist(id)) + } + pub fn set_following_artist(&self, id: &str, on: bool) -> Result<()> { + both!(self, set_following_artist(id, on)) + } + /// Following someone else's playlist (the Web API only). + pub fn following_playlist(&self, id: &str, user: &str) -> Result { + match self { + Api::Web(w) => w.following_playlist(id, user), + Api::Internal(_) => Err(anyhow::anyhow!("not available")), + } + } + pub fn set_following_playlist(&self, id: &str, on: bool) -> Result<()> { + match self { + Api::Web(w) => w.set_following_playlist(id, on), + Api::Internal(_) => Err(anyhow::anyhow!("not available")), + } + } + pub fn playlist(&self, id: &str) -> Result { + both!(self, playlist(id)) + } + pub fn playlist_tracks(&self, id: &str, offset: u32) -> Result> { + both!(self, playlist_tracks(id, offset)) + } + pub fn album(&self, id: &str) -> Result { + both!(self, album(id)) + } + pub fn album_tracks(&self, id: &str, offset: u32) -> Result> { + match self { + Api::Web(w) => w.album_tracks(id, offset), + // The internal album answer has every track already. + Api::Internal(_) => Ok(Paging::default()), + } + } + pub fn artist_page(&self, id: &str, country: &str) -> Result { + both!(self, artist_page(id, country)) + } + pub fn show(&self, id: &str) -> Result { + both!(self, show(id)) + } + pub fn show_episodes(&self, id: &str, offset: u32) -> Result> { + both!(self, show_episodes(id, offset)) + } + pub fn search(&self, q: &str) -> Result { + both!(self, search(q)) + } + pub fn add_to_queue(&self, uri: &str) -> Result<()> { + both!(self, add_to_queue(uri)) + } +} + +/// The Web API client (the mock server). +#[derive(Clone)] +pub struct Web { base: String, engine: Engine, agent: ureq::Agent, cache: Arc>>, } -impl Api { - pub fn new(engine: Engine) -> Api { +impl Web { + pub fn new(engine: Engine) -> Web { let agent: ureq::Agent = ureq::Agent::config_builder() .timeout_global(Some(Duration::from_secs(30))) .timeout_connect(Some(Duration::from_secs(8))) @@ -330,7 +461,7 @@ impl Api { .build() .into(); let base = std::env::var("SPOTIFY_API").unwrap_or_else(|_| API.to_string()); - Api { base: base.trim_end_matches('/').to_string(), engine, agent, cache: Arc::default() } + Web { base: base.trim_end_matches('/').to_string(), engine, agent, cache: Arc::default() } } /// Forgets cached answers (after a change to the library). @@ -427,6 +558,11 @@ impl Api { // ---- home ---- + pub fn recent(&self) -> Result> { + let mut seen = std::collections::HashSet::new(); + Ok(self.recently_played()?.into_iter().filter_map(|p| p.track.album).filter(|a| seen.insert(a.id.clone())).take(16).map(Entity::Album).collect()) + } + pub fn recently_played(&self) -> Result> { #[derive(Deserialize, Default)] #[serde(default)] @@ -435,20 +571,6 @@ impl Api { } Ok(self.get::("/me/player/recently-played?limit=50")?.items) } - pub fn top_artists(&self) -> Result> { - Ok(self.get::>("/me/top/artists?limit=20&time_range=short_term")?.list()) - } - pub fn top_tracks(&self) -> Result> { - Ok(self.get::>("/me/top/tracks?limit=20&time_range=short_term")?.list()) - } - pub fn new_releases(&self) -> Result> { - #[derive(Deserialize, Default)] - #[serde(default)] - struct R { - albums: Paging, - } - Ok(self.get::("/browse/new-releases?limit=20")?.albums.list()) - } // ---- library ---- @@ -567,6 +689,14 @@ impl Api { pub fn artist_albums(&self, id: &str, groups: &str) -> Result> { Ok(self.get::>(&format!("/artists/{id}/albums?include_groups={groups}&limit=30"))?.list()) } + pub fn artist_page(&self, id: &str, country: &str) -> Result { + let artist = self.artist(id)?; + let top = self.artist_top(id, country).unwrap_or_default(); + let albums = self.artist_albums(id, "album").unwrap_or_default(); + let singles = self.artist_albums(id, "single").unwrap_or_default(); + let appears = self.artist_albums(id, "appears_on,compilation").unwrap_or_default(); + Ok((artist, top, albums, singles, appears)) + } pub fn show(&self, id: &str) -> Result { self.get(&format!("/shows/{id}")) } @@ -592,16 +722,6 @@ impl Api { // ---- player ---- - /// What comes next on the active device. - pub fn queue(&self) -> Result> { - #[derive(Deserialize, Default)] - #[serde(default)] - struct R { - queue: Vec, - } - let text = self.call("GET", "/me/player/queue", false)?; - Ok(serde_json::from_str::(&text).unwrap_or_default().queue) - } pub fn add_to_queue(&self, uri: &str) -> Result<()> { self.send("POST", &format!("/me/player/queue?uri={}", enc(uri))) } diff --git a/src/internal.rs b/src/internal.rs new file mode 100644 index 0000000..787a105 --- /dev/null +++ b/src/internal.rs @@ -0,0 +1,755 @@ +//! Spotify's own (internal) endpoints, through the librespot session: the +//! public Web API rate-limits librespot's client id to a standstill (429 +//! with ever longer Retry-After), these do not. +//! +//! - metadata: albums, artists, tracks, shows, episodes (librespot-metadata) +//! - playlists: /playlist/v2 (protobuf), the user's list: the rootlist +//! - library: /collection/v2 paging and write (sets "collection": liked +//! songs and saved albums, "artist", "show") +//! - recently played: /recently-played/v3 (JSON) +//! - search: the "spotify:search:" context (songs), artists and albums from them +//! - queue: a Connect player command to this device +//! +//! Answers come back as the same objects the Web API code uses (api.rs). + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use anyhow::{Result, anyhow}; +use futures_util::StreamExt; +use librespot_core::{FileId, Session, SpotifyUri}; +use librespot_metadata::image::{ImageSize, Images}; +use librespot_metadata::{Metadata, album, artist, episode, show, track}; +use librespot_protocol::playlist4_external::SelectedListContent; +use hyper::{HeaderMap, Method}; +use protobuf::Message; + +use crate::api::{self, Album, Artist, Entity, Image, Named, Paging, Playlist, SearchResult, Show, Track, User}; +use crate::spotify::Engine; + +/// How long the library lists stay cached. +const SETS_FOR: std::time::Duration = std::time::Duration::from_secs(120); + +#[derive(Default)] +struct Cache { + /// Collection set -> (fetched, uris newest first). + sets: HashMap)>, + tracks: HashMap, + albums: HashMap, +} + +#[derive(Clone)] +pub struct Internal { + engine: Engine, + cache: Arc>, +} + +fn e(err: librespot_core::Error) -> anyhow::Error { + anyhow!("{err}") +} + +// ---------------------------------------------------------------------------- conversions + +fn image_url(id: &FileId) -> String { + format!("https://i.scdn.co/image/{id}") +} + +fn images(i: &Images) -> Vec { + i.iter() + .map(|i| Image { + url: image_url(&i.id), + width: Some(if i.width > 0 { + i.width as u32 + } else { + match i.size { + ImageSize::SMALL => 64, + ImageSize::LARGE => 640, + ImageSize::XLARGE => 1280, + _ => 300, + } + }), + }) + .collect() +} + +fn date(d: &librespot_core::date::Date) -> String { + let y = d.year(); + if y <= 1 { + return String::new(); + } + format!("{y}-{:02}-{:02}", u8::from(d.month()), d.day()) +} + +fn named(id: &SpotifyUri, name: &str) -> Named { + Named { id: id.to_id().unwrap_or_default(), name: name.to_string(), uri: id.to_uri().unwrap_or_default() } +} + +fn album_of(a: &album::Album) -> Album { + let mut imgs = images(&a.covers); + if imgs.is_empty() { + imgs = images(&a.cover_group); + } + Album { + id: a.id.to_id().unwrap_or_default(), + name: a.name.clone(), + uri: a.id.to_uri().unwrap_or_default(), + images: imgs, + artists: a.artists.iter().map(|x| named(&x.id, &x.name)).collect(), + release_date: date(&a.date), + total_tracks: a.discs.iter().map(|d| d.tracks.len() as u32).sum(), + album_type: format!("{:?}", a.album_type).to_lowercase(), + label: a.label.clone(), + tracks: None, + } +} + +fn track_of(t: &track::Track) -> Track { + Track { + id: t.id.to_id().unwrap_or_default(), + name: t.name.clone(), + uri: t.id.to_uri().unwrap_or_default(), + kind: "track".into(), + duration_ms: t.duration.max(0) as u32, + explicit: t.is_explicit, + artists: t.artists.iter().map(|a| named(&a.id, &a.name)).collect(), + album: Some(album_of(&t.album)), + track_number: t.number.max(0) as u32, + is_playable: None, + ..Track::default() + } +} + +fn episode_of(x: &episode::Episode) -> Track { + Track { + id: x.id.to_id().unwrap_or_default(), + name: x.name.clone(), + uri: x.id.to_uri().unwrap_or_default(), + kind: "episode".into(), + duration_ms: x.duration.max(0) as u32, + explicit: x.is_explicit, + images: images(&x.covers), + show: Some(Show { name: x.show_name.clone(), ..Show::default() }), + release_date: date(&x.publish_time), + description: x.description.clone(), + ..Track::default() + } +} + +fn artist_of(a: &artist::Artist) -> Artist { + let mut imgs = images(&a.portrait_group); + if imgs.is_empty() { + imgs = images(&a.portraits); + } + Artist { id: a.id.to_id().unwrap_or_default(), name: a.name.clone(), uri: a.id.to_uri().unwrap_or_default(), images: imgs, followers: None, genres: Vec::new() } +} + +fn show_of(s: &show::Show) -> Show { + Show { + id: s.id.to_id().unwrap_or_default(), + name: s.name.clone(), + uri: s.id.to_uri().unwrap_or_default(), + images: images(&s.covers), + publisher: s.publisher.clone(), + description: s.description.clone(), + total_episodes: s.episodes.len() as u32, + } +} + +fn uri(kind: &str, id: &str) -> Result { + SpotifyUri::from_uri(&format!("spotify:{kind}:{id}")).map_err(e) +} + +// ---------------------------------------------------------------------------- protobuf by hand +// collection2v2 is not compiled into librespot-protocol; its messages are tiny. + +fn varint(out: &mut Vec, mut v: u64) { + loop { + let b = (v & 0x7f) as u8; + v >>= 7; + if v == 0 { + out.push(b); + break; + } + out.push(b | 0x80); + } +} + +fn field_bytes(out: &mut Vec, f: u32, b: &[u8]) { + varint(out, ((f << 3) | 2) as u64); + varint(out, b.len() as u64); + out.extend_from_slice(b); +} + +fn field_varint(out: &mut Vec, f: u32, v: u64) { + varint(out, (f << 3) as u64); + varint(out, v); +} + +fn read_varint(b: &[u8], i: &mut usize) -> Option { + let (mut v, mut s) = (0u64, 0); + loop { + let x = *b.get(*i)?; + *i += 1; + v |= ((x & 0x7f) as u64) << s; + s += 7; + if x & 0x80 == 0 { + return Some(v); + } + if s > 63 { + return None; + } + } +} + +/// The fields of a message: (number, varint value or bytes). +fn fields(b: &[u8]) -> Vec<(u32, Result)> { + let mut out = Vec::new(); + let mut i = 0; + while i < b.len() { + let Some(key) = read_varint(b, &mut i) else { break }; + let (f, w) = ((key >> 3) as u32, key & 7); + match w { + 0 => match read_varint(b, &mut i) { + Some(v) => out.push((f, Ok(v))), + None => break, + }, + 2 => { + let Some(len) = read_varint(b, &mut i) else { break }; + let end = i + len as usize; + if end > b.len() { + break; + } + out.push((f, Err(&b[i..end]))); + i = end; + } + 1 => i += 8, + 5 => i += 4, + _ => break, + } + } + out +} + +/// PageResponse -> (items (uri, added_at, removed), next page token). +fn parse_page(b: &[u8]) -> (Vec<(String, u64, bool)>, String) { + let mut items = Vec::new(); + let mut next = String::new(); + for (f, v) in fields(b) { + match (f, v) { + (1, Err(item)) => { + let (mut uri, mut at, mut removed) = (String::new(), 0, false); + for (g, w) in fields(item) { + match (g, w) { + (1, Err(s)) => uri = String::from_utf8_lossy(s).into_owned(), + (2, Ok(t)) => at = t, + (3, Ok(r)) => removed = r != 0, + _ => {} + } + } + items.push((uri, at, removed)); + } + (2, Err(s)) => next = String::from_utf8_lossy(s).into_owned(), + _ => {} + } + } + (items, next) +} + +fn collection_headers() -> HeaderMap { + let mut h = HeaderMap::new(); + let ct = "application/vnd.collection-v2.spotify.proto"; + h.insert("content-type", ct.parse().unwrap()); + h.insert("accept", ct.parse().unwrap()); + h +} + +// ---------------------------------------------------------------------------- client + +impl Internal { + pub fn new(engine: Engine) -> Internal { + Internal { engine, cache: Arc::default() } + } + + fn session(&self) -> Result { + self.engine.session() + } + + /// Track (and episode) metadata, in order; cached. + fn tracks(&self, uris: &[String]) -> Result> { + let s = self.session()?; + let missing: Vec = { + let c = self.cache.lock().unwrap(); + uris.iter().filter(|u| !c.tracks.contains_key(*u)).cloned().collect() + }; + if !missing.is_empty() { + let got: Vec = self.engine.block(async { + futures_util::stream::iter(missing) + .map(|u| { + let s = s.clone(); + async move { + let id = SpotifyUri::from_uri(&u).ok()?; + match id { + SpotifyUri::Episode { .. } => episode::Episode::get(&s, &id).await.ok().map(|x| episode_of(&x)), + SpotifyUri::Track { .. } => track::Track::get(&s, &id).await.ok().map(|t| track_of(&t)), + _ => None, + } + } + }) + .buffered(16) + .filter_map(std::future::ready) + .collect() + .await + }); + let mut c = self.cache.lock().unwrap(); + if c.tracks.len() > 3000 { + c.tracks.clear(); + } + for t in got { + c.tracks.insert(t.uri.clone(), t); + } + } + let c = self.cache.lock().unwrap(); + Ok(uris.iter().filter_map(|u| c.tracks.get(u).cloned()).collect()) + } + + /// Album metadata (without the track list), in order; cached. + fn albums(&self, uris: &[String]) -> Result> { + let s = self.session()?; + let missing: Vec = { + let c = self.cache.lock().unwrap(); + uris.iter().filter(|u| !c.albums.contains_key(*u)).cloned().collect() + }; + if !missing.is_empty() { + let got: Vec = self.engine.block(async { + futures_util::stream::iter(missing) + .map(|u| { + let s = s.clone(); + async move { + let id = SpotifyUri::from_uri(&u).ok()?; + album::Album::get(&s, &id).await.ok().map(|a| album_of(&a)) + } + }) + .buffered(12) + .filter_map(std::future::ready) + .collect() + .await + }); + let mut c = self.cache.lock().unwrap(); + for a in got { + c.albums.insert(a.uri.clone(), a); + } + } + let c = self.cache.lock().unwrap(); + Ok(uris.iter().filter_map(|u| c.albums.get(u).cloned()).collect()) + } + + fn artists(&self, uris: &[String]) -> Result> { + let s = self.session()?; + Ok(self.engine.block(async { + futures_util::stream::iter(uris.to_vec()) + .map(|u| { + let s = s.clone(); + async move { + let id = SpotifyUri::from_uri(&u).ok()?; + artist::Artist::get(&s, &id).await.ok().map(|a| artist_of(&a)) + } + }) + .buffered(12) + .filter_map(std::future::ready) + .collect() + .await + })) + } + + fn shows(&self, uris: &[String]) -> Result> { + let s = self.session()?; + Ok(self.engine.block(async { + futures_util::stream::iter(uris.to_vec()) + .map(|u| { + let s = s.clone(); + async move { + let id = SpotifyUri::from_uri(&u).ok()?; + show::Show::get(&s, &id).await.ok().map(|x| show_of(&x)) + } + }) + .buffered(8) + .filter_map(std::future::ready) + .collect() + .await + })) + } + + // ---- the collection (library) ---- + + /// Every uri of a collection set, newest first (cached a while). + fn set(&self, set: &str) -> Result> { + if let Some((at, list)) = self.cache.lock().unwrap().sets.get(set) { + if at.elapsed() < SETS_FOR { + return Ok(list.clone()); + } + } + let s = self.session()?; + let user = s.username(); + let mut items: Vec<(String, u64)> = Vec::new(); + let mut token = String::new(); + for _ in 0..40 { + let mut body = Vec::new(); + field_bytes(&mut body, 1, user.as_bytes()); + field_bytes(&mut body, 2, set.as_bytes()); + if !token.is_empty() { + field_bytes(&mut body, 3, token.as_bytes()); + } + field_varint(&mut body, 4, 300); + let b = self.engine.block(s.spclient().request(&Method::POST, "/collection/v2/paging", Some(collection_headers()), Some(&body))).map_err(e)?; + let (page, next) = parse_page(&b); + items.extend(page.into_iter().filter(|i| !i.2).map(|i| (i.0, i.1))); + if next.is_empty() { + break; + } + token = next; + } + items.sort_by(|a, b| b.1.cmp(&a.1)); + let list: Vec = items.into_iter().map(|i| i.0).collect(); + self.cache.lock().unwrap().sets.insert(set.to_string(), (Instant::now(), list.clone())); + Ok(list) + } + + fn set_of(&self, set: &str, prefix: &str) -> Result> { + Ok(self.set(set)?.into_iter().filter(|u| u.starts_with(prefix)).collect()) + } + + fn write(&self, set: &str, item: &str, on: bool) -> Result<()> { + let s = self.session()?; + let mut it = Vec::new(); + field_bytes(&mut it, 1, item.as_bytes()); + let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); + field_varint(&mut it, 2, now); + if !on { + field_varint(&mut it, 3, 1); + } + let mut body = Vec::new(); + field_bytes(&mut body, 1, s.username().as_bytes()); + field_bytes(&mut body, 2, set.as_bytes()); + field_bytes(&mut body, 3, &it); + self.engine.block(s.spclient().request(&Method::POST, "/collection/v2/write", Some(collection_headers()), Some(&body))).map_err(e)?; + // Keep the cached list in step. + if let Some((_, list)) = self.cache.lock().unwrap().sets.get_mut(set) { + list.retain(|u| u != item); + if on { + list.insert(0, item.to_string()); + } + } + Ok(()) + } + + fn contains(&self, set: &str, item: &str) -> Result { + Ok(self.set(set)?.iter().any(|u| u == item)) + } + + // ---- playlists ---- + + fn selected_list(&self, path: &str) -> Result { + let s = self.session()?; + let b = self.engine.block(s.spclient().request(&Method::GET, path, None, None)).map_err(e)?; + SelectedListContent::parse_from_bytes(&b).map_err(|x| anyhow!("playlist: {x}")) + } + + fn picture(attrs: &librespot_protocol::playlist4_external::ListAttributes) -> String { + let pic = attrs.picture(); + if pic.len() == 20 { + return image_url(&FileId::from(pic)); + } + attrs.picture_size.iter().find(|p| p.target_name() == "default").or_else(|| attrs.picture_size.first()).map(|p| p.url().to_string()).unwrap_or_default() + } + + /// A playlist without its own picture: Spotify's mosaic of the first + /// four album covers (or the first cover when there are fewer). + fn mosaic(&self, id: &str) -> String { + let Ok(r) = self.selected_list(&format!("/playlist/v2/playlist/{id}?from=0&length=12")) else { return String::new() }; + let uris: Vec = r.contents.get_or_default().items.iter().map(|i| i.uri().to_string()).filter(|u| u.starts_with("spotify:track:")).collect(); + let Ok(tracks) = self.tracks(&uris) else { return String::new() }; + let mut seen = HashSet::new(); + let covers: Vec = tracks + .iter() + .filter_map(|t| t.album.as_ref()) + .filter(|a| seen.insert(a.uri.clone())) + .filter_map(|a| a.images.iter().find(|i| i.width == Some(300)).or(a.images.first()).map(|i| i.url.rsplit('/').next().unwrap_or("").to_string())) + .take(4) + .collect(); + match covers.len() { + 0 => String::new(), + 4 => format!("https://mosaic.scdn.co/300/{}", covers.concat()), + _ => format!("https://i.scdn.co/image/{}", covers[0]), + } + } + + // ---- the Api methods ---- + + pub fn me(&self) -> Result { + let s = self.session()?; + let user = s.username(); + let profile = self.engine.block(s.spclient().get_user_profile(&user, Some(0), Some(0))).ok().and_then(|b| serde_json::from_slice::(&b).ok()).unwrap_or_default(); + let image = profile["image_url"].as_str().unwrap_or("").to_string(); + Ok(User { + id: user.clone(), + display_name: profile["name"].as_str().map(str::to_string), + product: s.get_user_attribute("type").unwrap_or_default(), + country: s.country(), + images: if image.is_empty() { Vec::new() } else { vec![Image { url: image, width: Some(300) }] }, + }) + } + + /// What was played lately: albums, playlists, artists, shows, the liked songs. + pub fn recent(&self) -> Result> { + let s = self.session()?; + let user = s.username(); + let path = format!("/recently-played/v3/user/{user}/recently-played?format=json&offset=0&limit=30&filter=default,collection-new-episodes"); + let b = self.engine.block(s.spclient().request_as_json(&Method::GET, &path, None, None)).map_err(e)?; + let v: serde_json::Value = serde_json::from_slice(&b)?; + let mut seen = HashSet::new(); + let uris: Vec = v["playContexts"].as_array().map(|a| a.iter().filter_map(|c| c["uri"].as_str().map(str::to_string)).filter(|u| seen.insert(u.clone())).take(16).collect()).unwrap_or_default(); + let mut out = Vec::new(); + for u in uris { + let kind = u.split(':').nth(1).unwrap_or(""); + let ent = match kind { + "album" => self.albums(std::slice::from_ref(&u))?.into_iter().next().map(Entity::Album), + "playlist" => self.playlist(u.rsplit(':').next().unwrap_or("")).ok().map(Entity::Playlist), + "artist" => self.artists(std::slice::from_ref(&u))?.into_iter().next().map(Entity::Artist), + "show" => self.shows(std::slice::from_ref(&u))?.into_iter().next().map(Entity::Show), + "user" if u.ends_with(":collection") => Some(Entity::Liked), + _ => None, + }; + if let Some(x) = ent { + out.push(x); + } + } + Ok(out) + } + + pub fn my_playlists(&self, offset: u32) -> Result> { + let s = self.session()?; + let user = s.username(); + let r = self.selected_list(&format!("/playlist/v2/user/{user}/rootlist?decorate=revision,attributes,length,owner,capabilities,status_code&from={offset}&length=50"))?; + let c = r.contents.get_or_default(); + let mut items = Vec::new(); + for (i, item) in c.items.iter().enumerate() { + let u = item.uri(); + if !u.starts_with("spotify:playlist:") { + continue; // folders + } + let meta = c.meta_items.get(i); + let attrs = meta.map(|m| m.attributes.get_or_default().clone()).unwrap_or_default(); + let pic = Self::picture(&attrs); + items.push(Some(Playlist { + id: u.rsplit(':').next().unwrap_or("").to_string(), + name: attrs.name().to_string(), + uri: u.to_string(), + images: if pic.is_empty() { None } else { Some(vec![Image { url: pic, width: Some(300) }]) }, + description: attrs.description().to_string(), + owner: api::Owner { id: meta.map(|m| m.owner_username().to_string()).unwrap_or_default(), display_name: None }, + tracks: Some(api::Total { total: meta.map(|m| m.length().max(0) as u32).unwrap_or(0) }), + ..Playlist::default() + })); + } + // Mosaics for the ones without a picture, a few at a time. + let missing: Vec = items.iter().enumerate().filter(|(_, p)| p.as_ref().is_some_and(|p| p.images.is_none())).map(|(i, _)| i).collect(); + for chunk in missing.chunks(6) { + let pics: Vec<(usize, String)> = std::thread::scope(|sc| { + let hs: Vec<_> = chunk.iter().map(|&i| { let id = items[i].as_ref().unwrap().id.clone(); sc.spawn(move || (i, self.mosaic(&id))) }).collect(); + hs.into_iter().filter_map(|h| h.join().ok()).collect() + }); + for (i, url) in pics.into_iter().filter(|p| !p.1.is_empty()) { + if let Some(p) = items[i].as_mut() { + p.images = Some(vec![Image { url, width: Some(300) }]); + } + } + } + let total = r.length().max(0) as u32; + let fetched = offset + c.items.len() as u32; + Ok(Paging { items, next: (fetched < total && !c.items.is_empty()).then(|| fetched.to_string()), total, offset }) + } + + pub fn playlist(&self, id: &str) -> Result { + let r = self.selected_list(&format!("/playlist/v2/playlist/{id}?from=0&length=0"))?; + let attrs = r.attributes.get_or_default(); + let mut pic = Self::picture(attrs); + if pic.is_empty() { + pic = self.mosaic(id); + } + Ok(Playlist { + id: id.to_string(), + name: attrs.name().to_string(), + uri: format!("spotify:playlist:{id}"), + images: if pic.is_empty() { None } else { Some(vec![Image { url: pic, width: Some(640) }]) }, + description: attrs.description().to_string(), + owner: api::Owner { id: r.owner_username().to_string(), display_name: None }, + tracks: Some(api::Total { total: r.length().max(0) as u32 }), + ..Playlist::default() + }) + } + + pub fn playlist_tracks(&self, id: &str, offset: u32) -> Result> { + let r = self.selected_list(&format!("/playlist/v2/playlist/{id}?from={offset}&length=100"))?; + let c = r.contents.get_or_default(); + let uris: Vec = c.items.iter().map(|i| i.uri().to_string()).collect(); + let total = r.length().max(0) as u32; + let items = self.tracks(&uris)?; + let fetched = offset + uris.len() as u32; + Ok(Paging { items: items.into_iter().map(Some).collect(), next: (fetched < total && !uris.is_empty()).then(|| fetched.to_string()), total, offset }) + } + + pub fn liked(&self, offset: u32) -> Result> { + let all = self.set_of("collection", "spotify:track:")?; + let page: Vec = all.iter().skip(offset as usize).take(50).cloned().collect(); + let items = self.tracks(&page)?; + let fetched = offset as usize + page.len(); + Ok(Paging { items: items.into_iter().map(Some).collect(), next: (fetched < all.len()).then(|| fetched.to_string()), total: all.len() as u32, offset }) + } + + pub fn saved_albums(&self, offset: u32) -> Result> { + let all = self.set_of("collection", "spotify:album:")?; + let page: Vec = all.iter().skip(offset as usize).take(50).cloned().collect(); + let items = self.albums(&page)?; + let fetched = offset as usize + page.len(); + Ok(Paging { items: items.into_iter().map(Some).collect(), next: (fetched < all.len()).then(|| fetched.to_string()), total: all.len() as u32, offset }) + } + + pub fn saved_shows(&self, offset: u32) -> Result> { + let all = self.set_of("show", "spotify:show:")?; + let page: Vec = all.iter().skip(offset as usize).take(50).cloned().collect(); + let items = self.shows(&page)?; + let fetched = offset as usize + page.len(); + Ok(Paging { items: items.into_iter().map(Some).collect(), next: (fetched < all.len()).then(|| fetched.to_string()), total: all.len() as u32, offset }) + } + + /// Followed artists; `after` is the number already shown. + pub fn followed_artists(&self, after: &str) -> Result<(Vec, Option)> { + let all = self.set_of("artist", "spotify:artist:")?; + let from: usize = after.parse().unwrap_or(0); + let page: Vec = all.iter().skip(from).take(50).cloned().collect(); + let items = self.artists(&page)?; + let next = from + page.len(); + Ok((items, (next < all.len()).then(|| next.to_string()))) + } + + pub fn liked_contains(&self, ids: &[String]) -> Result> { + let all: HashSet = self.set_of("collection", "spotify:track:")?.into_iter().collect(); + Ok(ids.iter().map(|id| all.contains(&format!("spotify:track:{id}"))).collect()) + } + pub fn set_liked(&self, id: &str, on: bool) -> Result<()> { + self.write("collection", &format!("spotify:track:{id}"), on) + } + pub fn album_saved(&self, id: &str) -> Result { + self.contains("collection", &format!("spotify:album:{id}")) + } + pub fn set_album_saved(&self, id: &str, on: bool) -> Result<()> { + self.write("collection", &format!("spotify:album:{id}"), on) + } + pub fn show_saved(&self, id: &str) -> Result { + self.contains("show", &format!("spotify:show:{id}")) + } + pub fn set_show_saved(&self, id: &str, on: bool) -> Result<()> { + self.write("show", &format!("spotify:show:{id}"), on) + } + pub fn following_artist(&self, id: &str) -> Result { + self.contains("artist", &format!("spotify:artist:{id}")) + } + pub fn set_following_artist(&self, id: &str, on: bool) -> Result<()> { + self.write("artist", &format!("spotify:artist:{id}"), on) + } + + pub fn album(&self, id: &str) -> Result { + let s = self.session()?; + let a = self.engine.block(album::Album::get(&s, &uri("album", id)?)).map_err(e)?; + let uris: Vec = a.discs.iter().flat_map(|d| d.tracks.iter()).filter_map(|t| t.to_uri().ok()).take(200).collect(); + let tracks = self.tracks(&uris)?; + let mut out = album_of(&a); + out.tracks = Some(Paging { total: tracks.len() as u32, items: tracks.into_iter().map(Some).collect(), next: None, offset: 0 }); + Ok(out) + } + + pub fn artist_page(&self, id: &str, country: &str) -> Result<(Artist, Vec, Vec, Vec, Vec)> { + let s = self.session()?; + let a = self.engine.block(artist::Artist::get(&s, &uri("artist", id)?)).map_err(e)?; + let country = if country.is_empty() { s.country() } else { country.to_string() }; + let top: Vec = a.top_tracks.for_country(&country).iter().filter_map(|t| t.to_uri().ok()).take(10).collect(); + let firsts = |g: &artist::AlbumGroups| -> Vec { g.iter().filter_map(|grp| grp.first().and_then(|u| u.to_uri().ok())).take(20).collect() }; + let mut appears = firsts(&a.appears_on_albums); + appears.extend(firsts(&a.compilations)); + appears.truncate(20); + Ok((artist_of(&a), self.tracks(&top)?, self.albums(&firsts(&a.albums))?, self.albums(&firsts(&a.singles))?, self.albums(&appears)?)) + } + + pub fn show(&self, id: &str) -> Result { + let s = self.session()?; + let x = self.engine.block(show::Show::get(&s, &uri("show", id)?)).map_err(e)?; + Ok(show_of(&x)) + } + + pub fn show_episodes(&self, id: &str, offset: u32) -> Result> { + let s = self.session()?; + let x = self.engine.block(show::Show::get(&s, &uri("show", id)?)).map_err(e)?; + let all: Vec = x.episodes.iter().filter_map(|u| u.to_uri().ok()).collect(); + let page: Vec = all.iter().skip(offset as usize).take(30).cloned().collect(); + let items = self.tracks(&page)?; + let fetched = offset as usize + page.len(); + Ok(Paging { items: items.into_iter().map(Some).collect(), next: (fetched < all.len()).then(|| fetched.to_string()), total: all.len() as u32, offset }) + } + + /// Songs for `q`; the artists and albums are the ones of those songs. + pub fn search(&self, q: &str) -> Result { + let s = self.session()?; + let ctx_uri = format!("spotify:search:{}", api::enc(q.trim()).replace("%20", "+")); + let ctx = self.engine.block(s.spclient().get_context(&ctx_uri)).map_err(e)?; + let uris: Vec = ctx.pages.iter().flat_map(|p| p.tracks.iter()).map(|t| t.uri().to_string()).filter(|u| u.starts_with("spotify:track:")).take(12).collect(); + let tracks = self.tracks(&uris)?; + let mut seen = HashSet::new(); + let artist_uris: Vec = tracks.iter().flat_map(|t| t.artists.iter()).map(|a| a.uri.clone()).filter(|u| !u.is_empty() && seen.insert(u.clone())).take(8).collect(); + let mut seen = HashSet::new(); + let albums: Vec = tracks.iter().filter_map(|t| t.album.clone()).filter(|a| !a.uri.is_empty() && seen.insert(a.uri.clone())).take(10).collect(); + Ok(SearchResult { artists: self.artists(&artist_uris)?, albums, tracks, playlists: Vec::new(), shows: Vec::new() }) + } + + /// Adds `uri` to the queue of this device (a Connect player command). + pub fn add_to_queue(&self, uri: &str) -> Result<()> { + let s = self.session()?; + let dev = s.device_id().to_string(); + let body = serde_json::json!({ + "command": { + "endpoint": "add_to_queue", + "track": { "uri": uri, "metadata": { "is_queued": "true" }, "provider": "queue" }, + } + }) + .to_string(); + let path = format!("/connect-state/v1/player/command/from/{dev}/to/{dev}"); + self.engine.block(s.spclient().request_as_json(&Method::POST, &path, None, Some(&body))).map_err(e)?; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn collection_pages_round_trip() { + // A PageResponse with two items (one removed) and a next token. + let mut item1 = Vec::new(); + field_bytes(&mut item1, 1, b"spotify:track:a"); + field_varint(&mut item1, 2, 1700); + let mut item2 = Vec::new(); + field_bytes(&mut item2, 1, b"spotify:album:b"); + field_varint(&mut item2, 3, 1); + let mut page = Vec::new(); + field_bytes(&mut page, 1, &item1); + field_bytes(&mut page, 1, &item2); + field_bytes(&mut page, 2, b"NEXT"); + let (items, next) = parse_page(&page); + assert_eq!(items, vec![("spotify:track:a".to_string(), 1700, false), ("spotify:album:b".to_string(), 0, true)]); + assert_eq!(next, "NEXT"); + let mut v = Vec::new(); + varint(&mut v, 300); + assert_eq!(v, vec![0xac, 0x02]); + } +} diff --git a/src/main.rs b/src/main.rs index 0a0c3b8..1ffaa06 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,13 +3,14 @@ //! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer; the page engine //! and controller come from Netflex TV. //! - Spotify: librespot (src/spotify.rs) for the session, Spotify Connect, -//! the zeroconf sign-in and playback; the Web API (src/api.rs) for -//! browsing. +//! the sign-in and playback; Spotify's internal endpoints through the +//! same session (src/internal.rs) for browsing. mod api; mod app; mod config; mod format; +mod internal; mod nowplaying; mod page; mod screens; diff --git a/src/nowplaying.rs b/src/nowplaying.rs index 41562f1..d62338b 100644 --- a/src/nowplaying.rs +++ b/src/nowplaying.rs @@ -1,13 +1,12 @@ //! Most szól: the big cover, the title, the progress, the controls (shuffle, -//! previous, play/pause, next, repeat, like, lyrics, queue), synced lyrics -//! and the queue. Also keeps the playback state that the engine reports +//! previous, play/pause, next, repeat, like, lyrics) and synced lyrics. +//! Also keeps the playback state that the engine reports //! (pages show it in the "now playing" capsule of the nav). //! //! Keys: left/right between the buttons, OK presses one, up goes to the //! progress bar (left/right seek there), Back returns to the pages. Space //! (play/pause on a keyboard) works everywhere. -use std::rc::Rc; use std::time::{Duration, Instant}; use slint::{Model, ModelRc, VecModel}; @@ -15,10 +14,10 @@ use slint::{Model, ModelRc, VecModel}; use crate::api; use crate::app::{Action, Controller, Look}; use crate::spotify::{Cmd, Event, Track}; -use crate::{QueueItem, format, task}; +use crate::{format, task}; /// The buttons, left to right. -const BUTTONS: [&str; 8] = ["shuffle", "prev", "play", "next", "repeat", "like", "lyrics", "queue"]; +const BUTTONS: [&str; 7] = ["shuffle", "prev", "play", "next", "repeat", "like", "lyrics"]; const PLAY: usize = 2; #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -26,7 +25,6 @@ pub enum Panel { #[default] None, Lyrics, - Queue, } #[derive(Default)] @@ -42,7 +40,6 @@ pub struct NowPlaying { /// (track id, lines, synced); empty lines = none. lyrics: Option<(String, Vec<(u32, String)>, bool)>, lyrics_loading: bool, - queue: Vec, panel: Panel, focus: usize, /// 0: the buttons, 1: the progress bar. @@ -137,7 +134,7 @@ pub fn on_event(c: &Controller, ev: Event) { c.track_changed(); } -/// A new track: its cover behind the screen, its like state, lyrics, queue. +/// A new track: its cover behind the screen, its like state, lyrics. fn track_changed(c: &Controller) { let (track, panel) = { let st = c.state.borrow(); @@ -168,7 +165,6 @@ fn track_changed(c: &Controller) { } match panel { Panel::Lyrics => load_lyrics(c), - Panel::Queue => load_queue(c), Panel::None => {} } } @@ -231,48 +227,6 @@ fn load_lyrics(c: &Controller) { ); } -fn load_queue(c: &Controller) { - let api = c.api(); - let c2 = c.clone(); - task::spawn( - move || api.queue(), - move |r| { - match r { - Ok(q) => c2.state.borrow_mut().np.queue = q, - Err(e) => log::info!("queue: {e:#}"), - } - sync_queue(&c2); - }, - ); -} - -fn sync_queue(c: &Controller) { - let Some(ui) = c.ui() else { return }; - let queue = c.state.borrow().np.queue.clone(); - let model = Rc::new(VecModel::from( - queue - .iter() - .take(30) - .map(|t| QueueItem { title: t.name.clone().into(), artist: t.artist_names().into(), image: Default::default() }) - .collect::>(), - )); - ui.set_np_queue(ModelRc::from(model.clone())); - let px = c.px(); - for (i, t) in queue.iter().take(12).enumerate() { - let url = t.image(64); - if url.is_empty() { - continue; - } - let m = model.clone(); - c.images.load(&url, ((64.0 * px) as u32, (64.0 * px) as u32), move |img| { - if let Some(mut row) = m.row_data(i) { - row.image = img; - m.set_row_data(i, row); - } - }); - } -} - /// Shows the screen. pub fn open(c: &Controller) { { @@ -293,7 +247,6 @@ pub fn open(c: &Controller) { let panel = c.state.borrow().np.panel; match panel { Panel::Lyrics => load_lyrics(c), - Panel::Queue => load_queue(c), Panel::None => {} } let k = c.clone(); @@ -429,13 +382,6 @@ fn press(c: &Controller, button: &str) { load_lyrics(c); } } - "queue" => { - let next = if panel == Panel::Queue { Panel::None } else { Panel::Queue }; - c.state.borrow_mut().np.panel = next; - if next == Panel::Queue { - load_queue(c); - } - } _ => {} } sync(c); @@ -479,7 +425,6 @@ pub fn sync(c: &Controller) { ui.set_np_panel(match np.panel { Panel::None => 0, Panel::Lyrics => 1, - Panel::Queue => 2, }); let device = if !np.elsewhere.is_empty() && !np.playing { format!("Irányítja: {}", np.elsewhere) } else { format!("Lejátszás itt: {}", st.cfg.device_name) }; ui.set_np_device(device.into()); @@ -496,11 +441,6 @@ pub fn sync(c: &Controller) { ui.set_np_lyrics(ModelRc::new(VecModel::from(lines))); } ui.set_np_lyrics_note(note.into()); - if np.panel == Panel::Queue && np.queue.is_empty() { - ui.set_np_queue_note("A lejátszási sor üres.".into()); - } else { - ui.set_np_queue_note("".into()); - } } sync_time(c); } diff --git a/src/screens/artist.rs b/src/screens/artist.rs index 18182f7..50e1a6b 100644 --- a/src/screens/artist.rs +++ b/src/screens/artist.rs @@ -37,15 +37,8 @@ impl ArtistPage { let market = cx.user().country; cx.spawn::( move || -> anyhow::Result<(Data, Option)> { - let artist = api.artist(&id)?; - let (top, albums, singles, appears, following) = std::thread::scope(|s| { - let top = s.spawn(|| api.artist_top(&id, &market).unwrap_or_default()); - let albums = s.spawn(|| api.artist_albums(&id, "album").unwrap_or_default()); - let singles = s.spawn(|| api.artist_albums(&id, "single").unwrap_or_default()); - let appears = s.spawn(|| api.artist_albums(&id, "appears_on,compilation").unwrap_or_default()); - let following = s.spawn(|| api.following_artist(&id).ok()); - (top.join().unwrap_or_default(), albums.join().unwrap_or_default(), singles.join().unwrap_or_default(), appears.join().unwrap_or_default(), following.join().ok().flatten()) - }); + let (artist, top, albums, singles, appears) = api.artist_page(&id, &market)?; + let following = api.following_artist(&id).ok(); Ok((Data { artist, top, albums, singles, appears }, following)) }, |s, cx, r| match r { @@ -76,6 +69,7 @@ impl Screen for ArtistPage { hero.style = "ELŐADÓ".into(); hero.title = a.name.clone(); hero.subtitle = a.followers.as_ref().map(|f| format::followers(f.total)).unwrap_or_default(); + hero.meta = a.genres.iter().take(4).cloned().collect::>().join(" · "); let mut chips = vec![Ch::new("play", "Lejátszás").icon("play").tone("primary"), Ch::new("shuffle", "Keverés").icon("shuffle")]; if let Some(f) = self.following { diff --git a/src/screens/home.rs b/src/screens/home.rs index afe3b59..6831862 100644 --- a/src/screens/home.rs +++ b/src/screens/home.rs @@ -1,23 +1,22 @@ -//! Kezdőlap: rows: recently played, your playlists (with the -//! liked songs first), your top artists and tracks, saved albums, new -//! releases. Every row loads on its own; a failing one just stays away. +//! Kezdőlap: rows: recently played (albums, playlists, artists...), your +//! playlists (with the liked songs first), your artists, saved albums, your +//! podcasts. Every row loads on its own; a failing one just stays away. use std::any::Any; -use crate::api::{Album, Artist, Playlist, Played, Track}; +use crate::api::{self, Album, Artist, Entity, Playlist, Show}; use crate::app::{Cx, Look, Screen}; -use crate::page::{Frame, L, Spec}; -use crate::screens::{self, album_card, artist_card, liked_card, playlist_card, track_card}; +use crate::page::{C, Frame, L, Spec}; +use crate::screens::{self, album_card, artist_card, liked_card, playlist_card, show_card}; #[derive(Default)] struct Data { - recent: Option>, + recent: Option>, playlists: Option>, liked_total: Option, - top_artists: Option>, - top_tracks: Option>, + artists: Option>, albums: Option>, - releases: Option>, + shows: Option>, errors: Vec, } @@ -38,34 +37,41 @@ impl Home { cx.spawn::( move || { std::thread::scope(|s| { - let recent = s.spawn(|| api.recently_played()); + let recent = s.spawn(|| api.recent()); let playlists = s.spawn(|| api.my_playlists(0)); let liked = s.spawn(|| api.liked(0)); - let artists = s.spawn(|| api.top_artists()); - let tracks = s.spawn(|| api.top_tracks()); + let artists = s.spawn(|| api.followed_artists("")); let albums = s.spawn(|| api.saved_albums(0)); - let releases = s.spawn(|| api.new_releases()); - let mut d = Data::default(); - let e = &mut d.errors; + let shows = s.spawn(|| api.saved_shows(0)); + let mut errors = Vec::new(); + let e = &mut errors; let recent = keep(recent.join(), e); let playlists = keep(playlists.join(), e).map(|p| p.list()); let liked_total = keep(liked.join(), e).map(|p| p.total); - let top_artists = keep(artists.join(), e); - let top_tracks = keep(tracks.join(), e); + let artists = keep(artists.join(), e).map(|a| a.0); let albums = keep(albums.join(), e).map(|p| p.list()); - let releases = keep(releases.join(), e); - Data { recent, playlists, liked_total, top_artists, top_tracks, albums, releases, ..d } + let shows = keep(shows.join(), e).map(|p| p.list()); + Data { recent, playlists, liked_total, artists, albums, shows, errors } }) }, |s, cx, d| { s.data = d; s.loading = false; // The first picture of the page tints the background. - let first = s.data.recent.as_ref().and_then(|r| r.first()).map(|p| p.track.image(640)).unwrap_or_default(); - cx.backdrop(&first, Look::Soft, "home"); + cx.backdrop(&s.first_image(), Look::Soft, "home"); }, ); } + + fn first_image(&self) -> String { + match self.data.recent.as_ref().and_then(|r| r.first()) { + Some(Entity::Album(a)) => api::pick(&a.images, 640), + Some(Entity::Playlist(p)) => p.image(640), + Some(Entity::Artist(a)) => api::pick(&a.images, 640), + Some(Entity::Show(s)) => api::pick(&s.images, 640), + _ => String::new(), + } + } } /// A row's result: the data, or its error noted. @@ -81,18 +87,16 @@ fn keep(r: std::thread::Result>, errors: &mut Vec) } } -/// Recently played tracks, each once (newest first). -fn recent_cards(items: &[Played]) -> Vec { - let mut seen = std::collections::HashSet::new(); - items - .iter() - .filter(|p| seen.insert(p.track.uri.clone())) - .take(20) - .map(|p| track_card(&p.track, p.context.as_ref().map(|c| c.uri.as_str()).unwrap_or(""))) - .collect() +fn entity_card(e: &Entity, liked_total: Option) -> C { + match e { + Entity::Album(a) => album_card(a), + Entity::Playlist(p) => playlist_card(p), + Entity::Artist(a) => artist_card(a), + Entity::Show(s) => show_card(s), + Entity::Liked => liked_card(liked_total), + } } - impl Screen for Home { fn spec(&mut self, cx: &Cx) -> Spec { if !self.started { @@ -107,45 +111,33 @@ impl Screen for Home { } let d = &self.data; if let Some(r) = d.recent.as_ref().filter(|r| !r.is_empty()) { - lines.push(L::cards("recent", "Legutóbb játszott", "square", recent_cards(r)).captions()); + lines.push(L::cards("recent", "Legutóbb játszott", "square", r.iter().map(|e| entity_card(e, d.liked_total)).collect()).captions()); } let mut pl = vec![liked_card(d.liked_total)]; pl.extend(d.playlists.iter().flatten().map(playlist_card)); lines.push(L::cards("playlists", "Lejátszási listáid", "square", pl).captions()); - if let Some(a) = d.top_artists.as_ref().filter(|a| !a.is_empty()) { - lines.push(L::cards("artists", "Kedvenc előadóid", "round", a.iter().map(artist_card).collect()).captions()); - } - if let Some(t) = d.top_tracks.as_ref().filter(|t| !t.is_empty()) { - lines.push(L::cards("top", "Mostanában sokat hallgatod", "square", t.iter().map(|t| track_card(t, "")).collect()).captions()); + if let Some(a) = d.artists.as_ref().filter(|a| !a.is_empty()) { + lines.push(L::cards("artists", "Előadóid", "round", a.iter().take(30).map(artist_card).collect()).captions()); } if let Some(a) = d.albums.as_ref().filter(|a| !a.is_empty()) { - lines.push(L::cards("albums", "Elmentett albumaid", "square", a.iter().map(album_card).collect()).captions()); + lines.push(L::cards("albums", "Elmentett albumaid", "square", a.iter().take(30).map(album_card).collect()).captions()); } - if let Some(a) = d.releases.as_ref().filter(|a| !a.is_empty()) { - lines.push(L::cards("releases", "Új megjelenések", "square", a.iter().map(album_card).collect()).captions()); + if let Some(s) = d.shows.as_ref().filter(|s| !s.is_empty()) { + lines.push(L::cards("shows", "Podcastjaid", "square", s.iter().map(show_card).collect()).captions()); } - if d.recent.is_none() && d.playlists.is_none() && d.top_artists.is_none() { + if d.recent.is_none() && d.playlists.is_none() && d.artists.is_none() { let why = d.errors.first().cloned().unwrap_or_default(); lines.push(L::notice("error", "bad", "Nem sikerült betölteni a kezdőlapot", why)); } Spec { lines, frame } } - fn activate(&mut self, cx: &Cx, line: &str, item: &str) { - if line == "top" { - // Top tracks play as a list, from the chosen one. - if let Some(t) = &self.data.top_tracks { - let i = t.iter().position(|x| item == format!("t:{}|", x.uri)).unwrap_or(0); - screens::play_from(cx, "", t, i); - return; - } - } + fn activate(&mut self, cx: &Cx, _line: &str, item: &str) { screens::open_card(cx, item); } fn shown(&mut self, cx: &Cx) { - let first = self.data.recent.as_ref().and_then(|r| r.first()).map(|p| p.track.image(640)).unwrap_or_default(); - cx.backdrop(&first, Look::Soft, "home"); + cx.backdrop(&self.first_image(), Look::Soft, "home"); } fn as_any(&mut self) -> &mut dyn Any { diff --git a/src/screens/mod.rs b/src/screens/mod.rs index d2af8c0..347ec30 100644 --- a/src/screens/mod.rs +++ b/src/screens/mod.rs @@ -100,14 +100,6 @@ pub fn show_card(s: &Show) -> C { c } -/// A track as a card (album art): plays it, in `context` if given. -pub fn track_card(t: &Track, context: &str) -> C { - let mut c = C::new(format!("t:{}|{context}", t.uri), t.name.clone(), t.image(CARD_IMG)); - c.caption = t.name.clone(); - c.detail = t.artist_names(); - c -} - pub fn liked_card(total: Option) -> C { let mut c = C::new("liked", "Kedvelt dalok", ""); c.caption = "Kedvelt dalok".into(); diff --git a/src/screens/search.rs b/src/screens/search.rs index b959029..147c9f0 100644 --- a/src/screens/search.rs +++ b/src/screens/search.rs @@ -21,7 +21,7 @@ impl Search { impl Screen for Search { fn spec(&mut self, cx: &Cx) -> Spec { - let mut lines = vec![L::page_title("title", "Mit hallgatnál?", "Dalok, előadók, albumok, lejátszási listák és podcastok."), L::new("kb", Kind::Keyboard)]; + let mut lines = vec![L::page_title("title", "Mit hallgatnál?", "Dalok, előadók és albumok."), L::new("kb", Kind::Keyboard)]; match &self.result { None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "Két betű elég.")), Some(Load::Loading) => lines.push(L::text("loading", "Keresés…", "caption")), diff --git a/src/spotify.rs b/src/spotify.rs index 363d84a..83b284f 100644 --- a/src/spotify.rs +++ b/src/spotify.rs @@ -185,7 +185,12 @@ impl Engine { let _ = self.cmd.send(c); } - fn session(&self) -> anyhow::Result { + /// Runs `f` on the engine's runtime and waits (blocking; off the UI thread). + pub fn block(&self, f: F) -> F::Output { + self.rt.block_on(f) + } + + pub fn session(&self) -> anyhow::Result { self.session.lock().unwrap().clone().filter(|s| !s.is_invalid()).ok_or_else(|| anyhow::anyhow!("Nincs kapcsolat a Spotifyjal")) } @@ -195,7 +200,20 @@ impl Engine { return Ok("mock".into()); } let s = self.session()?; - let t = self.rt.block_on(async move { tokio::time::timeout(Duration::from_secs(15), s.token_provider().get_token(SCOPES)).await }); + // login5 first: what Spotify's own clients use now. The old keymaster + // endpoint answers 403 for most accounts; it is only the fallback. + let t = self.rt.block_on(async move { + tokio::time::timeout(Duration::from_secs(15), async { + match s.login5().auth_token().await { + Ok(t) => Ok(t), + Err(e) => { + log::warn!("login5 token: {e}"); + s.token_provider().get_token(SCOPES).await + } + } + }) + .await + }); match t { Ok(Ok(t)) => Ok(t.access_token), Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")), diff --git a/ui/app.slint b/ui/app.slint index 2fdc011..988a28a 100644 --- a/ui/app.slint +++ b/ui/app.slint @@ -139,8 +139,6 @@ export component App inherits TvWindow { in property np-lyric-line <=> np.lyric-line; in property np-lyrics-synced <=> np.lyrics-synced; in property np-lyrics-note <=> np.lyrics-note; - in property <[QueueItem]> np-queue <=> np.queue; - in property np-queue-note <=> np.queue-note; in property np-device <=> np.device; np := NowPlayingScreen { alpha: root.vis(root.np-t) * root.under; diff --git a/ui/nowplaying.slint b/ui/nowplaying.slint index c9e9f83..c4e5760 100644 --- a/ui/nowplaying.slint +++ b/ui/nowplaying.slint @@ -1,12 +1,11 @@ // Most szól: the cover, the title, the progress and the controls. With the -// lyrics or the queue open, the cover and the texts move to the left and a -// glass panel holds the lyrics / the queue on the right. +// lyrics open, the cover and the texts move to the left and a glass panel +// holds the lyrics on the right. // -// Rust owns the focus: `button` is the focused button (0..7), `area` 1 means +// Rust owns the focus: `button` is the focused button (0..6), `area` 1 means // the progress bar (left/right seek there). import { Tv, GlassRect, GlassPane, Spinner, Caption } from "@sf-ui/sf-ui.slint"; -import { QueueItem } from "types.slint"; import { SpIcon } from "icons.slint"; import { Accent, Equalizer } from "page.slint"; @@ -73,14 +72,12 @@ export component NowPlayingScreen inherits Rectangle { in property liked: -1; in property button: 2; in property area; - // 0 none, 1 lyrics, 2 queue + // 0 none, 1 lyrics in property panel; in property <[string]> lyrics; in property lyric-line: -1; in property lyrics-synced; in property lyrics-note; - in property <[QueueItem]> queue; - in property queue-note; in property device; // 0: the big layout, 1: side by side with the panel. @@ -269,9 +266,8 @@ export component NowPlayingScreen inherits Rectangle { Rectangle { width: root.mix(24, 6); } b5 := NpButton { y: (parent.height - self.height) / 2; icon: root.liked == 1 ? "heart-filled" : "heart"; size: root.bs; on: root.liked == 1; focused: root.area == 0 && root.button == 5; alpha: root.alpha * (root.liked < 0 ? 0.4 : 1); } b6 := NpButton { y: (parent.height - self.height) / 2; icon: "lyrics"; size: root.bs; on: root.panel == 1; focused: root.area == 0 && root.button == 6; alpha: root.alpha; } - b7 := NpButton { y: (parent.height - self.height) / 2; icon: "queue"; size: root.bs; on: root.panel == 2; focused: root.area == 0 && root.button == 7; alpha: root.alpha; } } - property <[string]> hints: ["Keverés", "Előző", root.playing ? "Szünet" : "Lejátszás", "Következő", "Ismétlés", "Kedvelés", "Dalszöveg", "Lejátszási sor"]; + property <[string]> hints: ["Keverés", "Előző", root.playing ? "Szünet" : "Lejátszás", "Következő", "Ismétlés", "Kedvelés", "Dalszöveg"]; Caption { x: root.tx; y: controls.y + controls.height + 18 * Tv.u; @@ -280,7 +276,7 @@ export component NowPlayingScreen inherits Rectangle { opacity: root.alpha; } - // ---- the panel: lyrics or the queue ---- + // ---- the panel: lyrics ---- property pa: root.alpha * clamp(root.t * 1.6 - 0.6, 0, 1); panel-pane := GlassPane { x: 820 * Tv.u; @@ -323,66 +319,6 @@ export component NowPlayingScreen inherits Rectangle { wrap: word-wrap; } } - // queue - if root.panel == 2: Rectangle { - clip: true; - opacity: root.pa; - Text { - x: 56 * Tv.u; - y: 44 * Tv.u; - text: "Következik"; - font-size: 38 * Tv.u; - font-weight: 700; - color: Tv.text; - } - for q[i] in root.queue: Rectangle { - x: 56 * Tv.u; - y: (120 + i * 84) * Tv.u; - width: parent.width - 112 * Tv.u; - height: 72 * Tv.u; - Rectangle { - x: 0; - width: 64 * Tv.u; - height: 64 * Tv.u; - y: 4 * Tv.u; - border-radius: 8 * Tv.u; - clip: true; - background: #1b1d24; - Image { - width: 100%; - height: 100%; - source: q.image; - image-fit: cover; - } - } - Text { - x: 88 * Tv.u; - y: 6 * Tv.u; - width: parent.width - 88 * Tv.u; - text: q.title; - font-size: 26 * Tv.u; - font-weight: 600; - color: Tv.text; - overflow: elide; - } - Text { - x: 88 * Tv.u; - y: 40 * Tv.u; - width: parent.width - 88 * Tv.u; - text: q.artist; - font-size: 21 * Tv.u; - color: Tv.text-tertiary; - overflow: elide; - } - } - if root.queue-note != "": Text { - x: 56 * Tv.u; - y: 130 * Tv.u; - text: root.queue-note; - font-size: 26 * Tv.u; - color: Tv.text-secondary; - } - } } out property <[GlassRect]> glass: [ @@ -399,7 +335,7 @@ export component NowPlayingScreen inherits Rectangle { tint: #ffffff.with-alpha(0.14 + 0.1 * root.pf), group: 0, }, - b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, b6.glass, b7.glass, + b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, b6.glass, panel-pane.glass, ]; }