0.1.1: browse through Spotify's internal endpoints
Some checks failed
release / release (push) Failing after 13s
Some checks failed
release / release (push) Failing after 13s
The public Web API answers librespot's client id with 429 on every call (and the old keymaster token endpoint with 403), so every page failed. Browsing now goes through the same librespot session as playback: metadata, /playlist/v2 (rootlist and lists), /collection/v2 (liked songs, saved albums, followed artists and podcasts; save and like too), recently played, the search context, and a Connect command for the queue. - Home: recently played albums/playlists/artists, your playlists, your artists, saved albums, podcasts (no top lists or new releases there). - Search finds songs; artists and albums come from them. - Playlists without a picture get Spotify's mosaic cover. - The queue panel is gone (the internal API does not show the queue). - The Web API client stays for the mock server only. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
10
AGENTS.md
10
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)
|
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/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/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/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/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
|
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
|
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/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/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/signin.slint ConnectScreen (QR code + Spotify app), InputScreen, MessageScreen
|
||||||
ui/icons.slint SpIcon: shuffle, repeat, heart, lyrics, queue, devices (+ sf-ui's icons)
|
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)
|
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
|
## 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.
|
- **Rust owns state and focus.** Slint only draws. Every key goes to `Controller::key`, except while an on-screen keyboard has the focus.
|
||||||
|
|||||||
5
Cargo.lock
generated
5
Cargo.lock
generated
@@ -6659,17 +6659,20 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "spotify-tv"
|
name = "spotify-tv"
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"env_logger",
|
"env_logger",
|
||||||
"futures-util",
|
"futures-util",
|
||||||
|
"hyper",
|
||||||
"librespot-connect",
|
"librespot-connect",
|
||||||
"librespot-core",
|
"librespot-core",
|
||||||
"librespot-discovery",
|
"librespot-discovery",
|
||||||
"librespot-metadata",
|
"librespot-metadata",
|
||||||
"librespot-playback",
|
"librespot-playback",
|
||||||
|
"librespot-protocol",
|
||||||
"log",
|
"log",
|
||||||
|
"protobuf",
|
||||||
"qrcode",
|
"qrcode",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "spotify-tv"
|
name = "spotify-tv"
|
||||||
description = "Spotify for Fennec OS: native TV client with Liquid Glass, Spotify Connect and librespot playback"
|
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"
|
edition = "2024"
|
||||||
# sf-ui (and Slint) are GPL-3.0 on a TV box; librespot is MIT.
|
# sf-ui (and Slint) are GPL-3.0 on a TV box; librespot is MIT.
|
||||||
license = "GPL-3.0-only"
|
license = "GPL-3.0-only"
|
||||||
@@ -19,7 +19,11 @@ serde_json = "1"
|
|||||||
toml = "0.9"
|
toml = "0.9"
|
||||||
ureq = { version = "3", features = ["json"] }
|
ureq = { version = "3", features = ["json"] }
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "signal"] }
|
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.
|
# The pairing QR code on the sign-in screen.
|
||||||
qrcode = { version = "0.14", default-features = false }
|
qrcode = { version = "0.14", default-features = false }
|
||||||
# Spotify: session, Connect (Spirc), zeroconf sign-in, playback.
|
# Spotify: session, Connect (Spirc), zeroconf sign-in, playback.
|
||||||
|
|||||||
@@ -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 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`).
|
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.
|
- **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, lejátszási sor. A dalsorok „+” gombja: sorba tétel, kedvelés, album, előadó.
|
- **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).
|
- **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
|
## Fejlesztés
|
||||||
|
|
||||||
|
|||||||
2
app.toml
2
app.toml
@@ -2,7 +2,7 @@
|
|||||||
id = "support.bluefox.spotify"
|
id = "support.bluefox.spotify"
|
||||||
name = "Spotify"
|
name = "Spotify"
|
||||||
# Release versions only (1.2.3). Bump it (and Cargo.toml) for every release.
|
# Release versions only (1.2.3). Bump it (and Cargo.toml) for every release.
|
||||||
version = "0.1.0"
|
version = "0.1.1"
|
||||||
kind = "exec"
|
kind = "exec"
|
||||||
category = "Zene"
|
category = "Zene"
|
||||||
description = "Zene és podcastok natívan, Spotify Connecttel: a telefonról is irányítható. Spotify Premium fiók kell hozzá."
|
description = "Zene és podcastok natívan, Spotify Connecttel: a telefonról is irányítható. Spotify Premium fiók kell hozzá."
|
||||||
|
|||||||
180
src/api.rs
180
src/api.rs
@@ -1,5 +1,10 @@
|
|||||||
//! Spotify Web API (api.spotify.com/v1): browsing, the library, search, the
|
//! The data behind the pages: Spotify's objects (as the Web API shapes them)
|
||||||
//! queue. The access token comes from the librespot session (spotify::Engine).
|
//! 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
|
//! Every answer is parsed leniently (missing fields default), since Spotify's
|
||||||
//! objects differ a bit between endpoints. GET answers are cached for a short
|
//! objects differ a bit between endpoints. GET answers are cached for a short
|
||||||
@@ -252,6 +257,20 @@ pub struct Played {
|
|||||||
pub context: Option<PlayContext>,
|
pub context: Option<PlayContext>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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<Track>, Vec<Album>, Vec<Album>, Vec<Album>);
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct SearchResult {
|
pub struct SearchResult {
|
||||||
pub tracks: Vec<Track>,
|
pub tracks: Vec<Track>,
|
||||||
@@ -313,15 +332,127 @@ pub fn enc(s: &str) -> String {
|
|||||||
|
|
||||||
/// Cheap to clone; usable from any thread (blocking calls).
|
/// Cheap to clone; usable from any thread (blocking calls).
|
||||||
#[derive(Clone)]
|
#[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<User> {
|
||||||
|
both!(self, me())
|
||||||
|
}
|
||||||
|
pub fn recent(&self) -> Result<Vec<Entity>> {
|
||||||
|
both!(self, recent())
|
||||||
|
}
|
||||||
|
pub fn my_playlists(&self, offset: u32) -> Result<Paging<Playlist>> {
|
||||||
|
both!(self, my_playlists(offset))
|
||||||
|
}
|
||||||
|
pub fn liked(&self, offset: u32) -> Result<Paging<Track>> {
|
||||||
|
both!(self, liked(offset))
|
||||||
|
}
|
||||||
|
pub fn saved_albums(&self, offset: u32) -> Result<Paging<Album>> {
|
||||||
|
both!(self, saved_albums(offset))
|
||||||
|
}
|
||||||
|
pub fn saved_shows(&self, offset: u32) -> Result<Paging<Show>> {
|
||||||
|
both!(self, saved_shows(offset))
|
||||||
|
}
|
||||||
|
pub fn followed_artists(&self, after: &str) -> Result<(Vec<Artist>, Option<String>)> {
|
||||||
|
both!(self, followed_artists(after))
|
||||||
|
}
|
||||||
|
pub fn liked_contains(&self, ids: &[String]) -> Result<Vec<bool>> {
|
||||||
|
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<bool> {
|
||||||
|
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<bool> {
|
||||||
|
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<bool> {
|
||||||
|
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<bool> {
|
||||||
|
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<Playlist> {
|
||||||
|
both!(self, playlist(id))
|
||||||
|
}
|
||||||
|
pub fn playlist_tracks(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
|
||||||
|
both!(self, playlist_tracks(id, offset))
|
||||||
|
}
|
||||||
|
pub fn album(&self, id: &str) -> Result<Album> {
|
||||||
|
both!(self, album(id))
|
||||||
|
}
|
||||||
|
pub fn album_tracks(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
|
||||||
|
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<ArtistPage> {
|
||||||
|
both!(self, artist_page(id, country))
|
||||||
|
}
|
||||||
|
pub fn show(&self, id: &str) -> Result<Show> {
|
||||||
|
both!(self, show(id))
|
||||||
|
}
|
||||||
|
pub fn show_episodes(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
|
||||||
|
both!(self, show_episodes(id, offset))
|
||||||
|
}
|
||||||
|
pub fn search(&self, q: &str) -> Result<SearchResult> {
|
||||||
|
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,
|
base: String,
|
||||||
engine: Engine,
|
engine: Engine,
|
||||||
agent: ureq::Agent,
|
agent: ureq::Agent,
|
||||||
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
|
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Api {
|
impl Web {
|
||||||
pub fn new(engine: Engine) -> Api {
|
pub fn new(engine: Engine) -> Web {
|
||||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||||
.timeout_global(Some(Duration::from_secs(30)))
|
.timeout_global(Some(Duration::from_secs(30)))
|
||||||
.timeout_connect(Some(Duration::from_secs(8)))
|
.timeout_connect(Some(Duration::from_secs(8)))
|
||||||
@@ -330,7 +461,7 @@ impl Api {
|
|||||||
.build()
|
.build()
|
||||||
.into();
|
.into();
|
||||||
let base = std::env::var("SPOTIFY_API").unwrap_or_else(|_| API.to_string());
|
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).
|
/// Forgets cached answers (after a change to the library).
|
||||||
@@ -427,6 +558,11 @@ impl Api {
|
|||||||
|
|
||||||
// ---- home ----
|
// ---- home ----
|
||||||
|
|
||||||
|
pub fn recent(&self) -> Result<Vec<Entity>> {
|
||||||
|
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<Vec<Played>> {
|
pub fn recently_played(&self) -> Result<Vec<Played>> {
|
||||||
#[derive(Deserialize, Default)]
|
#[derive(Deserialize, Default)]
|
||||||
#[serde(default)]
|
#[serde(default)]
|
||||||
@@ -435,20 +571,6 @@ impl Api {
|
|||||||
}
|
}
|
||||||
Ok(self.get::<R>("/me/player/recently-played?limit=50")?.items)
|
Ok(self.get::<R>("/me/player/recently-played?limit=50")?.items)
|
||||||
}
|
}
|
||||||
pub fn top_artists(&self) -> Result<Vec<Artist>> {
|
|
||||||
Ok(self.get::<Paging<Artist>>("/me/top/artists?limit=20&time_range=short_term")?.list())
|
|
||||||
}
|
|
||||||
pub fn top_tracks(&self) -> Result<Vec<Track>> {
|
|
||||||
Ok(self.get::<Paging<Track>>("/me/top/tracks?limit=20&time_range=short_term")?.list())
|
|
||||||
}
|
|
||||||
pub fn new_releases(&self) -> Result<Vec<Album>> {
|
|
||||||
#[derive(Deserialize, Default)]
|
|
||||||
#[serde(default)]
|
|
||||||
struct R {
|
|
||||||
albums: Paging<Album>,
|
|
||||||
}
|
|
||||||
Ok(self.get::<R>("/browse/new-releases?limit=20")?.albums.list())
|
|
||||||
}
|
|
||||||
|
|
||||||
// ---- library ----
|
// ---- library ----
|
||||||
|
|
||||||
@@ -567,6 +689,14 @@ impl Api {
|
|||||||
pub fn artist_albums(&self, id: &str, groups: &str) -> Result<Vec<Album>> {
|
pub fn artist_albums(&self, id: &str, groups: &str) -> Result<Vec<Album>> {
|
||||||
Ok(self.get::<Paging<Album>>(&format!("/artists/{id}/albums?include_groups={groups}&limit=30"))?.list())
|
Ok(self.get::<Paging<Album>>(&format!("/artists/{id}/albums?include_groups={groups}&limit=30"))?.list())
|
||||||
}
|
}
|
||||||
|
pub fn artist_page(&self, id: &str, country: &str) -> Result<ArtistPage> {
|
||||||
|
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<Show> {
|
pub fn show(&self, id: &str) -> Result<Show> {
|
||||||
self.get(&format!("/shows/{id}"))
|
self.get(&format!("/shows/{id}"))
|
||||||
}
|
}
|
||||||
@@ -592,16 +722,6 @@ impl Api {
|
|||||||
|
|
||||||
// ---- player ----
|
// ---- player ----
|
||||||
|
|
||||||
/// What comes next on the active device.
|
|
||||||
pub fn queue(&self) -> Result<Vec<Track>> {
|
|
||||||
#[derive(Deserialize, Default)]
|
|
||||||
#[serde(default)]
|
|
||||||
struct R {
|
|
||||||
queue: Vec<Track>,
|
|
||||||
}
|
|
||||||
let text = self.call("GET", "/me/player/queue", false)?;
|
|
||||||
Ok(serde_json::from_str::<R>(&text).unwrap_or_default().queue)
|
|
||||||
}
|
|
||||||
pub fn add_to_queue(&self, uri: &str) -> Result<()> {
|
pub fn add_to_queue(&self, uri: &str) -> Result<()> {
|
||||||
self.send("POST", &format!("/me/player/queue?uri={}", enc(uri)))
|
self.send("POST", &format!("/me/player/queue?uri={}", enc(uri)))
|
||||||
}
|
}
|
||||||
|
|||||||
755
src/internal.rs
Normal file
755
src/internal.rs
Normal file
@@ -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<String, (Instant, Vec<String>)>,
|
||||||
|
tracks: HashMap<String, Track>,
|
||||||
|
albums: HashMap<String, Album>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Internal {
|
||||||
|
engine: Engine,
|
||||||
|
cache: Arc<Mutex<Cache>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
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<Image> {
|
||||||
|
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> {
|
||||||
|
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<u8>, 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<u8>, 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<u8>, f: u32, v: u64) {
|
||||||
|
varint(out, (f << 3) as u64);
|
||||||
|
varint(out, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_varint(b: &[u8], i: &mut usize) -> Option<u64> {
|
||||||
|
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<u64, &[u8]>)> {
|
||||||
|
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<Session> {
|
||||||
|
self.engine.session()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Track (and episode) metadata, in order; cached.
|
||||||
|
fn tracks(&self, uris: &[String]) -> Result<Vec<Track>> {
|
||||||
|
let s = self.session()?;
|
||||||
|
let missing: Vec<String> = {
|
||||||
|
let c = self.cache.lock().unwrap();
|
||||||
|
uris.iter().filter(|u| !c.tracks.contains_key(*u)).cloned().collect()
|
||||||
|
};
|
||||||
|
if !missing.is_empty() {
|
||||||
|
let got: Vec<Track> = 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<Vec<Album>> {
|
||||||
|
let s = self.session()?;
|
||||||
|
let missing: Vec<String> = {
|
||||||
|
let c = self.cache.lock().unwrap();
|
||||||
|
uris.iter().filter(|u| !c.albums.contains_key(*u)).cloned().collect()
|
||||||
|
};
|
||||||
|
if !missing.is_empty() {
|
||||||
|
let got: Vec<Album> = 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<Vec<Artist>> {
|
||||||
|
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<Vec<Show>> {
|
||||||
|
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<Vec<String>> {
|
||||||
|
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<String> = 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<Vec<String>> {
|
||||||
|
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<bool> {
|
||||||
|
Ok(self.set(set)?.iter().any(|u| u == item))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- playlists ----
|
||||||
|
|
||||||
|
fn selected_list(&self, path: &str) -> Result<SelectedListContent> {
|
||||||
|
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<String> = 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<String> = 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<User> {
|
||||||
|
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::<serde_json::Value>(&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<Vec<Entity>> {
|
||||||
|
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<String> = 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<Paging<Playlist>> {
|
||||||
|
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<usize> = 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<Playlist> {
|
||||||
|
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<Paging<Track>> {
|
||||||
|
let r = self.selected_list(&format!("/playlist/v2/playlist/{id}?from={offset}&length=100"))?;
|
||||||
|
let c = r.contents.get_or_default();
|
||||||
|
let uris: Vec<String> = 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<Paging<Track>> {
|
||||||
|
let all = self.set_of("collection", "spotify:track:")?;
|
||||||
|
let page: Vec<String> = 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<Paging<Album>> {
|
||||||
|
let all = self.set_of("collection", "spotify:album:")?;
|
||||||
|
let page: Vec<String> = 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<Paging<Show>> {
|
||||||
|
let all = self.set_of("show", "spotify:show:")?;
|
||||||
|
let page: Vec<String> = 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<Artist>, Option<String>)> {
|
||||||
|
let all = self.set_of("artist", "spotify:artist:")?;
|
||||||
|
let from: usize = after.parse().unwrap_or(0);
|
||||||
|
let page: Vec<String> = 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<Vec<bool>> {
|
||||||
|
let all: HashSet<String> = 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<bool> {
|
||||||
|
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<bool> {
|
||||||
|
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<bool> {
|
||||||
|
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<Album> {
|
||||||
|
let s = self.session()?;
|
||||||
|
let a = self.engine.block(album::Album::get(&s, &uri("album", id)?)).map_err(e)?;
|
||||||
|
let uris: Vec<String> = 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<Track>, Vec<Album>, Vec<Album>, Vec<Album>)> {
|
||||||
|
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<String> = a.top_tracks.for_country(&country).iter().filter_map(|t| t.to_uri().ok()).take(10).collect();
|
||||||
|
let firsts = |g: &artist::AlbumGroups| -> Vec<String> { 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<Show> {
|
||||||
|
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<Paging<Track>> {
|
||||||
|
let s = self.session()?;
|
||||||
|
let x = self.engine.block(show::Show::get(&s, &uri("show", id)?)).map_err(e)?;
|
||||||
|
let all: Vec<String> = x.episodes.iter().filter_map(|u| u.to_uri().ok()).collect();
|
||||||
|
let page: Vec<String> = 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<SearchResult> {
|
||||||
|
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<String> = 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<String> = 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<Album> = 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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,13 +3,14 @@
|
|||||||
//! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer; the page engine
|
//! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer; the page engine
|
||||||
//! and controller come from Netflex TV.
|
//! and controller come from Netflex TV.
|
||||||
//! - Spotify: librespot (src/spotify.rs) for the session, Spotify Connect,
|
//! - Spotify: librespot (src/spotify.rs) for the session, Spotify Connect,
|
||||||
//! the zeroconf sign-in and playback; the Web API (src/api.rs) for
|
//! the sign-in and playback; Spotify's internal endpoints through the
|
||||||
//! browsing.
|
//! same session (src/internal.rs) for browsing.
|
||||||
|
|
||||||
mod api;
|
mod api;
|
||||||
mod app;
|
mod app;
|
||||||
mod config;
|
mod config;
|
||||||
mod format;
|
mod format;
|
||||||
|
mod internal;
|
||||||
mod nowplaying;
|
mod nowplaying;
|
||||||
mod page;
|
mod page;
|
||||||
mod screens;
|
mod screens;
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
//! Most szól: the big cover, the title, the progress, the controls (shuffle,
|
//! Most szól: the big cover, the title, the progress, the controls (shuffle,
|
||||||
//! previous, play/pause, next, repeat, like, lyrics, queue), synced lyrics
|
//! previous, play/pause, next, repeat, like, lyrics) and synced lyrics.
|
||||||
//! and the queue. Also keeps the playback state that the engine reports
|
//! Also keeps the playback state that the engine reports
|
||||||
//! (pages show it in the "now playing" capsule of the nav).
|
//! (pages show it in the "now playing" capsule of the nav).
|
||||||
//!
|
//!
|
||||||
//! Keys: left/right between the buttons, OK presses one, up goes to the
|
//! 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
|
//! progress bar (left/right seek there), Back returns to the pages. Space
|
||||||
//! (play/pause on a keyboard) works everywhere.
|
//! (play/pause on a keyboard) works everywhere.
|
||||||
|
|
||||||
use std::rc::Rc;
|
|
||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use slint::{Model, ModelRc, VecModel};
|
use slint::{Model, ModelRc, VecModel};
|
||||||
@@ -15,10 +14,10 @@ use slint::{Model, ModelRc, VecModel};
|
|||||||
use crate::api;
|
use crate::api;
|
||||||
use crate::app::{Action, Controller, Look};
|
use crate::app::{Action, Controller, Look};
|
||||||
use crate::spotify::{Cmd, Event, Track};
|
use crate::spotify::{Cmd, Event, Track};
|
||||||
use crate::{QueueItem, format, task};
|
use crate::{format, task};
|
||||||
|
|
||||||
/// The buttons, left to right.
|
/// 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;
|
const PLAY: usize = 2;
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||||
@@ -26,7 +25,6 @@ pub enum Panel {
|
|||||||
#[default]
|
#[default]
|
||||||
None,
|
None,
|
||||||
Lyrics,
|
Lyrics,
|
||||||
Queue,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -42,7 +40,6 @@ pub struct NowPlaying {
|
|||||||
/// (track id, lines, synced); empty lines = none.
|
/// (track id, lines, synced); empty lines = none.
|
||||||
lyrics: Option<(String, Vec<(u32, String)>, bool)>,
|
lyrics: Option<(String, Vec<(u32, String)>, bool)>,
|
||||||
lyrics_loading: bool,
|
lyrics_loading: bool,
|
||||||
queue: Vec<api::Track>,
|
|
||||||
panel: Panel,
|
panel: Panel,
|
||||||
focus: usize,
|
focus: usize,
|
||||||
/// 0: the buttons, 1: the progress bar.
|
/// 0: the buttons, 1: the progress bar.
|
||||||
@@ -137,7 +134,7 @@ pub fn on_event(c: &Controller, ev: Event) {
|
|||||||
c.track_changed();
|
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) {
|
fn track_changed(c: &Controller) {
|
||||||
let (track, panel) = {
|
let (track, panel) = {
|
||||||
let st = c.state.borrow();
|
let st = c.state.borrow();
|
||||||
@@ -168,7 +165,6 @@ fn track_changed(c: &Controller) {
|
|||||||
}
|
}
|
||||||
match panel {
|
match panel {
|
||||||
Panel::Lyrics => load_lyrics(c),
|
Panel::Lyrics => load_lyrics(c),
|
||||||
Panel::Queue => load_queue(c),
|
|
||||||
Panel::None => {}
|
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::<Vec<_>>(),
|
|
||||||
));
|
|
||||||
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.
|
/// Shows the screen.
|
||||||
pub fn open(c: &Controller) {
|
pub fn open(c: &Controller) {
|
||||||
{
|
{
|
||||||
@@ -293,7 +247,6 @@ pub fn open(c: &Controller) {
|
|||||||
let panel = c.state.borrow().np.panel;
|
let panel = c.state.borrow().np.panel;
|
||||||
match panel {
|
match panel {
|
||||||
Panel::Lyrics => load_lyrics(c),
|
Panel::Lyrics => load_lyrics(c),
|
||||||
Panel::Queue => load_queue(c),
|
|
||||||
Panel::None => {}
|
Panel::None => {}
|
||||||
}
|
}
|
||||||
let k = c.clone();
|
let k = c.clone();
|
||||||
@@ -429,13 +382,6 @@ fn press(c: &Controller, button: &str) {
|
|||||||
load_lyrics(c);
|
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);
|
sync(c);
|
||||||
@@ -479,7 +425,6 @@ pub fn sync(c: &Controller) {
|
|||||||
ui.set_np_panel(match np.panel {
|
ui.set_np_panel(match np.panel {
|
||||||
Panel::None => 0,
|
Panel::None => 0,
|
||||||
Panel::Lyrics => 1,
|
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) };
|
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());
|
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(ModelRc::new(VecModel::from(lines)));
|
||||||
}
|
}
|
||||||
ui.set_np_lyrics_note(note.into());
|
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);
|
sync_time(c);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -37,15 +37,8 @@ impl ArtistPage {
|
|||||||
let market = cx.user().country;
|
let market = cx.user().country;
|
||||||
cx.spawn::<ArtistPage, _>(
|
cx.spawn::<ArtistPage, _>(
|
||||||
move || -> anyhow::Result<(Data, Option<bool>)> {
|
move || -> anyhow::Result<(Data, Option<bool>)> {
|
||||||
let artist = api.artist(&id)?;
|
let (artist, top, albums, singles, appears) = api.artist_page(&id, &market)?;
|
||||||
let (top, albums, singles, appears, following) = std::thread::scope(|s| {
|
let following = api.following_artist(&id).ok();
|
||||||
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())
|
|
||||||
});
|
|
||||||
Ok((Data { artist, top, albums, singles, appears }, following))
|
Ok((Data { artist, top, albums, singles, appears }, following))
|
||||||
},
|
},
|
||||||
|s, cx, r| match r {
|
|s, cx, r| match r {
|
||||||
@@ -76,6 +69,7 @@ impl Screen for ArtistPage {
|
|||||||
hero.style = "ELŐADÓ".into();
|
hero.style = "ELŐADÓ".into();
|
||||||
hero.title = a.name.clone();
|
hero.title = a.name.clone();
|
||||||
hero.subtitle = a.followers.as_ref().map(|f| format::followers(f.total)).unwrap_or_default();
|
hero.subtitle = a.followers.as_ref().map(|f| format::followers(f.total)).unwrap_or_default();
|
||||||
|
|
||||||
hero.meta = a.genres.iter().take(4).cloned().collect::<Vec<_>>().join(" · ");
|
hero.meta = a.genres.iter().take(4).cloned().collect::<Vec<_>>().join(" · ");
|
||||||
let mut chips = vec![Ch::new("play", "Lejátszás").icon("play").tone("primary"), Ch::new("shuffle", "Keverés").icon("shuffle")];
|
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 {
|
if let Some(f) = self.following {
|
||||||
|
|||||||
@@ -1,23 +1,22 @@
|
|||||||
//! Kezdőlap: rows: recently played, your playlists (with the
|
//! Kezdőlap: rows: recently played (albums, playlists, artists...), your
|
||||||
//! liked songs first), your top artists and tracks, saved albums, new
|
//! playlists (with the liked songs first), your artists, saved albums, your
|
||||||
//! releases. Every row loads on its own; a failing one just stays away.
|
//! podcasts. Every row loads on its own; a failing one just stays away.
|
||||||
|
|
||||||
use std::any::Any;
|
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::app::{Cx, Look, Screen};
|
||||||
use crate::page::{Frame, L, Spec};
|
use crate::page::{C, Frame, L, Spec};
|
||||||
use crate::screens::{self, album_card, artist_card, liked_card, playlist_card, track_card};
|
use crate::screens::{self, album_card, artist_card, liked_card, playlist_card, show_card};
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct Data {
|
struct Data {
|
||||||
recent: Option<Vec<Played>>,
|
recent: Option<Vec<Entity>>,
|
||||||
playlists: Option<Vec<Playlist>>,
|
playlists: Option<Vec<Playlist>>,
|
||||||
liked_total: Option<u32>,
|
liked_total: Option<u32>,
|
||||||
top_artists: Option<Vec<Artist>>,
|
artists: Option<Vec<Artist>>,
|
||||||
top_tracks: Option<Vec<Track>>,
|
|
||||||
albums: Option<Vec<Album>>,
|
albums: Option<Vec<Album>>,
|
||||||
releases: Option<Vec<Album>>,
|
shows: Option<Vec<Show>>,
|
||||||
errors: Vec<String>,
|
errors: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -38,34 +37,41 @@ impl Home {
|
|||||||
cx.spawn::<Home, _>(
|
cx.spawn::<Home, _>(
|
||||||
move || {
|
move || {
|
||||||
std::thread::scope(|s| {
|
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 playlists = s.spawn(|| api.my_playlists(0));
|
||||||
let liked = s.spawn(|| api.liked(0));
|
let liked = s.spawn(|| api.liked(0));
|
||||||
let artists = s.spawn(|| api.top_artists());
|
let artists = s.spawn(|| api.followed_artists(""));
|
||||||
let tracks = s.spawn(|| api.top_tracks());
|
|
||||||
let albums = s.spawn(|| api.saved_albums(0));
|
let albums = s.spawn(|| api.saved_albums(0));
|
||||||
let releases = s.spawn(|| api.new_releases());
|
let shows = s.spawn(|| api.saved_shows(0));
|
||||||
let mut d = Data::default();
|
let mut errors = Vec::new();
|
||||||
let e = &mut d.errors;
|
let e = &mut errors;
|
||||||
let recent = keep(recent.join(), e);
|
let recent = keep(recent.join(), e);
|
||||||
let playlists = keep(playlists.join(), e).map(|p| p.list());
|
let playlists = keep(playlists.join(), e).map(|p| p.list());
|
||||||
let liked_total = keep(liked.join(), e).map(|p| p.total);
|
let liked_total = keep(liked.join(), e).map(|p| p.total);
|
||||||
let top_artists = keep(artists.join(), e);
|
let artists = keep(artists.join(), e).map(|a| a.0);
|
||||||
let top_tracks = keep(tracks.join(), e);
|
|
||||||
let albums = keep(albums.join(), e).map(|p| p.list());
|
let albums = keep(albums.join(), e).map(|p| p.list());
|
||||||
let releases = keep(releases.join(), e);
|
let shows = keep(shows.join(), e).map(|p| p.list());
|
||||||
Data { recent, playlists, liked_total, top_artists, top_tracks, albums, releases, ..d }
|
Data { recent, playlists, liked_total, artists, albums, shows, errors }
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
|s, cx, d| {
|
|s, cx, d| {
|
||||||
s.data = d;
|
s.data = d;
|
||||||
s.loading = false;
|
s.loading = false;
|
||||||
// The first picture of the page tints the background.
|
// 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(&s.first_image(), Look::Soft, "home");
|
||||||
cx.backdrop(&first, 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.
|
/// A row's result: the data, or its error noted.
|
||||||
@@ -81,17 +87,15 @@ fn keep<T>(r: std::thread::Result<anyhow::Result<T>>, errors: &mut Vec<String>)
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Recently played tracks, each once (newest first).
|
fn entity_card(e: &Entity, liked_total: Option<u32>) -> C {
|
||||||
fn recent_cards(items: &[Played]) -> Vec<crate::page::C> {
|
match e {
|
||||||
let mut seen = std::collections::HashSet::new();
|
Entity::Album(a) => album_card(a),
|
||||||
items
|
Entity::Playlist(p) => playlist_card(p),
|
||||||
.iter()
|
Entity::Artist(a) => artist_card(a),
|
||||||
.filter(|p| seen.insert(p.track.uri.clone()))
|
Entity::Show(s) => show_card(s),
|
||||||
.take(20)
|
Entity::Liked => liked_card(liked_total),
|
||||||
.map(|p| track_card(&p.track, p.context.as_ref().map(|c| c.uri.as_str()).unwrap_or("")))
|
}
|
||||||
.collect()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
impl Screen for Home {
|
impl Screen for Home {
|
||||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
fn spec(&mut self, cx: &Cx) -> Spec {
|
||||||
@@ -107,45 +111,33 @@ impl Screen for Home {
|
|||||||
}
|
}
|
||||||
let d = &self.data;
|
let d = &self.data;
|
||||||
if let Some(r) = d.recent.as_ref().filter(|r| !r.is_empty()) {
|
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)];
|
let mut pl = vec![liked_card(d.liked_total)];
|
||||||
pl.extend(d.playlists.iter().flatten().map(playlist_card));
|
pl.extend(d.playlists.iter().flatten().map(playlist_card));
|
||||||
lines.push(L::cards("playlists", "Lejátszási listáid", "square", pl).captions());
|
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()) {
|
if let Some(a) = d.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());
|
lines.push(L::cards("artists", "Előadóid", "round", a.iter().take(30).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.albums.as_ref().filter(|a| !a.is_empty()) {
|
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()) {
|
if let Some(s) = d.shows.as_ref().filter(|s| !s.is_empty()) {
|
||||||
lines.push(L::cards("releases", "Új megjelenések", "square", a.iter().map(album_card).collect()).captions());
|
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();
|
let why = d.errors.first().cloned().unwrap_or_default();
|
||||||
lines.push(L::notice("error", "bad", "Nem sikerült betölteni a kezdőlapot", why));
|
lines.push(L::notice("error", "bad", "Nem sikerült betölteni a kezdőlapot", why));
|
||||||
}
|
}
|
||||||
Spec { lines, frame }
|
Spec { lines, frame }
|
||||||
}
|
}
|
||||||
|
|
||||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
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;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
screens::open_card(cx, item);
|
screens::open_card(cx, item);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn shown(&mut self, cx: &Cx) {
|
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(&self.first_image(), Look::Soft, "home");
|
||||||
cx.backdrop(&first, Look::Soft, "home");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn as_any(&mut self) -> &mut dyn Any {
|
fn as_any(&mut self) -> &mut dyn Any {
|
||||||
|
|||||||
@@ -100,14 +100,6 @@ pub fn show_card(s: &Show) -> C {
|
|||||||
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<u32>) -> C {
|
pub fn liked_card(total: Option<u32>) -> C {
|
||||||
let mut c = C::new("liked", "Kedvelt dalok", "");
|
let mut c = C::new("liked", "Kedvelt dalok", "");
|
||||||
c.caption = "Kedvelt dalok".into();
|
c.caption = "Kedvelt dalok".into();
|
||||||
|
|||||||
@@ -21,7 +21,7 @@ impl Search {
|
|||||||
|
|
||||||
impl Screen for Search {
|
impl Screen for Search {
|
||||||
fn spec(&mut self, cx: &Cx) -> Spec {
|
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 {
|
match &self.result {
|
||||||
None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "Két betű elég.")),
|
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")),
|
Some(Load::Loading) => lines.push(L::text("loading", "Keresés…", "caption")),
|
||||||
|
|||||||
@@ -185,7 +185,12 @@ impl Engine {
|
|||||||
let _ = self.cmd.send(c);
|
let _ = self.cmd.send(c);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn session(&self) -> anyhow::Result<Session> {
|
/// Runs `f` on the engine's runtime and waits (blocking; off the UI thread).
|
||||||
|
pub fn block<F: std::future::Future>(&self, f: F) -> F::Output {
|
||||||
|
self.rt.block_on(f)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn session(&self) -> anyhow::Result<Session> {
|
||||||
self.session.lock().unwrap().clone().filter(|s| !s.is_invalid()).ok_or_else(|| anyhow::anyhow!("Nincs kapcsolat a Spotifyjal"))
|
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());
|
return Ok("mock".into());
|
||||||
}
|
}
|
||||||
let s = self.session()?;
|
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 {
|
match t {
|
||||||
Ok(Ok(t)) => Ok(t.access_token),
|
Ok(Ok(t)) => Ok(t.access_token),
|
||||||
Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")),
|
Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")),
|
||||||
|
|||||||
@@ -139,8 +139,6 @@ export component App inherits TvWindow {
|
|||||||
in property <int> np-lyric-line <=> np.lyric-line;
|
in property <int> np-lyric-line <=> np.lyric-line;
|
||||||
in property <bool> np-lyrics-synced <=> np.lyrics-synced;
|
in property <bool> np-lyrics-synced <=> np.lyrics-synced;
|
||||||
in property <string> np-lyrics-note <=> np.lyrics-note;
|
in property <string> np-lyrics-note <=> np.lyrics-note;
|
||||||
in property <[QueueItem]> np-queue <=> np.queue;
|
|
||||||
in property <string> np-queue-note <=> np.queue-note;
|
|
||||||
in property <string> np-device <=> np.device;
|
in property <string> np-device <=> np.device;
|
||||||
np := NowPlayingScreen {
|
np := NowPlayingScreen {
|
||||||
alpha: root.vis(root.np-t) * root.under;
|
alpha: root.vis(root.np-t) * root.under;
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
// Most szól: the cover, the title, the progress and the controls. With the
|
// 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
|
// lyrics open, the cover and the texts move to the left and a glass panel
|
||||||
// glass panel holds the lyrics / the queue on the right.
|
// 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).
|
// the progress bar (left/right seek there).
|
||||||
|
|
||||||
import { Tv, GlassRect, GlassPane, Spinner, Caption } from "@sf-ui/sf-ui.slint";
|
import { Tv, GlassRect, GlassPane, Spinner, Caption } from "@sf-ui/sf-ui.slint";
|
||||||
import { QueueItem } from "types.slint";
|
|
||||||
import { SpIcon } from "icons.slint";
|
import { SpIcon } from "icons.slint";
|
||||||
import { Accent, Equalizer } from "page.slint";
|
import { Accent, Equalizer } from "page.slint";
|
||||||
|
|
||||||
@@ -73,14 +72,12 @@ export component NowPlayingScreen inherits Rectangle {
|
|||||||
in property <int> liked: -1;
|
in property <int> liked: -1;
|
||||||
in property <int> button: 2;
|
in property <int> button: 2;
|
||||||
in property <int> area;
|
in property <int> area;
|
||||||
// 0 none, 1 lyrics, 2 queue
|
// 0 none, 1 lyrics
|
||||||
in property <int> panel;
|
in property <int> panel;
|
||||||
in property <[string]> lyrics;
|
in property <[string]> lyrics;
|
||||||
in property <int> lyric-line: -1;
|
in property <int> lyric-line: -1;
|
||||||
in property <bool> lyrics-synced;
|
in property <bool> lyrics-synced;
|
||||||
in property <string> lyrics-note;
|
in property <string> lyrics-note;
|
||||||
in property <[QueueItem]> queue;
|
|
||||||
in property <string> queue-note;
|
|
||||||
in property <string> device;
|
in property <string> device;
|
||||||
|
|
||||||
// 0: the big layout, 1: side by side with the panel.
|
// 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); }
|
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); }
|
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; }
|
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 {
|
Caption {
|
||||||
x: root.tx;
|
x: root.tx;
|
||||||
y: controls.y + controls.height + 18 * Tv.u;
|
y: controls.y + controls.height + 18 * Tv.u;
|
||||||
@@ -280,7 +276,7 @@ export component NowPlayingScreen inherits Rectangle {
|
|||||||
opacity: root.alpha;
|
opacity: root.alpha;
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- the panel: lyrics or the queue ----
|
// ---- the panel: lyrics ----
|
||||||
property <float> pa: root.alpha * clamp(root.t * 1.6 - 0.6, 0, 1);
|
property <float> pa: root.alpha * clamp(root.t * 1.6 - 0.6, 0, 1);
|
||||||
panel-pane := GlassPane {
|
panel-pane := GlassPane {
|
||||||
x: 820 * Tv.u;
|
x: 820 * Tv.u;
|
||||||
@@ -323,66 +319,6 @@ export component NowPlayingScreen inherits Rectangle {
|
|||||||
wrap: word-wrap;
|
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: [
|
out property <[GlassRect]> glass: [
|
||||||
@@ -399,7 +335,7 @@ export component NowPlayingScreen inherits Rectangle {
|
|||||||
tint: #ffffff.with-alpha(0.14 + 0.1 * root.pf),
|
tint: #ffffff.with-alpha(0.14 + 0.1 * root.pf),
|
||||||
group: 0,
|
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,
|
panel-pane.glass,
|
||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user