Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fd7e242a7 | ||
|
|
5a76e56fe1 | ||
|
|
84cfeff00a | ||
|
|
740397ea59 |
@@ -45,15 +45,13 @@ jobs:
|
||||
printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \
|
||||
"$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources
|
||||
apt-get update -qq
|
||||
# Multiarch dev packages for both architectures; for arm64 only the
|
||||
# GStreamer runtime libraries: its dev packages can't be installed for
|
||||
# two architectures at once (package.sh --arm links the libraries).
|
||||
libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libglib2.0-dev"
|
||||
apt-get install -y -qq --no-install-recommends build-essential pkg-config \
|
||||
gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross \
|
||||
$libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done) \
|
||||
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev \
|
||||
libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64
|
||||
# Multiarch dev packages for both architectures.
|
||||
libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev"
|
||||
pkgs="build-essential pkg-config gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross
|
||||
$libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done)"
|
||||
# tools/ci-apt.sh: when ports.ubuntu.com lags behind, it aligns the
|
||||
# Multi-Arch libraries on both architectures to the arm64 version.
|
||||
sh "$W/src/tools/ci-apt.sh" $pkgs
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu
|
||||
"$CARGO_HOME/bin/cargo" install -q --locked --git "$SDK_GIT" --tag "$SDK_TAG" sf-pack
|
||||
|
||||
18
AGENTS.md
18
AGENTS.md
@@ -11,8 +11,11 @@ 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/spotify.rs the engine: librespot session (pairing-code sign-in, browsing), Cmd in (playback -> Soloist), Event out
|
||||
src/soloist.rs Spotify Soloist: download/update, run, restart, its WebSocket API -> Events
|
||||
src/keyserver.rs the local web page where the phone pastes the Soloist key (QR code on the key screen)
|
||||
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,17 +31,22 @@ 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/signin.slint ConnectScreen (QR code + Spotify app), InputScreen, MessageScreen
|
||||
ui/nowplaying.slint the now playing screen and its lyrics panel
|
||||
ui/signin.slint ConnectScreen (pairing code), KeyScreen (Soloist key), 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.
|
||||
- **Engine thread:** librespot runs on its own tokio runtime. Talk to it with `Engine::send(Cmd)`; its `Event`s reach the UI thread through `slint::invoke_from_event_loop`. Blocking calls (`Engine::token`, `Engine::lyrics`, every `Api` method) only off the UI thread (`task::spawn`, `Cx::spawn`).
|
||||
- **Playback is Spirc's:** play a context (`Cmd::Context`) whenever possible, so next/previous, shuffle and the phone's view work. `Cx::play` also opens Most szól.
|
||||
- **Playback is Soloist's** (librespot is refused the audio keys). Its `play` takes one URI: a context plays from its start; a track from a list plays and the next ones are queued (`Cmd::Tracks`). `Cx::play` also opens Most szól. Soloist must not be redistributed: it is downloaded on the TV.
|
||||
- **Short borrows:** never hold `state.borrow_mut()` while calling `images.load*`; a cached picture calls back at once.
|
||||
- **Glass:** new glass elements need their `glass` listed in a root `out property <[GlassRect]>`, and that array added in `main.rs`. Nothing Slint draws may sit under a glass pane.
|
||||
- **Slint names:** a property may not be called `focus` (a function) or `cover` (an ImageFit value).
|
||||
|
||||
791
Cargo.lock
generated
791
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
27
Cargo.toml
27
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"
|
||||
description = "Spotify for Fennec OS: native TV client with Liquid Glass; Spotify Soloist plays, librespot browses"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
# sf-ui (and Slint) are GPL-3.0 on a TV box; librespot is MIT.
|
||||
license = "GPL-3.0-only"
|
||||
@@ -18,22 +18,21 @@ serde = { version = "1", features = ["derive"] }
|
||||
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 }
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "sync", "time", "signal", "process", "io-util", "net", "fs"] }
|
||||
futures-util = { version = "0.3", default-features = false, features = ["std", "sink"] }
|
||||
# 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.
|
||||
# Spotify: the session (sign-in, browsing, lyrics) and its metadata.
|
||||
librespot-core = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
|
||||
librespot-connect = { version = "0.8", default-features = false, features = ["rustls-tls-webpki-roots"] }
|
||||
librespot-discovery = { version = "0.8", default-features = false, features = ["with-libmdns"] }
|
||||
librespot-metadata = { version = "0.8", default-features = false }
|
||||
|
||||
# Sound: GStreamer on the TV (PipeWire), rodio elsewhere (UI work on Windows).
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
librespot-playback = { version = "0.8", default-features = false, features = ["gstreamer-backend", "rustls-tls-webpki-roots"] }
|
||||
|
||||
[target.'cfg(not(target_os = "linux"))'.dependencies]
|
||||
librespot-playback = { version = "0.8", default-features = false, features = ["rodio-backend", "rustls-tls-webpki-roots"] }
|
||||
# Playback: Spotify Soloist (downloaded on the TV), driven over its local WebSocket.
|
||||
tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect"] }
|
||||
flate2 = "1"
|
||||
tar = "0.4"
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "1.18"
|
||||
|
||||
21
README.md
21
README.md
@@ -3,17 +3,14 @@
|
||||
Natív Spotify kliens Fennec OS-re (store app, `support.bluefox.spotify`). Spotify Premium fiók kell hozzá.
|
||||
|
||||
- **Felület:** Rust + Slint az sf-ui Liquid Glass-ával, ugyanazzal a lapmotorral, mint a Netflex TV.
|
||||
- **Lejátszás:** [librespot](https://github.com/librespot-org/librespot) (Rust), GStreamerrel (PipeWire). A TV teljes értékű **Spotify Connect** eszköz: a telefonról is irányítható, és a lejátszás átvihető rá vagy róla.
|
||||
- **Bejelentkezés a telefonnal**, kétféleképpen:
|
||||
- **QR-kód / párosítókód:** a TV QR-kódot és rövid kódot mutat. A telefonon a `spotify.com/pair` oldalon kell bejelentkezni, a TV magától belép. Nem kell hozzá ugyanaz a hálózat.
|
||||
- **A Spotify appból:** ugyanazon a Wi-Fin a TV megjelenik a telefon eszközlistájában (zeroconf). Kiválasztva bejelentkezik.
|
||||
- **Lejátszás:** a [Spotify Soloist](https://developer.spotify.com/documentation/soloist), a Spotify saját Linuxos lejátszója. Az app a TV-n tölti le a Spotifytól (terjeszteni nem szabad), 45 naponta frissíti, és a helyi WebSocket-API-ján irányítja. A TV teljes értékű **Spotify Connect** eszköz: a telefonról is irányítható. A librespot nem tud lejátszani: a Spotify megtagadja tőle a hangkulcsokat ([librespot #1649](https://github.com/librespot-org/librespot/issues/1649)).
|
||||
- **Soloist-kulcs:** a saját fiókodból kell egy kulcs (developer.spotify.com/dashboard/soloist, Premium). A TV QR-kódot mutat, a telefonon megnyíló oldalra kell bemásolni (vagy a TV billentyűzetén beírni); egyszer kell, a TV megjegyzi. Utána egyszer ki kell választani a TV-t a telefon Spotify appjában (párosítás).
|
||||
- **Bejelentkezés (böngészéshez) a telefonnal:** a TV QR-kódot és rövid kódot mutat; a telefonon a `spotify.com/pair` oldalon kell bejelentkezni, a TV magától belép. 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, 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ó. Egy lista dalát kiválasztva az a dal szól, a lista többi dala (30-ig) a sorba kerül.
|
||||
- **Beállítások:** kijelentkezés, a lejátszó állapota és kulcsa, a TV neve (Connect), megjelenés (üveg / matt).
|
||||
|
||||
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ó.
|
||||
- **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
|
||||
|
||||
@@ -30,8 +27,8 @@ SPOTIFY_MOCK=1 SPOTIFY_API=http://127.0.0.1:7890/v1 SPOTIFY_WINDOWED=1 cargo run
|
||||
# SPOTIFY_MOCK=signin: a bejelentkező képernyő egy mintakóddal
|
||||
```
|
||||
|
||||
- **Windowson** is fordul és fut (a hang ott rodio-val szól), a TV-n GStreamer.
|
||||
- **Linuxon** (Debian trixie / WSL) kell még: `libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libfontconfig1-dev libxkbcommon-dev`.
|
||||
- **Windowson** is fordul és fut (böngészésre; a Soloist csak Linuxon van).
|
||||
- **Linuxon** (Debian trixie / WSL) kell még: `libfontconfig1-dev libxkbcommon-dev`.
|
||||
- **Pillanatkép ember nélkül:** `SF_UI_SIZE=1600x900 SF_UI_KEYS="wait down enter" SF_UI_SNAPSHOT=out.png cargo run` (az SDK `docs/sf-ui.md` 11. fejezete). `SPOTIFY_WINDOW_POS=x,y`: hol nyíljon az ablak (például egy másik monitoron).
|
||||
|
||||
## Kiadás
|
||||
|
||||
5
app.toml
5
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.2.0"
|
||||
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á."
|
||||
@@ -15,6 +15,7 @@ accent = "#1ED760"
|
||||
palette = ["#1ed760", "#0d5c2b", "#060a07"]
|
||||
|
||||
[sandbox]
|
||||
# network: Spotify and Spotify Connect (zeroconf on the local network);
|
||||
# network: Spotify, Spotify Connect (zeroconf on the local network), the
|
||||
# Soloist download and the key page for the phone;
|
||||
# gpu: the glass UI; audio: sound.
|
||||
permissions = ["network", "gpu", "audio"]
|
||||
|
||||
28
package.sh
28
package.sh
@@ -6,15 +6,12 @@
|
||||
# ./package.sh --arm adds support.bluefox.spotify-<version>-aarch64.tar.zst
|
||||
# (Raspberry Pi, cross-compiled)
|
||||
#
|
||||
# Build on Debian trixie or older (the TV's glibc), with the GStreamer dev
|
||||
# packages (libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev) and
|
||||
# sf-pack from the Fennec SDK:
|
||||
# Build on Debian trixie or older (the TV's glibc), with the fontconfig,
|
||||
# freetype and xkbcommon dev packages and sf-pack from the Fennec SDK:
|
||||
# cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.1 sf-pack
|
||||
# --arm also needs gcc-aarch64-linux-gnu, the arm64 (multiarch) dev packages
|
||||
# of fontconfig, freetype, xkbcommon and glib, and the arm64 GStreamer
|
||||
# runtime libraries (libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64).
|
||||
# Not necessarily the GStreamer dev packages: they can't be installed for two
|
||||
# architectures at once, so the build links the runtime libraries directly.
|
||||
# --arm also needs gcc-aarch64-linux-gnu and the arm64 (multiarch) dev
|
||||
# packages of fontconfig, freetype and xkbcommon.
|
||||
# (No GStreamer: Spotify Soloist plays, downloaded on the TV.)
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
@@ -46,21 +43,6 @@ else
|
||||
export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/
|
||||
export PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig
|
||||
rustup target list --installed | grep -qx "$t" || rustup target add "$t"
|
||||
# GStreamer without pkg-config (system-deps): link the runtime libraries
|
||||
# through a folder of unversioned names. librespot plays through
|
||||
# appsrc -> audioconvert -> autoaudiosink: core, base, app, audio.
|
||||
mkdir -p "$target"
|
||||
gst="$(cd "$target" && pwd)/arm-gstreamer"
|
||||
rm -rf "$gst" && mkdir -p "$gst"
|
||||
# system-deps key (the pkg-config name) and the library it stands for.
|
||||
for pair in GSTREAMER_1_0:gstreamer-1.0 GSTREAMER_BASE_1_0:gstbase-1.0 \
|
||||
GSTREAMER_APP_1_0:gstapp-1.0 GSTREAMER_AUDIO_1_0:gstaudio-1.0; do
|
||||
key=${pair%%:*} lib=${pair#*:}
|
||||
so=/usr/lib/aarch64-linux-gnu/lib$lib.so.0
|
||||
[ -e "$so" ] || { echo "missing $so (install the arm64 GStreamer runtime libraries)" >&2; exit 1; }
|
||||
ln -s "$so" "$gst/lib$lib.so"
|
||||
export "SYSTEM_DEPS_${key}_NO_PKG_CONFIG=1" "SYSTEM_DEPS_${key}_LIB=$lib" "SYSTEM_DEPS_${key}_SEARCH_NATIVE=$gst"
|
||||
done
|
||||
cargo build --release --locked --target "$t"
|
||||
rm -rf dist-arm
|
||||
pack "$target/$t/release/$bin" dist-arm
|
||||
|
||||
186
src/api.rs
186
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<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)]
|
||||
pub struct SearchResult {
|
||||
pub tracks: Vec<Track>,
|
||||
@@ -313,15 +332,123 @@ pub fn enc(s: &str) -> String {
|
||||
|
||||
/// Cheap to clone; usable from any thread (blocking calls).
|
||||
#[derive(Clone)]
|
||||
pub struct Api {
|
||||
base: String,
|
||||
engine: Engine,
|
||||
agent: ureq::Agent,
|
||||
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
|
||||
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))
|
||||
}
|
||||
}
|
||||
|
||||
/// The Web API client (the mock server).
|
||||
#[derive(Clone)]
|
||||
pub struct Web {
|
||||
base: String,
|
||||
agent: ureq::Agent,
|
||||
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
|
||||
}
|
||||
|
||||
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 +457,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(), agent, cache: Arc::default() }
|
||||
}
|
||||
|
||||
/// Forgets cached answers (after a change to the library).
|
||||
@@ -355,7 +482,8 @@ impl Api {
|
||||
let mut tries = 0;
|
||||
loop {
|
||||
tries += 1;
|
||||
let auth = format!("Bearer {}", self.engine.token()?);
|
||||
// Only the mock server: any token does.
|
||||
let auth = "Bearer mock".to_string();
|
||||
let resp = match method {
|
||||
"GET" => self.agent.get(&url).header("Authorization", &auth).header("Accept-Language", "hu").call(),
|
||||
"POST" => self.agent.post(&url).header("Authorization", &auth).send_empty(),
|
||||
@@ -427,6 +555,11 @@ impl Api {
|
||||
|
||||
// ---- 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>> {
|
||||
#[derive(Deserialize, Default)]
|
||||
#[serde(default)]
|
||||
@@ -435,20 +568,6 @@ impl Api {
|
||||
}
|
||||
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 ----
|
||||
|
||||
@@ -567,6 +686,14 @@ impl Api {
|
||||
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())
|
||||
}
|
||||
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> {
|
||||
self.get(&format!("/shows/{id}"))
|
||||
}
|
||||
@@ -592,19 +719,6 @@ impl Api {
|
||||
|
||||
// ---- 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<()> {
|
||||
self.send("POST", &format!("/me/player/queue?uri={}", enc(uri)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
118
src/app.rs
118
src/app.rs
@@ -139,6 +139,10 @@ pub struct State {
|
||||
pub np: NowPlaying,
|
||||
/// The nav focus sits on the "now playing" capsule.
|
||||
np_capsule: bool,
|
||||
/// The player (Soloist).
|
||||
pub solo: crate::soloist::Status,
|
||||
/// The key page while the key screen is open.
|
||||
keyserver: Option<crate::keyserver::KeyServer>,
|
||||
}
|
||||
|
||||
pub struct Inner {
|
||||
@@ -195,6 +199,9 @@ impl<'a> Cx<'a> {
|
||||
pub fn user(&self) -> User {
|
||||
self.c.state.borrow().user.clone()
|
||||
}
|
||||
pub fn solo(&self) -> crate::soloist::Status {
|
||||
self.c.state.borrow().solo.clone()
|
||||
}
|
||||
pub fn cfg(&self) -> Config {
|
||||
self.c.state.borrow().cfg.clone()
|
||||
}
|
||||
@@ -293,6 +300,8 @@ impl Controller {
|
||||
select: None,
|
||||
np: NowPlaying::default(),
|
||||
np_capsule: false,
|
||||
solo: crate::soloist::Status::Starting,
|
||||
keyserver: None,
|
||||
};
|
||||
let c = Controller(Rc::new(Inner {
|
||||
ui: ui.as_weak(),
|
||||
@@ -381,6 +390,7 @@ impl Controller {
|
||||
match ev {
|
||||
Event::Status(s) => self.on_status(s),
|
||||
Event::Pair(p) => self.on_pair(p),
|
||||
Event::Solo(s) => self.on_solo(s),
|
||||
other => nowplaying::on_event(self, other),
|
||||
}
|
||||
}
|
||||
@@ -441,12 +451,12 @@ impl Controller {
|
||||
}
|
||||
c.show_user(&user);
|
||||
c.state.borrow_mut().user = user;
|
||||
c.section_now(0);
|
||||
c.after_sign_in();
|
||||
}
|
||||
Err(e) => {
|
||||
// Browsing may still fail, but playback works: go on.
|
||||
log::warn!("me: {e:#}");
|
||||
c.section_now(0);
|
||||
c.after_sign_in();
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -467,6 +477,107 @@ impl Controller {
|
||||
}
|
||||
}
|
||||
|
||||
/// Signed in: the home page, or first the Soloist key if there is none.
|
||||
fn after_sign_in(&self) {
|
||||
if self.state.borrow().cfg.soloist_key.trim().is_empty() {
|
||||
self.open_key_screen();
|
||||
} else {
|
||||
self.section_now(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// The player's state changed.
|
||||
fn on_solo(&self, s: crate::soloist::Status) {
|
||||
let changed = self.state.borrow().solo != s;
|
||||
self.state.borrow_mut().solo = s.clone();
|
||||
if !changed {
|
||||
return;
|
||||
}
|
||||
if let crate::soloist::Status::Failed(msg) = &s {
|
||||
self.toast(msg, true);
|
||||
}
|
||||
// Home and settings show it.
|
||||
if self.state.borrow().screen == "page" {
|
||||
self.rebuild();
|
||||
}
|
||||
crate::nowplaying::sync(self);
|
||||
}
|
||||
|
||||
/// The Soloist key screen: a QR code to a page where the phone pastes
|
||||
/// the key; OK types it on the TV instead; Back: later.
|
||||
pub fn open_key_screen(&self) {
|
||||
let server = crate::keyserver::start(move |key| {
|
||||
let _ = slint::invoke_from_event_loop(move || {
|
||||
if let Some(c) = CONTROLLER.with(|k| k.borrow().clone()) {
|
||||
c.set_solo_key(&key);
|
||||
}
|
||||
});
|
||||
});
|
||||
let url = match server {
|
||||
Ok(s) => {
|
||||
let url = s.url.clone();
|
||||
self.state.borrow_mut().keyserver = Some(s);
|
||||
url
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("key page: {e:#}");
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
if let Some(ui) = self.ui() {
|
||||
ui.set_solokey_url(url.trim_start_matches("http://").trim_end_matches('/').into());
|
||||
ui.set_solokey_qr(if url.is_empty() { Default::default() } else { qr_image(&url).unwrap_or_default() });
|
||||
}
|
||||
self.clear_backdrop();
|
||||
self.show("solokey");
|
||||
}
|
||||
|
||||
/// A new Soloist key (from the phone or the TV keyboard).
|
||||
pub fn set_solo_key(&self, key: &str) {
|
||||
let key = key.trim().to_string();
|
||||
if key.len() < 16 {
|
||||
self.toast("Ez nem tűnik kulcsnak.", true);
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.cfg.soloist_key = key.clone();
|
||||
st.cfg.save();
|
||||
}
|
||||
self.engine.set_key(&key);
|
||||
self.toast("Kulcs elmentve, indul a lejátszó", false);
|
||||
if self.state.borrow().screen == "solokey" {
|
||||
self.close_key_screen();
|
||||
}
|
||||
}
|
||||
|
||||
fn close_key_screen(&self) {
|
||||
self.state.borrow_mut().keyserver = None;
|
||||
if self.state.borrow().stack.is_empty() {
|
||||
self.section_now(0);
|
||||
} else {
|
||||
self.back_to_pages();
|
||||
}
|
||||
}
|
||||
|
||||
fn key_screen_key(&self, a: Action) {
|
||||
match a {
|
||||
Action::Back => self.close_key_screen(),
|
||||
Action::Ok => {
|
||||
let req = Input {
|
||||
title: "Spotify Soloist kulcs".into(),
|
||||
subtitle: "developer.spotify.com/dashboard/soloist".into(),
|
||||
placeholder: "API-kulcs".into(),
|
||||
value: String::new(),
|
||||
submit: "Mentés".into(),
|
||||
min: 16,
|
||||
};
|
||||
self.open_input(req, Rc::new(|c: &Controller, text: String| c.set_solo_key(&text)));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's picture (or initial) in the top right corner.
|
||||
fn show_user(&self, user: &User) {
|
||||
let Some(ui) = self.ui() else { return };
|
||||
@@ -822,7 +933,7 @@ impl Controller {
|
||||
}
|
||||
|
||||
/// The nav focus and the "now playing" capsule.
|
||||
fn sync_nav(&self) {
|
||||
pub fn sync_nav(&self) {
|
||||
let Some(ui) = self.ui() else { return };
|
||||
let st = self.state.borrow();
|
||||
let nav_focus = st.stack.last().is_some_and(|e| e.view.focus == Focus::Nav);
|
||||
@@ -876,6 +987,7 @@ impl Controller {
|
||||
}
|
||||
let screen = self.state.borrow().screen;
|
||||
match screen {
|
||||
"solokey" => self.key_screen_key(a),
|
||||
"message" | "signin" => {
|
||||
if a == Action::Back {
|
||||
let _ = slint::quit_event_loop();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
//! What this TV remembers: its Connect identity and the playback settings.
|
||||
//! What this TV remembers: its Connect name, the Soloist API key, the look.
|
||||
//! `$HOME/.config/spotify-tv/config.toml` (on the TV, $HOME is the app's own
|
||||
//! data folder inside the sandbox). The Spotify credentials live apart, in
|
||||
//! `$HOME/.cache/spotify-tv/credentials.json` (librespot's cache).
|
||||
@@ -17,15 +17,9 @@ pub struct Config {
|
||||
/// The name phones show.
|
||||
#[serde(default = "default_name")]
|
||||
pub device_name: String,
|
||||
/// 96 | 160 | 320 kbit/s.
|
||||
#[serde(default = "default_bitrate")]
|
||||
pub bitrate: u32,
|
||||
/// Same loudness for every track.
|
||||
#[serde(default = "yes")]
|
||||
pub normalise: bool,
|
||||
/// Similar tracks after the end of an album or playlist.
|
||||
#[serde(default = "yes")]
|
||||
pub autoplay: bool,
|
||||
/// The user's Spotify Soloist API key (developer.spotify.com/dashboard/soloist).
|
||||
#[serde(default)]
|
||||
pub soloist_key: String,
|
||||
/// "auto" | "full" | "light" | "off" (Material)
|
||||
#[serde(default = "auto")]
|
||||
pub glass: String,
|
||||
@@ -34,19 +28,13 @@ pub struct Config {
|
||||
fn default_name() -> String {
|
||||
DEFAULT_NAME.into()
|
||||
}
|
||||
fn default_bitrate() -> u32 {
|
||||
320
|
||||
}
|
||||
fn yes() -> bool {
|
||||
true
|
||||
}
|
||||
fn auto() -> String {
|
||||
"auto".into()
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config { device_id: String::new(), device_name: default_name(), bitrate: default_bitrate(), normalise: true, autoplay: true, glass: auto() }
|
||||
Config { device_id: String::new(), device_name: default_name(), soloist_key: String::new(), glass: auto() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
739
src/internal.rs
Normal file
739
src/internal.rs
Normal file
@@ -0,0 +1,739 @@
|
||||
//! 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
|
||||
//!
|
||||
//! 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() })
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
#[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]);
|
||||
}
|
||||
}
|
||||
148
src/keyserver.rs
Normal file
148
src/keyserver.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
//! A tiny web page on the local network for the Soloist API key: the TV
|
||||
//! shows a QR code to it, the phone pastes the key (typing a long key with a
|
||||
//! remote is no fun). It runs only while the key screen is open.
|
||||
|
||||
use std::io::{BufRead, BufReader, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream, UdpSocket};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
const DASHBOARD: &str = "https://developer.spotify.com/dashboard/soloist";
|
||||
|
||||
/// The running page; it stops when dropped.
|
||||
pub struct KeyServer {
|
||||
pub url: String,
|
||||
stop: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl Drop for KeyServer {
|
||||
fn drop(&mut self) {
|
||||
self.stop.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
/// This TV's address on the local network (the route to the internet).
|
||||
fn local_ip() -> Option<std::net::IpAddr> {
|
||||
let s = UdpSocket::bind("0.0.0.0:0").ok()?;
|
||||
s.connect("8.8.8.8:80").ok()?;
|
||||
Some(s.local_addr().ok()?.ip())
|
||||
}
|
||||
|
||||
/// Starts the page; `got` gets the key (on a server thread).
|
||||
pub fn start(got: impl Fn(String) + Send + Sync + 'static) -> anyhow::Result<KeyServer> {
|
||||
// On the TV the phone must reach it; on a developer's PC (not Linux)
|
||||
// only the loopback, so no firewall prompt pops up.
|
||||
let listener = TcpListener::bind(if cfg!(target_os = "linux") { "0.0.0.0:0" } else { "127.0.0.1:0" })?;
|
||||
listener.set_nonblocking(true)?;
|
||||
let port = listener.local_addr()?.port();
|
||||
let ip = local_ip().ok_or_else(|| anyhow::anyhow!("nincs hálózat"))?;
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let stop2 = stop.clone();
|
||||
let got = Arc::new(got);
|
||||
std::thread::spawn(move || {
|
||||
while !stop2.load(Ordering::SeqCst) {
|
||||
match listener.accept() {
|
||||
Ok((s, _)) => {
|
||||
let got = got.clone();
|
||||
std::thread::spawn(move || {
|
||||
if let Err(e) = serve(s, &*got) {
|
||||
log::info!("key page: {e}");
|
||||
}
|
||||
});
|
||||
}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => std::thread::sleep(Duration::from_millis(150)),
|
||||
Err(e) => {
|
||||
log::warn!("key page: {e}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(KeyServer { url: format!("http://{ip}:{port}/"), stop })
|
||||
}
|
||||
|
||||
fn serve(mut s: TcpStream, got: &(dyn Fn(String) + Send + Sync)) -> anyhow::Result<()> {
|
||||
s.set_nonblocking(false)?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(10)))?;
|
||||
let mut r = BufReader::new(s.try_clone()?);
|
||||
let mut first = String::new();
|
||||
r.read_line(&mut first)?;
|
||||
let mut len = 0usize;
|
||||
loop {
|
||||
let mut h = String::new();
|
||||
if r.read_line(&mut h)? == 0 || h.trim().is_empty() {
|
||||
break;
|
||||
}
|
||||
if let Some(v) = h.to_ascii_lowercase().strip_prefix("content-length:") {
|
||||
len = v.trim().parse().unwrap_or(0);
|
||||
}
|
||||
}
|
||||
let (status, body) = if first.starts_with("POST") {
|
||||
let mut b = vec![0u8; len.min(8192)];
|
||||
r.read_exact(&mut b)?;
|
||||
let key = form_value(&String::from_utf8_lossy(&b), "key");
|
||||
if key.len() >= 16 && key.chars().all(|c| c.is_ascii_graphic()) {
|
||||
got(key);
|
||||
("200 OK", page("<h1>Kész ✓</h1><p>A TV megkapta a kulcsot, és elindítja a lejátszót. Ezt az oldalt bezárhatod.</p>"))
|
||||
} else {
|
||||
("400 Bad Request", page(&format!("<h1>Ez nem tűnik kulcsnak</h1><p>Másold ki a teljes kulcsot innen: <a href=\"{DASHBOARD}\">{DASHBOARD}</a></p>{}", FORM)))
|
||||
}
|
||||
} else {
|
||||
("200 OK", page(&format!(
|
||||
"<h1>Spotify Soloist kulcs</h1><p>1. Nyisd meg: <a href=\"{DASHBOARD}\" target=\"_blank\">developer.spotify.com/dashboard/soloist</a>, jelentkezz be a Spotify-fiókoddal (Premium), és hozz létre egy kulcsot.</p><p>2. Másold ide, és küldd el a TV-nek.</p>{FORM}<p class=\"s\">A kulcs csak a TV-n marad.</p>"
|
||||
)))
|
||||
};
|
||||
write!(s, "HTTP/1.1 {status}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\nCache-Control: no-store\r\n\r\n{body}", body.len())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
const FORM: &str = "<form method=\"post\"><textarea name=\"key\" rows=\"4\" placeholder=\"API-kulcs\" autofocus></textarea><button>Küldés a TV-nek</button></form>";
|
||||
|
||||
fn page(inner: &str) -> String {
|
||||
format!(
|
||||
"<!doctype html><html lang=\"hu\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><title>Spotify a TV-n</title><style>body{{font-family:system-ui,sans-serif;background:#0b0f0c;color:#eee;margin:0;padding:24px;max-width:560px}}h1{{color:#1ed760;font-size:24px}}a{{color:#1ed760}}textarea{{width:100%;box-sizing:border-box;font:16px monospace;padding:12px;border-radius:12px;border:1px solid #444;background:#151a16;color:#fff}}button{{margin-top:12px;width:100%;padding:14px;border:0;border-radius:24px;background:#1ed760;color:#111;font-size:17px;font-weight:700}}.s{{color:#999;font-size:14px}}</style></head><body>{inner}</body></html>"
|
||||
)
|
||||
}
|
||||
|
||||
/// The value of `name` in an x-www-form-urlencoded body.
|
||||
fn form_value(body: &str, name: &str) -> String {
|
||||
for part in body.split('&') {
|
||||
if let Some((k, v)) = part.split_once('=') {
|
||||
if k == name {
|
||||
return decode(v).trim().to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
String::new()
|
||||
}
|
||||
|
||||
fn decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(b.len());
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
match b[i] {
|
||||
b'+' => out.push(b' '),
|
||||
b'%' if i + 2 < b.len() => {
|
||||
if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
|
||||
out.push(v);
|
||||
i += 2;
|
||||
} else {
|
||||
out.push(b'%');
|
||||
}
|
||||
}
|
||||
c => out.push(c),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn reads_the_form() {
|
||||
assert_eq!(super::form_value("x=1&key=ab%2Bcd+ef%0A", "key"), "ab+cd ef");
|
||||
}
|
||||
}
|
||||
13
src/main.rs
13
src/main.rs
@@ -2,17 +2,21 @@
|
||||
//!
|
||||
//! - 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.
|
||||
//! - Playback: Spotify Soloist (src/soloist.rs), Spotify's own player,
|
||||
//! downloaded on the TV and driven over its local WebSocket.
|
||||
//! - Browsing: a librespot session (src/spotify.rs) and Spotify's internal
|
||||
//! endpoints through it (src/internal.rs).
|
||||
|
||||
mod api;
|
||||
mod app;
|
||||
mod config;
|
||||
mod format;
|
||||
mod internal;
|
||||
mod keyserver;
|
||||
mod nowplaying;
|
||||
mod page;
|
||||
mod screens;
|
||||
mod soloist;
|
||||
mod spotify;
|
||||
mod task;
|
||||
|
||||
@@ -22,7 +26,7 @@ slint::include_modules!();
|
||||
sf_ui::glue!(App);
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info,librespot=info,libmdns=warn")).init();
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info,librespot=info")).init();
|
||||
sf_ui::init()?;
|
||||
|
||||
let ui = App::new()?;
|
||||
@@ -38,6 +42,7 @@ fn main() -> anyhow::Result<()> {
|
||||
|
||||
let glass = sf_ui::Glass::install(&ui, |ui, p| {
|
||||
p.extend(ui.get_glass_signin().iter());
|
||||
p.extend(ui.get_glass_solokey().iter());
|
||||
p.extend(ui.get_glass_page().iter());
|
||||
p.extend(ui.get_glass_page_keyboard().iter());
|
||||
p.extend(ui.get_glass_np().iter());
|
||||
|
||||
@@ -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
|
||||
//! and the queue (Soloist's). 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,6 +14,8 @@ use slint::{Model, ModelRc, VecModel};
|
||||
use crate::api;
|
||||
use crate::app::{Action, Controller, Look};
|
||||
use crate::spotify::{Cmd, Event, Track};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{QueueItem, format, task};
|
||||
|
||||
/// The buttons, left to right.
|
||||
@@ -42,7 +43,6 @@ pub struct NowPlaying {
|
||||
/// (track id, lines, synced); empty lines = none.
|
||||
lyrics: Option<(String, Vec<(u32, String)>, bool)>,
|
||||
lyrics_loading: bool,
|
||||
queue: Vec<api::Track>,
|
||||
panel: Panel,
|
||||
focus: usize,
|
||||
/// 0: the buttons, 1: the progress bar.
|
||||
@@ -70,6 +70,7 @@ impl NowPlaying {
|
||||
|
||||
pub fn on_event(c: &Controller, ev: Event) {
|
||||
let mut new_track = false;
|
||||
let was_playing = c.state.borrow().np.playing;
|
||||
{
|
||||
let mut st = c.state.borrow_mut();
|
||||
let np = &mut st.np;
|
||||
@@ -102,9 +103,20 @@ pub fn on_event(c: &Controller, ev: Event) {
|
||||
np.loading = false;
|
||||
np.set_pos(p);
|
||||
}
|
||||
Event::Unavailable => {
|
||||
Event::Playstate(on) => {
|
||||
let p = np.position();
|
||||
np.playing = on;
|
||||
np.loading = false;
|
||||
np.set_pos(p);
|
||||
}
|
||||
Event::Error(msg) => {
|
||||
drop(st);
|
||||
c.toast("Ez a szám most nem játszható le.", true);
|
||||
c.toast(&msg, true);
|
||||
return;
|
||||
}
|
||||
Event::Queue => {
|
||||
drop(st);
|
||||
sync_queue(c);
|
||||
return;
|
||||
}
|
||||
Event::Shuffle(on) => np.shuffle = on,
|
||||
@@ -122,19 +134,21 @@ pub fn on_event(c: &Controller, ev: Event) {
|
||||
np.playing = false;
|
||||
np.set_pos(p);
|
||||
}
|
||||
Event::Client(name) => {
|
||||
if !name.is_empty() {
|
||||
np.elsewhere = name;
|
||||
}
|
||||
}
|
||||
Event::Status(_) | Event::Pair(_) => {}
|
||||
Event::Status(_) | Event::Pair(_) | Event::Solo(_) => {}
|
||||
}
|
||||
}
|
||||
if new_track {
|
||||
track_changed(c);
|
||||
}
|
||||
if c.state.borrow().screen == "nowplaying" {
|
||||
sync(c);
|
||||
}
|
||||
// Pages mark the playing track and show it in the nav capsule.
|
||||
if new_track {
|
||||
c.track_changed();
|
||||
} else if was_playing != c.state.borrow().np.playing {
|
||||
c.sync_nav();
|
||||
}
|
||||
}
|
||||
|
||||
/// A new track: its cover behind the screen, its like state, lyrics, queue.
|
||||
@@ -168,11 +182,35 @@ fn track_changed(c: &Controller) {
|
||||
}
|
||||
match panel {
|
||||
Panel::Lyrics => load_lyrics(c),
|
||||
Panel::Queue => load_queue(c),
|
||||
Panel::Queue => sync_queue(c),
|
||||
Panel::None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The queue panel from the player's queue.
|
||||
fn sync_queue(c: &Controller) {
|
||||
let Some(ui) = c.ui() else { return };
|
||||
let queue = c.engine.queue();
|
||||
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()));
|
||||
ui.set_np_queue_note(if queue.is_empty() { "A lejátszási sor üres.".into() } else { "".into() });
|
||||
let px = c.px();
|
||||
for (i, t) in queue.iter().take(12).enumerate() {
|
||||
if t.cover.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let m = model.clone();
|
||||
c.images.load(&t.cover, ((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);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn load_cover(c: &Controller, t: &Track) {
|
||||
let Some(ui) = c.ui() else { return };
|
||||
ui.set_np_cover(Default::default());
|
||||
@@ -231,48 +269,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.
|
||||
pub fn open(c: &Controller) {
|
||||
{
|
||||
@@ -293,7 +289,7 @@ 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::Queue => sync_queue(c),
|
||||
Panel::None => {}
|
||||
}
|
||||
let k = c.clone();
|
||||
@@ -422,6 +418,13 @@ fn press(c: &Controller, button: &str) {
|
||||
},
|
||||
);
|
||||
}
|
||||
"queue" => {
|
||||
let next = if panel == Panel::Queue { Panel::None } else { Panel::Queue };
|
||||
c.state.borrow_mut().np.panel = next;
|
||||
if next == Panel::Queue {
|
||||
sync_queue(c);
|
||||
}
|
||||
}
|
||||
"lyrics" => {
|
||||
let next = if panel == Panel::Lyrics { Panel::None } else { Panel::Lyrics };
|
||||
c.state.borrow_mut().np.panel = next;
|
||||
@@ -429,13 +432,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);
|
||||
@@ -496,11 +492,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);
|
||||
}
|
||||
|
||||
@@ -37,15 +37,8 @@ impl ArtistPage {
|
||||
let market = cx.user().country;
|
||||
cx.spawn::<ArtistPage, _>(
|
||||
move || -> anyhow::Result<(Data, Option<bool>)> {
|
||||
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::<Vec<_>>().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 {
|
||||
@@ -103,7 +97,7 @@ impl Screen for ArtistPage {
|
||||
let uri = d.artist.uri.clone();
|
||||
if line == "hero" {
|
||||
match item {
|
||||
"play" | "shuffle" => cx.play(Cmd::Context { uri, start: None, shuffle: item == "shuffle" }),
|
||||
"play" | "shuffle" => cx.play(Cmd::Context { uri, shuffle: item == "shuffle" }),
|
||||
"follow" => {
|
||||
let Some(on) = self.following.map(|f| !f) else { return };
|
||||
let api = cx.api();
|
||||
|
||||
@@ -303,7 +303,7 @@ impl Screen for Collection {
|
||||
cx.play(Cmd::Tracks { uris, start: 0 });
|
||||
}
|
||||
} else {
|
||||
cx.play(Cmd::Context { uri: context, start: None, shuffle });
|
||||
cx.play(Cmd::Context { uri: context, shuffle });
|
||||
}
|
||||
}
|
||||
"save" => self.toggle_saved(cx),
|
||||
|
||||
@@ -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<Vec<Played>>,
|
||||
recent: Option<Vec<Entity>>,
|
||||
playlists: Option<Vec<Playlist>>,
|
||||
liked_total: Option<u32>,
|
||||
top_artists: Option<Vec<Artist>>,
|
||||
top_tracks: Option<Vec<Track>>,
|
||||
artists: Option<Vec<Artist>>,
|
||||
albums: Option<Vec<Album>>,
|
||||
releases: Option<Vec<Album>>,
|
||||
shows: Option<Vec<Show>>,
|
||||
errors: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -38,34 +37,41 @@ impl Home {
|
||||
cx.spawn::<Home, _>(
|
||||
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<T>(r: std::thread::Result<anyhow::Result<T>>, errors: &mut Vec<String>)
|
||||
}
|
||||
}
|
||||
|
||||
/// Recently played tracks, each once (newest first).
|
||||
fn recent_cards(items: &[Played]) -> Vec<crate::page::C> {
|
||||
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<u32>) -> 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 {
|
||||
@@ -105,26 +109,33 @@ impl Screen for Home {
|
||||
lines.push(L::text("loading", "Betöltés…", "caption"));
|
||||
return Spec { lines, frame };
|
||||
}
|
||||
// One step left before anything can play.
|
||||
let solo = cx.solo();
|
||||
if !matches!(solo, crate::soloist::Status::Ready | crate::soloist::Status::Starting) {
|
||||
let (title, text) = crate::screens::settings::solo_text(&solo, &cx.cfg().device_name);
|
||||
let mut n = L::item("solo", format!("Lejátszó: {title}"), text, "", Vec::new());
|
||||
if matches!(solo, crate::soloist::Status::NeedKey | crate::soloist::Status::Failed(_)) {
|
||||
n.chips = vec![crate::page::Ch::new("key", "Kulcs megadása").tone("primary")];
|
||||
}
|
||||
lines.push(n);
|
||||
}
|
||||
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));
|
||||
}
|
||||
@@ -132,20 +143,15 @@ impl Screen for Home {
|
||||
}
|
||||
|
||||
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);
|
||||
if line == "solo" {
|
||||
cx.c.open_key_screen();
|
||||
return;
|
||||
}
|
||||
}
|
||||
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 {
|
||||
|
||||
@@ -16,7 +16,7 @@ use crate::api::{self, Album, Artist, Playlist, Show, Track};
|
||||
use crate::app::{Controller, Cx, Screen};
|
||||
use crate::format;
|
||||
use crate::page::{C, CARD, L};
|
||||
use crate::spotify::{Cmd, Start};
|
||||
use crate::spotify::Cmd;
|
||||
use crate::task;
|
||||
|
||||
/// The screen of a top navigation section.
|
||||
@@ -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<u32>) -> C {
|
||||
let mut c = C::new("liked", "Kedvelt dalok", "");
|
||||
c.caption = "Kedvelt dalok".into();
|
||||
@@ -162,21 +154,17 @@ pub fn row_index(line: &str) -> Option<usize> {
|
||||
line.rsplit_once('#')?.1.parse().ok()
|
||||
}
|
||||
|
||||
/// Plays `t` from a list: in `context` if given, else the list's tracks.
|
||||
pub fn play_from(cx: &Cx, context: &str, tracks: &[Track], i: usize) {
|
||||
/// Plays `t` from a list, the rest of the list queued after it (Soloist
|
||||
/// can start a context only at its beginning).
|
||||
pub fn play_from(cx: &Cx, _context: &str, tracks: &[Track], i: usize) {
|
||||
let Some(t) = tracks.get(i) else { return };
|
||||
if !t.playable() {
|
||||
cx.toast("Ez a szám nem játszható le.");
|
||||
return;
|
||||
}
|
||||
let shuffle = cx.c.state.borrow().np.shuffle;
|
||||
if context.is_empty() {
|
||||
let uris: Vec<String> = tracks.iter().filter(|t| t.playable()).map(|t| t.uri.clone()).collect();
|
||||
let start = uris.iter().position(|u| *u == t.uri).unwrap_or(0) as u32;
|
||||
cx.play(Cmd::Tracks { uris, start });
|
||||
} else {
|
||||
cx.play(Cmd::Context { uri: context.to_string(), start: Some(Start::Uri(t.uri.clone())), shuffle });
|
||||
}
|
||||
}
|
||||
|
||||
/// Opens the page of a card id (see the module docs); true if it was one.
|
||||
@@ -192,13 +180,8 @@ pub fn open_card(cx: &Cx, key: &str) -> bool {
|
||||
} else if let Some(id) = key.strip_prefix("ar:") {
|
||||
cx.push(Box::new(artist::ArtistPage::new(id)));
|
||||
} else if let Some(rest) = key.strip_prefix("t:") {
|
||||
let (uri, context) = rest.split_once('|').unwrap_or((rest, ""));
|
||||
let shuffle = cx.c.state.borrow().np.shuffle;
|
||||
if context.is_empty() {
|
||||
let uri = rest.split('|').next().unwrap_or(rest);
|
||||
cx.play(Cmd::Tracks { uris: vec![uri.to_string()], start: 0 });
|
||||
} else {
|
||||
cx.play(Cmd::Context { uri: context.to_string(), start: Some(Start::Uri(uri.to_string())), shuffle });
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
@@ -246,15 +229,8 @@ fn open_track_menu(c: &Controller, t: Track, liked: Option<bool>) {
|
||||
let c2 = c.clone();
|
||||
match actions.get(i).copied() {
|
||||
Some("queue") => {
|
||||
let uri = t.uri.clone();
|
||||
task::spawn(
|
||||
move || api.add_to_queue(&uri),
|
||||
move |r| match r {
|
||||
Ok(()) => c2.toast("Hozzáadva a lejátszási sorhoz", false),
|
||||
Err(e) if api::status_of(&e) == Some(404) => c2.toast("Előbb indíts el valamit, utána lehet a sorba tenni.", true),
|
||||
Err(e) => c2.toast(&api::describe(&e), true),
|
||||
},
|
||||
);
|
||||
c.engine.send(Cmd::AddToQueue(t.uri.clone()));
|
||||
c.toast("Hozzáadva a lejátszási sorhoz", false);
|
||||
}
|
||||
Some(a @ ("like" | "unlike")) => {
|
||||
let on = a == "like";
|
||||
|
||||
@@ -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")),
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! Beállítások: the account (sign out), the Connect name, sound quality,
|
||||
//! loudness normalisation, autoplay, the look.
|
||||
//! Beállítások: the account (sign out), the player (Soloist: its state and
|
||||
//! key), the Connect name, the look.
|
||||
|
||||
use std::any::Any;
|
||||
|
||||
@@ -32,22 +32,20 @@ impl Screen for Settings {
|
||||
let name = if user.name().is_empty() { "Spotify fiók".to_string() } else { user.name() };
|
||||
lines.push(L::item("account", name, meta, "Kijelentkezés után a TV újra a telefonról kér bejelentkezést.", vec![Ch::new("signout", "Kijelentkezés").tone("danger")]));
|
||||
|
||||
lines.push(L::heading("play-h", "Lejátszó"));
|
||||
let (state, note) = solo_text(&cx.solo(), &cfg.device_name);
|
||||
let key_chip = if cfg.soloist_key.is_empty() { Ch::new("key", "Kulcs megadása").tone("primary") } else { Ch::new("key", "Másik kulcs") };
|
||||
lines.push(L::item("solo", "Spotify Soloist", state, note, vec![key_chip]));
|
||||
|
||||
lines.push(L::heading("dev-h", "Spotify Connect"));
|
||||
lines.push(L::chips("name", "", vec![Ch::field("name", &cfg.device_name, "A TV neve", "tv")]));
|
||||
lines.push(L::text("name-note", format!("A telefon ezen a néven mutatja a TV-t. {RESTART}"), "caption"));
|
||||
|
||||
lines.push(L::heading("play-h", "Lejátszás"));
|
||||
let q = |id: &str, t: &str, v: u32| Ch::new(id, t).active(cfg.bitrate == v);
|
||||
lines.push(L::chips("quality", "HANGMINŐSÉG", vec![q("96", "Alacsony · 96 kbit/s", 96), q("160", "Normál · 160 kbit/s", 160), q("320", "Nagyon magas · 320 kbit/s", 320)]));
|
||||
lines.push(L::chips("normalise", "HANGERŐ-KIEGYENLÍTÉS", vec![Ch::new("on", "Be").active(cfg.normalise), Ch::new("off", "Ki").active(!cfg.normalise)]));
|
||||
lines.push(L::chips("autoplay", "AUTOMATIKUS LEJÁTSZÁS A LISTA VÉGÉN", vec![Ch::new("on", "Be").active(cfg.autoplay), Ch::new("off", "Ki").active(!cfg.autoplay)]));
|
||||
lines.push(L::text("play-note", RESTART, "caption"));
|
||||
|
||||
lines.push(L::heading("look-h", "Megjelenés"));
|
||||
let g = |id: &str, t: &str| Ch::new(id, t).active(cfg.glass == id);
|
||||
lines.push(L::chips("glass", "", vec![g("auto", "Automatikus"), g("full", "Teljes üveg"), g("light", "Könnyű üveg"), g("off", "Matt")]));
|
||||
lines.push(L::text("look-note", "Automatikus: a TV a grafikus chip ereje szerint választ.", "caption"));
|
||||
lines.push(L::text("about", format!("Spotify for Fennec OS {} · librespot", env!("CARGO_PKG_VERSION")), "caption"));
|
||||
lines.push(L::text("about", format!("Spotify for Fennec OS {} · lejátszás: Spotify Soloist · böngészés: librespot", env!("CARGO_PKG_VERSION")), "caption"));
|
||||
Spec { lines, frame: Frame { nav: Some(3), ..Frame::default() } }
|
||||
}
|
||||
|
||||
@@ -75,13 +73,7 @@ impl Screen for Settings {
|
||||
},
|
||||
);
|
||||
}
|
||||
"quality" => {
|
||||
if let Ok(v) = item.parse() {
|
||||
cx.set_cfg(|c| c.bitrate = v);
|
||||
}
|
||||
}
|
||||
"normalise" => cx.set_cfg(|c| c.normalise = item == "on"),
|
||||
"autoplay" => cx.set_cfg(|c| c.autoplay = item == "on"),
|
||||
"solo" => cx.c.open_key_screen(),
|
||||
"glass" => {
|
||||
cx.set_cfg(|c| c.glass = item.to_string());
|
||||
crate::config::apply_look(&cx.c.glass, item);
|
||||
@@ -94,3 +86,16 @@ impl Screen for Settings {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The player's state for people: (state, what to do).
|
||||
pub fn solo_text(s: &crate::soloist::Status, name: &str) -> (String, String) {
|
||||
use crate::soloist::Status::*;
|
||||
match s {
|
||||
NeedKey => ("Nincs kulcs".into(), "Lejátszáshoz kell egy kulcs: developer.spotify.com/dashboard/soloist".into()),
|
||||
Downloading => ("Letöltés…".into(), "A lejátszó letöltése a Spotifytól.".into()),
|
||||
Starting => ("Indul…".into(), String::new()),
|
||||
NotPaired(n) => ("Még nincs párosítva".into(), format!("Nyisd meg a Spotify appot a telefonodon (ugyanazon a Wi-Fin), koppints az eszközök ikonra, és válaszd: „{}”.", if n.is_empty() { name } else { n })),
|
||||
Ready => ("Kész".into(), "A lejátszó működik, a telefonról is irányítható.".into()),
|
||||
Failed(m) => ("Hiba".into(), m.clone()),
|
||||
}
|
||||
}
|
||||
|
||||
484
src/soloist.rs
Normal file
484
src/soloist.rs
Normal file
@@ -0,0 +1,484 @@
|
||||
//! Spotify Soloist: Spotify's own headless Linux player, which plays here.
|
||||
//! (librespot is refused the audio keys; Soloist is not.)
|
||||
//!
|
||||
//! - Spotify does not allow redistributing Soloist, so the TV downloads it
|
||||
//! from Spotify (soloist-builds.spotifycdn.com) into the app's data folder,
|
||||
//! and again before a build gets old (builds expire after 90 days; an
|
||||
//! expired one exits with code 10).
|
||||
//! - It needs the user's own Soloist API key (developer.spotify.com/dashboard/soloist)
|
||||
//! and, once, to be picked in the Spotify app on a phone (Connect pairing).
|
||||
//! - It is the Spotify Connect device; this app drives it over its local
|
||||
//! WebSocket API (127.0.0.1, port from <data>/ws.port) and turns its
|
||||
//! events into `spotify::Event`s.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::{SinkExt, StreamExt};
|
||||
use serde_json::{Value, json};
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
use crate::spotify::{Event, Track};
|
||||
|
||||
const BASE: &str = "https://soloist-builds.spotifycdn.com";
|
||||
/// Download a new build when the one we have is older than this.
|
||||
const MAX_AGE: Duration = Duration::from_secs(45 * 24 * 3600);
|
||||
|
||||
/// Where Soloist stands.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Status {
|
||||
/// No API key yet.
|
||||
NeedKey,
|
||||
Downloading,
|
||||
Starting,
|
||||
/// Running, but not signed in: pick the TV once in the phone's Spotify app.
|
||||
NotPaired(String),
|
||||
Ready,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
fn dir() -> PathBuf {
|
||||
crate::config::home().join(".local").join("share").join("spotify-tv").join("soloist")
|
||||
}
|
||||
|
||||
fn data_dir() -> PathBuf {
|
||||
dir().join("data")
|
||||
}
|
||||
|
||||
fn archive_name() -> Option<&'static str> {
|
||||
if !cfg!(target_os = "linux") {
|
||||
return None;
|
||||
}
|
||||
match std::env::consts::ARCH {
|
||||
"aarch64" => Some("soloist_release_arm64.tar.gz"),
|
||||
"x86_64" => Some("soloist_release_x86_64.tar.gz"),
|
||||
"arm" => Some("soloist_release_arm32.tar.gz"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads and unpacks the current build (blocking).
|
||||
fn download() -> anyhow::Result<()> {
|
||||
let name = archive_name().ok_or_else(|| anyhow::anyhow!("A Soloist ezen a rendszeren nem fut (csak Linuxon)"))?;
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(300))).build().into();
|
||||
let resp = agent.get(&format!("{BASE}/{name}")).call()?;
|
||||
let reader = resp.into_body().into_reader();
|
||||
let mut archive = tar::Archive::new(flate2::read::GzDecoder::new(reader));
|
||||
let d = dir();
|
||||
std::fs::create_dir_all(&d)?;
|
||||
let tmp = d.join("soloist.new");
|
||||
let mut found = false;
|
||||
for entry in archive.entries()? {
|
||||
let mut entry = entry?;
|
||||
let path = entry.path()?.into_owned();
|
||||
if path.file_name().and_then(|n| n.to_str()) == Some("soloist") {
|
||||
entry.unpack(&tmp)?;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
anyhow::bail!("a letöltött csomagban nincs soloist");
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o755))?;
|
||||
}
|
||||
std::fs::rename(&tmp, d.join("soloist"))?;
|
||||
std::fs::write(d.join("downloaded"), now_secs().to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn now_secs() -> u64 {
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
fn needs_download() -> bool {
|
||||
let d = dir();
|
||||
if !d.join("soloist").exists() {
|
||||
return true;
|
||||
}
|
||||
let at: u64 = std::fs::read_to_string(d.join("downloaded")).ok().and_then(|s| s.trim().parse().ok()).unwrap_or(0);
|
||||
now_secs().saturating_sub(at) > MAX_AGE.as_secs()
|
||||
}
|
||||
|
||||
/// What the app keeps of Soloist's state.
|
||||
#[derive(Default)]
|
||||
pub struct Shared {
|
||||
pub playing: bool,
|
||||
pub active: bool,
|
||||
/// The next tracks (title, artist, cover).
|
||||
pub queue: Vec<Track>,
|
||||
}
|
||||
|
||||
/// Runs Soloist for as long as the app runs: download, start, restart,
|
||||
/// talk. `key` changes restart it; `cmds` go to its WebSocket.
|
||||
pub async fn supervise(
|
||||
name: String,
|
||||
mut key: watch::Receiver<String>,
|
||||
mut cmds: mpsc::UnboundedReceiver<Value>,
|
||||
shared: Arc<Mutex<Shared>>,
|
||||
events: Arc<dyn Fn(Event) + Send + Sync>,
|
||||
status: Arc<dyn Fn(Status) + Send + Sync>,
|
||||
) {
|
||||
let mut failures = 0u32;
|
||||
let mut force_download = false;
|
||||
loop {
|
||||
let k = key.borrow().clone();
|
||||
if k.trim().is_empty() {
|
||||
status(Status::NeedKey);
|
||||
if key.changed().await.is_err() {
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if force_download || needs_download() {
|
||||
status(Status::Downloading);
|
||||
match tokio::task::spawn_blocking(download).await {
|
||||
Ok(Ok(())) => {
|
||||
force_download = false;
|
||||
log::info!("soloist: downloaded");
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::warn!("soloist download: {e:#}");
|
||||
// An old build may still work.
|
||||
if !dir().join("soloist").exists() || force_download {
|
||||
status(Status::Failed(format!("A Soloist letöltése nem sikerült: {e}")));
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
Err(_) => continue,
|
||||
}
|
||||
}
|
||||
status(Status::Starting);
|
||||
let code = run_once(&name, k.trim(), &mut key, &mut cmds, &shared, &events, &status).await;
|
||||
match code {
|
||||
// Expired build: get a new one.
|
||||
Some(10) => force_download = true,
|
||||
// The key changed: restart at once.
|
||||
None => {
|
||||
failures = 0;
|
||||
continue;
|
||||
}
|
||||
Some(c) => log::warn!("soloist exited with code {c}"),
|
||||
}
|
||||
failures += 1;
|
||||
if failures >= 3 {
|
||||
status(Status::Failed("A Soloist nem indul. Ellenőrizd a kulcsot a Beállításokban.".into()));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs((2u64 << failures.min(4)).min(30))).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// One run of the daemon. Returns its exit code, or None when the key changed.
|
||||
async fn run_once(
|
||||
name: &str,
|
||||
key: &str,
|
||||
key_rx: &mut watch::Receiver<String>,
|
||||
cmds: &mut mpsc::UnboundedReceiver<Value>,
|
||||
shared: &Arc<Mutex<Shared>>,
|
||||
events: &Arc<dyn Fn(Event) + Send + Sync>,
|
||||
status: &Arc<dyn Fn(Status) + Send + Sync>,
|
||||
) -> Option<i32> {
|
||||
let data = data_dir();
|
||||
let cache = crate::config::home().join(".cache").join("spotify-tv").join("soloist");
|
||||
let _ = std::fs::create_dir_all(&data);
|
||||
let _ = std::fs::create_dir_all(&cache);
|
||||
let _ = std::fs::remove_file(data.join("ws.port"));
|
||||
let mut child = match tokio::process::Command::new(dir().join("soloist"))
|
||||
.args(["-n", name, "-k", key, "-w", "127.0.0.1:0", "-i", "100", "-z", "300"])
|
||||
.arg("-D")
|
||||
.arg(&data)
|
||||
.arg("-C")
|
||||
.arg(&cache)
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
{
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::warn!("soloist: {e}");
|
||||
status(Status::Failed(format!("A Soloist nem indul: {e}")));
|
||||
return Some(-1);
|
||||
}
|
||||
};
|
||||
// Its log lines into ours.
|
||||
for out in [child.stdout.take().map(|o| Box::new(o) as Box<dyn tokio::io::AsyncRead + Unpin + Send>), child.stderr.take().map(|o| Box::new(o) as _)].into_iter().flatten() {
|
||||
tokio::spawn(async move {
|
||||
let mut lines = tokio::io::BufReader::new(out).lines();
|
||||
while let Ok(Some(l)) = lines.next_line().await {
|
||||
log::info!("soloist: {l}");
|
||||
}
|
||||
});
|
||||
}
|
||||
// Wait for its WebSocket port.
|
||||
let mut port = None;
|
||||
for _ in 0..100 {
|
||||
if let Some(p) = std::fs::read_to_string(data.join("ws.port")).ok().and_then(|s| s.trim().parse::<u16>().ok()) {
|
||||
port = Some(p);
|
||||
break;
|
||||
}
|
||||
if let Ok(Some(st)) = child.try_wait() {
|
||||
return Some(st.code().unwrap_or(-1));
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(150)).await;
|
||||
}
|
||||
let Some(port) = port else {
|
||||
let _ = child.kill().await;
|
||||
status(Status::Failed("A Soloist nem nyitotta meg a vezérlőportját".into()));
|
||||
return Some(-1);
|
||||
};
|
||||
let ws = match tokio_tungstenite::connect_async(format!("ws://127.0.0.1:{port}")).await {
|
||||
Ok((ws, _)) => ws,
|
||||
Err(e) => {
|
||||
log::warn!("soloist ws: {e}");
|
||||
let _ = child.kill().await;
|
||||
return Some(-1);
|
||||
}
|
||||
};
|
||||
let (mut tx, mut rx) = ws.split();
|
||||
let _ = tx.send(Message::text(json!({"type": "command", "command": "get_auth_state"}).to_string())).await;
|
||||
let mut tracker = Tracker::default();
|
||||
loop {
|
||||
tokio::select! {
|
||||
st = child.wait() => {
|
||||
let code = st.ok().and_then(|s| s.code()).unwrap_or(-1);
|
||||
events(Event::Stopped);
|
||||
return Some(code);
|
||||
}
|
||||
_ = key_rx.changed() => {
|
||||
let _ = child.kill().await;
|
||||
return None;
|
||||
}
|
||||
msg = rx.next() => {
|
||||
match msg {
|
||||
Some(Ok(Message::Text(t))) => {
|
||||
if let Ok(v) = serde_json::from_str::<Value>(t.as_str()) {
|
||||
tracker.handle(&v, shared, events, status, name);
|
||||
}
|
||||
}
|
||||
Some(Ok(_)) => {}
|
||||
_ => {
|
||||
// The socket closed: the daemon is going away; wait for it.
|
||||
let st = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;
|
||||
let _ = child.kill().await;
|
||||
return Some(st.ok().and_then(|s| s.ok()).and_then(|s| s.code()).unwrap_or(-1));
|
||||
}
|
||||
}
|
||||
}
|
||||
cmd = cmds.recv() => {
|
||||
let Some(cmd) = cmd else { let _ = child.kill().await; return Some(0) };
|
||||
log::debug!("soloist <- {cmd}");
|
||||
if tx.send(Message::text(cmd.to_string())).await.is_err() {
|
||||
let _ = child.kill().await;
|
||||
return Some(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns Soloist's events into the app's.
|
||||
#[derive(Default)]
|
||||
struct Tracker {
|
||||
status: String,
|
||||
track_uri: String,
|
||||
}
|
||||
|
||||
fn position_of(p: &Value) -> Option<u32> {
|
||||
let ms = p["position_ms"].as_f64()?;
|
||||
let at = p["timestamp_ms"].as_f64().unwrap_or(0.0);
|
||||
let speed = p["speed"].as_f64().unwrap_or(0.0);
|
||||
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() as f64).unwrap_or(0.0);
|
||||
let cur = if at > 0.0 && speed > 0.0 { ms + (now - at).max(0.0) * speed } else { ms };
|
||||
Some(cur.max(0.0) as u32)
|
||||
}
|
||||
|
||||
/// A Soloist item (track or episode) as the app's track.
|
||||
pub fn track_of(item: &Value) -> Option<Track> {
|
||||
let uri = item["uri"].as_str()?.to_string();
|
||||
let d = &item["decorations"];
|
||||
let name = d["identity"]["name"].as_str().unwrap_or("").to_string();
|
||||
let artists: Vec<(String, String)> = d["creators"]
|
||||
.as_array()
|
||||
.map(|a| {
|
||||
a.iter()
|
||||
.map(|c| {
|
||||
let e = &c["entity"];
|
||||
let id = e["uri"].as_str().unwrap_or("").rsplit(':').next().unwrap_or("").to_string();
|
||||
(id, e["decorations"]["identity"]["name"].as_str().unwrap_or("").to_string())
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let parent = &d["parent"]["entity"];
|
||||
let album = parent["decorations"]["identity"]["name"].as_str().unwrap_or("").to_string();
|
||||
let covers = d["visual_identity"]["cover"].as_array().cloned().unwrap_or_default();
|
||||
let pick = |size: &str| covers.iter().find(|c| c["size"].as_str() == Some(size)).and_then(|c| c["url"].as_str()).map(str::to_string);
|
||||
let cover = pick("large").or_else(|| pick("xlarge")).or_else(|| pick("default")).or_else(|| covers.first().and_then(|c| c["url"].as_str()).map(str::to_string)).unwrap_or_default();
|
||||
let episode = item["entity_type"].as_str() == Some("episode");
|
||||
Some(Track {
|
||||
id: uri.rsplit(':').next().unwrap_or("").to_string(),
|
||||
uri,
|
||||
name,
|
||||
artists: if artists.is_empty() && episode { vec![(String::new(), album.clone())] } else { artists },
|
||||
album,
|
||||
cover,
|
||||
duration_ms: d["playback"]["duration_ms"].as_u64().unwrap_or(0) as u32,
|
||||
episode,
|
||||
explicit: d["playback"]["content_ratings"].as_array().is_some_and(|r| !r.is_empty()),
|
||||
})
|
||||
}
|
||||
|
||||
impl Tracker {
|
||||
fn handle(&mut self, v: &Value, shared: &Arc<Mutex<Shared>>, events: &Arc<dyn Fn(Event) + Send + Sync>, status: &Arc<dyn Fn(Status) + Send + Sync>, name: &str) {
|
||||
match v["type"].as_str().unwrap_or("") {
|
||||
"auth_state" => {
|
||||
if v["logged_in"].as_bool() == Some(true) {
|
||||
status(Status::Ready);
|
||||
} else {
|
||||
status(Status::NotPaired(v["device_name"].as_str().unwrap_or(name).to_string()));
|
||||
}
|
||||
if let Some(a) = v["is_active"].as_bool() {
|
||||
self.active(a, shared, events);
|
||||
}
|
||||
}
|
||||
"playback_state" => {
|
||||
if let Some(t) = track_of(&v["item"]) {
|
||||
self.track(t, events);
|
||||
}
|
||||
self.options(&v["options"], events);
|
||||
if let Some(a) = v["is_active"].as_bool() {
|
||||
self.active(a, shared, events);
|
||||
}
|
||||
self.status = v["status"].as_str().unwrap_or("").to_string();
|
||||
self.position(&v["position"], shared, events);
|
||||
}
|
||||
"track_changed" => {
|
||||
if let Some(t) = track_of(&v["item"]) {
|
||||
self.track(t, events);
|
||||
}
|
||||
}
|
||||
"playback_changed" => {
|
||||
self.status = v["status"].as_str().unwrap_or("").to_string();
|
||||
match self.status.as_str() {
|
||||
"buffering" => events(Event::Loading),
|
||||
"idle" => {
|
||||
shared.lock().unwrap().playing = false;
|
||||
events(Event::Stopped);
|
||||
}
|
||||
_ => {
|
||||
// The position follows in position_sync; keep the old one meanwhile.
|
||||
let playing = self.status == "playing";
|
||||
shared.lock().unwrap().playing = playing;
|
||||
events(Event::Playstate(playing));
|
||||
}
|
||||
}
|
||||
}
|
||||
"position_sync" => self.position(&v["position"], shared, events),
|
||||
"options_changed" => self.options(&v["options"], events),
|
||||
"device_changed" => {
|
||||
if let Some(a) = v["is_active"].as_bool() {
|
||||
self.active(a, shared, events);
|
||||
}
|
||||
}
|
||||
"queue_changed" => {
|
||||
let up: Vec<Track> = v["upcoming"].as_array().map(|a| a.iter().filter_map(|e| track_of(&e["item"])).collect()).unwrap_or_default();
|
||||
shared.lock().unwrap().queue = up;
|
||||
events(Event::Queue);
|
||||
}
|
||||
"error" => {
|
||||
let msg = v["message"].as_str().unwrap_or("").to_string();
|
||||
log::warn!("soloist error: {msg}");
|
||||
if msg.contains("authentication") {
|
||||
events(Event::Error("Előbb válaszd ki ezt a TV-t egyszer a telefonod Spotify appjában.".into()));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn track(&mut self, t: Track, events: &Arc<dyn Fn(Event) + Send + Sync>) {
|
||||
if t.uri != self.track_uri {
|
||||
self.track_uri = t.uri.clone();
|
||||
}
|
||||
events(Event::Track(t));
|
||||
}
|
||||
|
||||
fn active(&mut self, a: bool, shared: &Arc<Mutex<Shared>>, events: &Arc<dyn Fn(Event) + Send + Sync>) {
|
||||
let was = std::mem::replace(&mut shared.lock().unwrap().active, a);
|
||||
if was != a {
|
||||
events(Event::Active(a));
|
||||
}
|
||||
}
|
||||
|
||||
fn options(&mut self, o: &Value, events: &Arc<dyn Fn(Event) + Send + Sync>) {
|
||||
if let Some(s) = o["shuffle"].as_bool() {
|
||||
events(Event::Shuffle(s));
|
||||
}
|
||||
if let Some(r) = o["repeat"].as_str() {
|
||||
events(Event::Repeat(r != "off", r == "track"));
|
||||
}
|
||||
}
|
||||
|
||||
fn position(&mut self, p: &Value, shared: &Arc<Mutex<Shared>>, events: &Arc<dyn Fn(Event) + Send + Sync>) {
|
||||
let Some(ms) = position_of(p) else { return };
|
||||
let moving = p["speed"].as_f64().unwrap_or(0.0) > 0.0;
|
||||
let playing = moving || self.status == "playing";
|
||||
shared.lock().unwrap().playing = playing;
|
||||
events(if playing { Event::Playing(ms) } else { Event::Paused(ms) });
|
||||
}
|
||||
}
|
||||
|
||||
/// The WebSocket command for one action.
|
||||
pub fn command(name: &str, extra: Value) -> Value {
|
||||
let mut c = json!({"type": "command", "command": name});
|
||||
if let (Some(o), Some(e)) = (c.as_object_mut(), extra.as_object()) {
|
||||
for (k, v) in e {
|
||||
o.insert(k.clone(), v.clone());
|
||||
}
|
||||
}
|
||||
c
|
||||
}
|
||||
|
||||
/// Forgets the pairing (sign out).
|
||||
pub fn forget_pairing() {
|
||||
let d = data_dir();
|
||||
if let Ok(rd) = std::fs::read_dir(&d) {
|
||||
for e in rd.flatten() {
|
||||
let p = e.path();
|
||||
let _ = if p.is_dir() { std::fs::remove_dir_all(&p) } else { std::fs::remove_file(&p) };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_items() {
|
||||
let item = json!({
|
||||
"uri": "spotify:track:abc",
|
||||
"entity_type": "track",
|
||||
"decorations": {
|
||||
"identity": {"name": "Song"},
|
||||
"visual_identity": {"cover": [{"url": "https://i/small", "size": "small"}, {"url": "https://i/large", "size": "large"}]},
|
||||
"parent": {"entity": {"uri": "spotify:album:x", "decorations": {"identity": {"name": "Album"}}}},
|
||||
"creators": [{"entity": {"uri": "spotify:artist:a1", "decorations": {"identity": {"name": "Artist"}}}}],
|
||||
"playback": {"duration_ms": 210000, "content_ratings": []}
|
||||
}
|
||||
});
|
||||
let t = track_of(&item).unwrap();
|
||||
assert_eq!((t.id.as_str(), t.name.as_str(), t.album.as_str(), t.cover.as_str(), t.duration_ms), ("abc", "Song", "Album", "https://i/large", 210000));
|
||||
assert_eq!(t.artists, vec![("a1".to_string(), "Artist".to_string())]);
|
||||
let c = command("seek", json!({"position_ms": 5}));
|
||||
assert_eq!(c, json!({"type": "command", "command": "seek", "position_ms": 5}));
|
||||
}
|
||||
}
|
||||
423
src/spotify.rs
423
src/spotify.rs
@@ -1,42 +1,31 @@
|
||||
//! The Spotify side: a librespot session with Spotify Connect (Spirc), the
|
||||
//! zeroconf sign-in and the player. It runs on its own tokio runtime; the UI
|
||||
//! sends `Cmd`s and gets `Event`s on the UI thread.
|
||||
//! The Spotify side, on its own tokio runtime. The UI sends `Cmd`s and gets
|
||||
//! `Event`s on the UI thread.
|
||||
//!
|
||||
//! Sign-in, two ways at once (whichever comes first):
|
||||
//! - Spotify Connect: the TV announces itself on the local network
|
||||
//! (zeroconf). The Spotify app on a phone lists it among its devices;
|
||||
//! picking it hands over the credentials.
|
||||
//! - Pairing code (OAuth device flow, like Spotify's own TV apps): the TV
|
||||
//! shows a QR code and a short code; the phone signs in at
|
||||
//! spotify.com/pair, the TV polls for the token.
|
||||
//! - Playback: Spotify Soloist (src/soloist.rs), Spotify's own player. It is
|
||||
//! the Spotify Connect device (the phone sees and controls it). librespot
|
||||
//! cannot play any more: Spotify refuses it the audio keys.
|
||||
//! - Browsing, the library, lyrics: a librespot session (src/internal.rs).
|
||||
//!
|
||||
//! The credentials are kept in `$HOME/.cache/spotify-tv` for the next start.
|
||||
//! A Premium account is needed (librespot plays nothing else).
|
||||
//!
|
||||
//! Playback goes through Spirc, so the TV is a full Connect device: the phone
|
||||
//! can control it, and playback can move between the TV and other devices.
|
||||
//! librespot sign-in: a pairing code (OAuth device flow, like Spotify's own
|
||||
//! TV apps): the TV shows a QR code and a short code; the phone signs in at
|
||||
//! spotify.com/pair, the TV polls for the token. The credentials are kept in
|
||||
//! `$HOME/.cache/spotify-tv` for the next start. Soloist signs in on its own,
|
||||
//! once: the phone picks the TV in its device list. A Premium account is
|
||||
//! needed for both.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use librespot_connect::{ConnectConfig, LoadContextOptions, LoadRequest, LoadRequestOptions, Options, PlayingTrack, Spirc};
|
||||
use librespot_core::authentication::Credentials;
|
||||
use librespot_core::cache::Cache;
|
||||
use librespot_core::config::{DeviceType, SessionConfig};
|
||||
use librespot_core::config::SessionConfig;
|
||||
use librespot_core::{Session, SpotifyId};
|
||||
use librespot_metadata::audio::{AudioItem, UniqueFields};
|
||||
use librespot_playback::audio_backend;
|
||||
use librespot_playback::config::{AudioFormat, Bitrate, PlayerConfig};
|
||||
use librespot_playback::mixer::{self, MixerConfig};
|
||||
use librespot_playback::player::{Player, PlayerEvent};
|
||||
use tokio::sync::mpsc;
|
||||
use serde_json::json;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// Scopes of the Web API token (browsing, library, queue).
|
||||
const SCOPES: &str = "user-read-private,user-read-email,playlist-read-private,playlist-read-collaborative,playlist-modify-private,playlist-modify-public,user-library-read,user-library-modify,user-follow-read,user-follow-modify,user-top-read,user-read-recently-played,user-read-playback-state,user-modify-playback-state,user-read-currently-playing,streaming";
|
||||
use crate::soloist::{self, command};
|
||||
|
||||
/// The track (or episode) that plays.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
@@ -59,9 +48,10 @@ impl Track {
|
||||
}
|
||||
}
|
||||
|
||||
/// The librespot session (browsing).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Status {
|
||||
/// No credentials: waiting for a phone (device name).
|
||||
/// No credentials: show the pairing code (device name).
|
||||
SignIn(String),
|
||||
Connecting,
|
||||
/// Signed in (user name).
|
||||
@@ -82,26 +72,30 @@ pub enum Event {
|
||||
Status(Status),
|
||||
/// A new pairing code (None: none could be had, e.g. no network).
|
||||
Pair(Option<Pair>),
|
||||
/// The player (Soloist).
|
||||
Solo(soloist::Status),
|
||||
Track(Track),
|
||||
Loading,
|
||||
Playing(u32),
|
||||
Paused(u32),
|
||||
/// Playing or paused, the position unchanged.
|
||||
Playstate(bool),
|
||||
Seeked(u32),
|
||||
Stopped,
|
||||
Unavailable,
|
||||
Shuffle(bool),
|
||||
Repeat(bool, bool),
|
||||
/// This TV became (or stopped being) the active Connect device.
|
||||
Active(bool),
|
||||
/// Another device (its name) took over the playback.
|
||||
Client(String),
|
||||
/// The queue changed (Engine::queue).
|
||||
Queue,
|
||||
/// Something to tell the user.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
pub enum Cmd {
|
||||
/// Plays `context` (an album, playlist, artist, show, "spotify:user:<u>:collection"),
|
||||
/// from track `start` (a uri) or index, optionally shuffled.
|
||||
Context { uri: String, start: Option<Start>, shuffle: bool },
|
||||
/// Plays a list of track uris from index `start`.
|
||||
/// Plays an album, playlist, artist, show, or "spotify:user:<u>:collection".
|
||||
Context { uri: String, shuffle: bool },
|
||||
/// Plays `uris[start]`, the ones after it queued.
|
||||
Tracks { uris: Vec<String>, start: u32 },
|
||||
PlayPause,
|
||||
Play,
|
||||
@@ -112,23 +106,25 @@ pub enum Cmd {
|
||||
Shuffle(bool),
|
||||
/// (context, track)
|
||||
Repeat(bool, bool),
|
||||
AddToQueue(String),
|
||||
SignOut,
|
||||
/// The app closes: leave Spotify Connect cleanly.
|
||||
/// The app closes.
|
||||
Quit,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Start {
|
||||
Uri(String),
|
||||
}
|
||||
/// How many of a list's next tracks get queued after the one picked.
|
||||
const QUEUE_AHEAD: usize = 30;
|
||||
|
||||
/// Cheap to clone; usable from any thread.
|
||||
#[derive(Clone)]
|
||||
pub struct Engine {
|
||||
rt: Arc<tokio::runtime::Runtime>,
|
||||
cmd: mpsc::UnboundedSender<Cmd>,
|
||||
solo: mpsc::UnboundedSender<serde_json::Value>,
|
||||
key: Arc<watch::Sender<String>>,
|
||||
shared: Arc<Mutex<soloist::Shared>>,
|
||||
session: Arc<Mutex<Option<Session>>>,
|
||||
/// Mock mode (UI work without an account): no librespot at all.
|
||||
/// Mock mode (UI work without an account): no librespot, no Soloist.
|
||||
mock: bool,
|
||||
/// Set when the engine's loop has ended (after `Cmd::Quit`).
|
||||
stopped: Arc<std::sync::atomic::AtomicBool>,
|
||||
@@ -143,12 +139,20 @@ impl Engine {
|
||||
pub fn start(cfg: &Config, events: impl Fn(Event) + Send + Sync + 'static) -> Engine {
|
||||
let rt = Arc::new(tokio::runtime::Builder::new_multi_thread().worker_threads(2).enable_all().thread_name("spotify").build().expect("tokio runtime"));
|
||||
let (tx, rx) = mpsc::unbounded_channel();
|
||||
let (solo_tx, solo_rx) = mpsc::unbounded_channel();
|
||||
let (key_tx, key_rx) = watch::channel(cfg.soloist_key.clone());
|
||||
let session = Arc::new(Mutex::new(None));
|
||||
let shared = Arc::new(Mutex::new(soloist::Shared::default()));
|
||||
let mock = std::env::var_os("SPOTIFY_MOCK").is_some();
|
||||
let stopped = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let engine = Engine { rt: rt.clone(), cmd: tx, session: session.clone(), mock, stopped: stopped.clone() };
|
||||
let engine = Engine { rt: rt.clone(), cmd: tx, solo: solo_tx, key: Arc::new(key_tx), shared: shared.clone(), session: session.clone(), mock, stopped: stopped.clone() };
|
||||
let events: Arc<dyn Fn(Event) + Send + Sync> = Arc::new(events);
|
||||
let cfg = cfg.clone();
|
||||
if !mock {
|
||||
let ev = events.clone();
|
||||
let status: Arc<dyn Fn(soloist::Status) + Send + Sync> = Arc::new(move |s| ev(Event::Solo(s)));
|
||||
rt.spawn(soloist::supervise(cfg.device_name.clone(), key_rx, solo_rx, shared, events.clone(), status));
|
||||
}
|
||||
rt.spawn(async move {
|
||||
if mock {
|
||||
mock_loop(rx, events).await;
|
||||
@@ -171,38 +175,86 @@ impl Engine {
|
||||
engine
|
||||
}
|
||||
|
||||
/// Leaves Spotify Connect (the phone sees the TV go), waiting at most
|
||||
/// `limit` for it.
|
||||
/// A playback command (goes to Soloist) or a session command.
|
||||
pub fn send(&self, c: Cmd) {
|
||||
if self.mock || matches!(c, Cmd::SignOut | Cmd::Quit) {
|
||||
let _ = self.cmd.send(c);
|
||||
return;
|
||||
}
|
||||
let playing = self.shared.lock().unwrap().playing;
|
||||
let mut out = Vec::new();
|
||||
match c {
|
||||
Cmd::Context { uri, shuffle } => {
|
||||
out.push(command("activate", json!({})));
|
||||
out.push(command("set_shuffle", json!({"enabled": shuffle})));
|
||||
out.push(command("play", json!({"uri": uri})));
|
||||
}
|
||||
Cmd::Tracks { uris, start } => {
|
||||
let start = (start as usize).min(uris.len().saturating_sub(1));
|
||||
if let Some(first) = uris.get(start) {
|
||||
out.push(command("activate", json!({})));
|
||||
out.push(command("play", json!({"uri": first})));
|
||||
for u in uris.iter().skip(start + 1).filter(|u| u.starts_with("spotify:track:")).take(QUEUE_AHEAD) {
|
||||
out.push(command("add_to_queue", json!({"uri": u})));
|
||||
}
|
||||
}
|
||||
}
|
||||
Cmd::PlayPause => out.push(command(if playing { "pause" } else { "play" }, json!({}))),
|
||||
Cmd::Play => {
|
||||
out.push(command("activate", json!({})));
|
||||
out.push(command("play", json!({})));
|
||||
}
|
||||
Cmd::Pause => out.push(command("pause", json!({}))),
|
||||
Cmd::Next => out.push(command("skip_next", json!({}))),
|
||||
Cmd::Prev => out.push(command("skip_prev", json!({}))),
|
||||
Cmd::Seek(ms) => out.push(command("seek", json!({"position_ms": ms}))),
|
||||
Cmd::Shuffle(on) => out.push(command("set_shuffle", json!({"enabled": on}))),
|
||||
Cmd::Repeat(ctx, track) => {
|
||||
// The order matters (Soloist's WebSocket API).
|
||||
if track {
|
||||
out.push(command("set_repeat_context", json!({"enabled": false})));
|
||||
out.push(command("set_repeat_track", json!({"enabled": true})));
|
||||
} else {
|
||||
out.push(command("set_repeat_track", json!({"enabled": false})));
|
||||
out.push(command("set_repeat_context", json!({"enabled": ctx})));
|
||||
}
|
||||
}
|
||||
Cmd::AddToQueue(uri) => out.push(command("add_to_queue", json!({"uri": uri}))),
|
||||
Cmd::SignOut | Cmd::Quit => {}
|
||||
}
|
||||
for o in out {
|
||||
let _ = self.solo.send(o);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Soloist API key changed: (re)start Soloist with it.
|
||||
pub fn set_key(&self, key: &str) {
|
||||
let _ = self.key.send(key.trim().to_string());
|
||||
}
|
||||
|
||||
/// The next tracks (Soloist's queue).
|
||||
pub fn queue(&self) -> Vec<Track> {
|
||||
self.shared.lock().unwrap().queue.clone()
|
||||
}
|
||||
|
||||
/// Leaves cleanly, waiting at most `limit`.
|
||||
pub fn shutdown(&self, limit: Duration) {
|
||||
self.send(Cmd::Quit);
|
||||
let _ = self.cmd.send(Cmd::Quit);
|
||||
let start = std::time::Instant::now();
|
||||
while !self.stopped.load(std::sync::atomic::Ordering::SeqCst) && start.elapsed() < limit {
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn send(&self, c: Cmd) {
|
||||
let _ = self.cmd.send(c);
|
||||
/// 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)
|
||||
}
|
||||
|
||||
fn session(&self) -> anyhow::Result<Session> {
|
||||
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"))
|
||||
}
|
||||
|
||||
/// A Web API access token (blocking; call it off the UI thread).
|
||||
pub fn token(&self) -> anyhow::Result<String> {
|
||||
if self.mock {
|
||||
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 });
|
||||
match t {
|
||||
Ok(Ok(t)) => Ok(t.access_token),
|
||||
Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")),
|
||||
Err(_) => Err(anyhow::anyhow!("A Spotify nem válaszolt")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Lyrics of a track: (start ms, line), and whether they are synced.
|
||||
pub fn lyrics(&self, track_id: &str) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
|
||||
if self.mock {
|
||||
@@ -227,7 +279,7 @@ pub fn parse_lyrics(body: &[u8]) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
|
||||
a.iter()
|
||||
.map(|x| {
|
||||
let t = x["startTimeMs"].as_str().and_then(|s| s.parse().ok()).or_else(|| x["startTimeMs"].as_u64().map(|v| v as u32)).unwrap_or(0);
|
||||
let w = x["words"].as_str().unwrap_or("").replace('♪', "").trim().to_string();
|
||||
let w = x["words"].as_str().unwrap_or("").replace('\u{266a}', "").trim().to_string();
|
||||
(t, w)
|
||||
})
|
||||
.collect()
|
||||
@@ -236,51 +288,11 @@ pub fn parse_lyrics(body: &[u8]) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
|
||||
Ok((lines, synced))
|
||||
}
|
||||
|
||||
fn track_of(item: &AudioItem) -> Track {
|
||||
let id = item.track_id.to_id().unwrap_or_default();
|
||||
let cover = item.covers.iter().max_by_key(|c| c.width).map(|c| c.url.clone()).unwrap_or_default();
|
||||
let (artists, album, episode) = match &item.unique_fields {
|
||||
UniqueFields::Track { artists, album, .. } => (
|
||||
artists.0.iter().map(|a| (a.id.to_id().unwrap_or_default(), a.name.clone())).collect(),
|
||||
album.clone(),
|
||||
false,
|
||||
),
|
||||
UniqueFields::Episode { show_name, .. } => (vec![(String::new(), show_name.clone())], show_name.clone(), true),
|
||||
UniqueFields::Local { artists, album, .. } => (artists.iter().map(|a| (String::new(), a.clone())).collect(), album.clone().unwrap_or_default(), false),
|
||||
};
|
||||
Track { uri: item.uri.clone(), id, name: item.name.clone(), artists, album, cover, duration_ms: item.duration_ms, episode, explicit: item.is_explicit }
|
||||
}
|
||||
|
||||
fn bitrate(b: u32) -> Bitrate {
|
||||
match b {
|
||||
96 => Bitrate::Bitrate96,
|
||||
320 => Bitrate::Bitrate320,
|
||||
_ => Bitrate::Bitrate160,
|
||||
}
|
||||
}
|
||||
|
||||
fn load_request(c: Cmd) -> Option<LoadRequest> {
|
||||
match c {
|
||||
Cmd::Context { uri, start, shuffle } => {
|
||||
let options = LoadRequestOptions {
|
||||
start_playing: true,
|
||||
seek_to: 0,
|
||||
context_options: Some(LoadContextOptions::Options(Options { shuffle, repeat: false, repeat_track: false })),
|
||||
playing_track: start.map(|Start::Uri(u)| PlayingTrack::Uri(u)),
|
||||
};
|
||||
Some(LoadRequest::from_context_uri(uri, options))
|
||||
}
|
||||
Cmd::Tracks { uris, start } => {
|
||||
let options = LoadRequestOptions { start_playing: true, seek_to: 0, context_options: None, playing_track: Some(PlayingTrack::Index(start)) };
|
||||
Some(LoadRequest::from_tracks(uris, options))
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The librespot session: sign in (cached credentials or a pairing code),
|
||||
/// stay connected, sign out.
|
||||
async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mutex<Option<Session>>>, events: Arc<dyn Fn(Event) + Send + Sync>) {
|
||||
let dir = cache_dir();
|
||||
let cache = match Cache::new(Some(dir.clone()), Some(dir.clone()), Some(dir.join("audio")), Some(512 << 20)) {
|
||||
let cache = match Cache::new(Some(dir.clone()), None, None, None) {
|
||||
Ok(c) => Some(c),
|
||||
Err(e) => {
|
||||
log::warn!("cache: {e}");
|
||||
@@ -289,65 +301,7 @@ async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mute
|
||||
};
|
||||
let mut session_config = SessionConfig::default();
|
||||
session_config.device_id = cfg.device_id.clone();
|
||||
session_config.autoplay = Some(cfg.autoplay);
|
||||
let connect_config = ConnectConfig {
|
||||
name: cfg.device_name.clone(),
|
||||
device_type: DeviceType::Tv,
|
||||
is_group: false,
|
||||
// The TV sets the loudness; Spotify plays at full scale.
|
||||
initial_volume: u16::MAX,
|
||||
disable_volume: false,
|
||||
volume_steps: 64,
|
||||
};
|
||||
let player_config = PlayerConfig { bitrate: bitrate(cfg.bitrate), normalisation: cfg.normalise, gapless: true, ..PlayerConfig::default() };
|
||||
|
||||
let mixer = match mixer::find(None).map(|m| m(MixerConfig::default())) {
|
||||
Some(Ok(m)) => m,
|
||||
_ => {
|
||||
events(Event::Status(Status::Failed("A hangkeverő nem indult el".into())));
|
||||
return;
|
||||
}
|
||||
};
|
||||
#[cfg(target_os = "linux")]
|
||||
let backend = audio_backend::find(Some("gstreamer".into()));
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
let backend = audio_backend::find(None);
|
||||
let Some(backend) = backend else {
|
||||
events(Event::Status(Status::Failed("Nincs hangkimenet".into())));
|
||||
return;
|
||||
};
|
||||
|
||||
let mut session = Session::new(session_config.clone(), cache.clone());
|
||||
let player = Player::new(player_config, session.clone(), mixer.get_soft_volume(), move || backend(None, AudioFormat::default()));
|
||||
*shared.lock().unwrap() = Some(session.clone());
|
||||
|
||||
// Player events -> UI.
|
||||
{
|
||||
let mut ch = player.get_player_event_channel();
|
||||
let events = events.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Some(ev) = ch.recv().await {
|
||||
if let Some(e) = player_event(ev) {
|
||||
events(e);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Zeroconf: the phone signs in (or switches the account).
|
||||
let mut discovery = match librespot_discovery::Discovery::builder(session_config.device_id.clone(), session_config.client_id.clone())
|
||||
.name(cfg.device_name.clone())
|
||||
.device_type(DeviceType::Tv)
|
||||
.launch()
|
||||
{
|
||||
Ok(d) => Some(d),
|
||||
Err(e) => {
|
||||
log::warn!("discovery: {e}");
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
// Pairing codes: run while signed out.
|
||||
let (pair_tx, mut pair_rx) = mpsc::unbounded_channel::<Credentials>();
|
||||
let mut pairing: Option<tokio::task::JoinHandle<()>> = None;
|
||||
let start_pairing = |pairing: &mut Option<tokio::task::JoinHandle<()>>| {
|
||||
@@ -364,38 +318,17 @@ async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mute
|
||||
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
|
||||
start_pairing(&mut pairing);
|
||||
}
|
||||
|
||||
let mut spirc: Option<Spirc> = None;
|
||||
let mut spirc_task: Option<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>> = None;
|
||||
let mut session: Option<Session> = None;
|
||||
let mut failures = 0u32;
|
||||
// Commands that came before Spirc was up (a load right after sign-in).
|
||||
let mut waiting: Vec<Cmd> = Vec::new();
|
||||
let mut watchdog = tokio::time::interval(Duration::from_secs(10));
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
creds = async { match discovery.as_mut() { Some(d) => d.next().await, None => std::future::pending().await } } => {
|
||||
let Some(creds) = creds else {
|
||||
log::warn!("discovery stopped");
|
||||
discovery = None;
|
||||
continue;
|
||||
};
|
||||
log::info!("signed in from the network");
|
||||
if let Some(p) = pairing.take() { p.abort(); }
|
||||
if let Some(s) = spirc.take() { let _ = s.shutdown(); }
|
||||
if let Some(t) = spirc_task.take() { tokio::spawn(t); }
|
||||
if !session.is_invalid() { session.shutdown(); }
|
||||
credentials = Some(creds);
|
||||
failures = 0;
|
||||
connecting = true;
|
||||
events(Event::Status(Status::Connecting));
|
||||
}
|
||||
creds = pair_rx.recv() => {
|
||||
let Some(creds) = creds else { continue };
|
||||
log::info!("signed in with a pairing code");
|
||||
pairing = None;
|
||||
if let Some(s) = spirc.take() { let _ = s.shutdown(); }
|
||||
if let Some(t) = spirc_task.take() { tokio::spawn(t); }
|
||||
if !session.is_invalid() { session.shutdown(); }
|
||||
if let Some(s) = session.take() { s.shutdown(); }
|
||||
credentials = Some(creds);
|
||||
failures = 0;
|
||||
connecting = true;
|
||||
@@ -403,26 +336,20 @@ async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mute
|
||||
}
|
||||
_ = async {}, if connecting => {
|
||||
connecting = false;
|
||||
if session.is_invalid() {
|
||||
session = Session::new(session_config.clone(), cache.clone());
|
||||
player.set_session(session.clone());
|
||||
*shared.lock().unwrap() = Some(session.clone());
|
||||
}
|
||||
let s = Session::new(session_config.clone(), cache.clone());
|
||||
let creds = credentials.clone().unwrap_or_default();
|
||||
match Spirc::new(connect_config.clone(), session.clone(), creds, player.clone(), mixer.clone()).await {
|
||||
Ok((s, task)) => {
|
||||
for c in waiting.drain(..) { apply(&s, c); }
|
||||
spirc = Some(s);
|
||||
spirc_task = Some(Box::pin(task));
|
||||
*shared.lock().unwrap() = Some(session.clone());
|
||||
events(Event::Status(Status::Ready(session.username())));
|
||||
match s.connect(creds, true).await {
|
||||
Ok(()) => {
|
||||
failures = 0;
|
||||
*shared.lock().unwrap() = Some(s.clone());
|
||||
events(Event::Status(Status::Ready(s.username())));
|
||||
session = Some(s);
|
||||
}
|
||||
Err(e) => {
|
||||
log::warn!("connect: {e}");
|
||||
let msg = e.to_string();
|
||||
// Bad credentials: sign in again from the phone.
|
||||
if msg.contains("BadCredentials") || msg.contains("PremiumAccountRequired") || msg.contains("Login failed") {
|
||||
if let Some(c) = &cache { let _ = std::fs::remove_file(cache_dir().join("credentials.json")); let _ = c; }
|
||||
let _ = std::fs::remove_file(cache_dir().join("credentials.json"));
|
||||
credentials = None;
|
||||
let text = if msg.contains("Premium") { "Ehhez Spotify Premium előfizetés kell." } else { "A bejelentkezés lejárt." };
|
||||
events(Event::Status(Status::Failed(format!("{text} Jelentkezz be újra a telefonról."))));
|
||||
@@ -431,59 +358,44 @@ async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mute
|
||||
} else {
|
||||
failures += 1;
|
||||
events(Event::Status(Status::Failed(format!("Nem sikerült csatlakozni a Spotifyhoz: {msg}"))));
|
||||
let delay = Duration::from_secs((2u64 << failures.min(5)).min(60));
|
||||
tokio::time::sleep(delay).await;
|
||||
tokio::time::sleep(Duration::from_secs((2u64 << failures.min(5)).min(60))).await;
|
||||
connecting = credentials.is_some();
|
||||
if connecting { events(Event::Status(Status::Connecting)); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ = async { if let Some(t) = spirc_task.as_mut() { t.await } else { std::future::pending().await } } => {
|
||||
// Spirc ended: the connection broke. Reconnect.
|
||||
log::warn!("connect ended, reconnecting");
|
||||
spirc_task = None;
|
||||
spirc = None;
|
||||
if credentials.is_some() {
|
||||
failures += 1;
|
||||
tokio::time::sleep(Duration::from_secs((1u64 << failures.min(5)).min(30))).await;
|
||||
_ = watchdog.tick() => {
|
||||
// The connection broke (network, sleep): connect again.
|
||||
if session.as_ref().is_some_and(|s| s.is_invalid()) && !connecting && credentials.is_some() {
|
||||
log::warn!("session lost, reconnecting");
|
||||
session = None;
|
||||
connecting = true;
|
||||
events(Event::Status(Status::Connecting));
|
||||
}
|
||||
}
|
||||
cmd = rx.recv() => {
|
||||
let Some(cmd) = cmd else { break };
|
||||
if matches!(cmd, Cmd::Quit) { break; }
|
||||
if matches!(cmd, Cmd::SignOut) {
|
||||
if let Some(s) = spirc.take() { let _ = s.shutdown(); }
|
||||
if let Some(t) = spirc_task.take() { tokio::spawn(t); }
|
||||
player.stop();
|
||||
if !session.is_invalid() { session.shutdown(); }
|
||||
match cmd {
|
||||
None | Some(Cmd::Quit) => break,
|
||||
Some(Cmd::SignOut) => {
|
||||
if let Some(s) = session.take() { s.shutdown(); }
|
||||
*shared.lock().unwrap() = None;
|
||||
let _ = std::fs::remove_file(cache_dir().join("credentials.json"));
|
||||
soloist::forget_pairing();
|
||||
credentials = None;
|
||||
events(Event::Stopped);
|
||||
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
|
||||
start_pairing(&mut pairing);
|
||||
continue;
|
||||
}
|
||||
match &spirc {
|
||||
Some(s) => { failures = 0; apply(s, cmd) }
|
||||
None => waiting.push(cmd),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(s) = spirc.take() {
|
||||
let _ = s.shutdown();
|
||||
}
|
||||
if let Some(t) = spirc_task.take() {
|
||||
let _ = tokio::time::timeout(Duration::from_secs(2), t).await;
|
||||
}
|
||||
if let Some(p) = pairing {
|
||||
p.abort();
|
||||
}
|
||||
if let Some(d) = discovery {
|
||||
d.shutdown().await;
|
||||
if let Some(s) = session {
|
||||
s.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -586,47 +498,6 @@ async fn pair_loop(client_id: String, events: Arc<dyn Fn(Event) + Send + Sync>,
|
||||
}
|
||||
}
|
||||
|
||||
fn apply(s: &Spirc, c: Cmd) {
|
||||
let r = match c {
|
||||
Cmd::Context { .. } | Cmd::Tracks { .. } => {
|
||||
let req = load_request(c).unwrap();
|
||||
// The TV takes the playback over (it may be on the phone).
|
||||
let _ = s.activate();
|
||||
s.load(req)
|
||||
}
|
||||
Cmd::PlayPause => s.play_pause(),
|
||||
Cmd::Play => s.activate().and_then(|_| s.play()),
|
||||
Cmd::Pause => s.pause(),
|
||||
Cmd::Next => s.next(),
|
||||
Cmd::Prev => s.prev(),
|
||||
Cmd::Seek(ms) => s.set_position_ms(ms),
|
||||
Cmd::Shuffle(on) => s.shuffle(on),
|
||||
Cmd::Repeat(ctx, track) => s.repeat(ctx).and_then(|_| s.repeat_track(track)),
|
||||
Cmd::SignOut | Cmd::Quit => Ok(()),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
log::warn!("command: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn player_event(ev: PlayerEvent) -> Option<Event> {
|
||||
Some(match ev {
|
||||
PlayerEvent::TrackChanged { audio_item } => Event::Track(track_of(&audio_item)),
|
||||
PlayerEvent::Loading { .. } => Event::Loading,
|
||||
PlayerEvent::Playing { position_ms, .. } => Event::Playing(position_ms),
|
||||
PlayerEvent::Paused { position_ms, .. } => Event::Paused(position_ms),
|
||||
PlayerEvent::Seeked { position_ms, .. } | PlayerEvent::PositionCorrection { position_ms, .. } => Event::Seeked(position_ms),
|
||||
PlayerEvent::Stopped { .. } => Event::Stopped,
|
||||
PlayerEvent::Unavailable { .. } => Event::Unavailable,
|
||||
PlayerEvent::ShuffleChanged { shuffle } => Event::Shuffle(shuffle),
|
||||
PlayerEvent::RepeatChanged { context, track } => Event::Repeat(context, track),
|
||||
PlayerEvent::SessionConnected { .. } => Event::Active(true),
|
||||
PlayerEvent::SessionDisconnected { .. } => Event::Active(false),
|
||||
PlayerEvent::SessionClientChanged { client_name, .. } => Event::Client(client_name),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Mock mode: signed in at once; "plays" a made-up track for every load.
|
||||
async fn mock_loop(mut rx: mpsc::UnboundedReceiver<Cmd>, events: Arc<dyn Fn(Event) + Send + Sync>) {
|
||||
tokio::time::sleep(Duration::from_millis(300)).await;
|
||||
@@ -636,6 +507,11 @@ async fn mock_loop(mut rx: mpsc::UnboundedReceiver<Cmd>, events: Arc<dyn Fn(Even
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
events(Event::Status(Status::Ready("demo".into())));
|
||||
if std::env::var("SPOTIFY_MOCK").as_deref() == Ok("nokey") {
|
||||
events(Event::Solo(soloist::Status::NeedKey));
|
||||
} else {
|
||||
events(Event::Solo(soloist::Status::Ready));
|
||||
}
|
||||
let mut playing = false;
|
||||
let mut n = 0u32;
|
||||
let track = |n: u32| Track {
|
||||
@@ -672,6 +548,7 @@ async fn mock_loop(mut rx: mpsc::UnboundedReceiver<Cmd>, events: Arc<dyn Fn(Even
|
||||
Cmd::Seek(ms) => events(Event::Seeked(ms)),
|
||||
Cmd::Shuffle(on) => events(Event::Shuffle(on)),
|
||||
Cmd::Repeat(c, t) => events(Event::Repeat(c, t)),
|
||||
Cmd::AddToQueue(_) => {}
|
||||
Cmd::SignOut => events(Event::Status(Status::SignIn("Fennec TV".into()))),
|
||||
Cmd::Quit => break,
|
||||
}
|
||||
|
||||
41
tools/ci-apt.sh
Executable file
41
tools/ci-apt.sh
Executable file
@@ -0,0 +1,41 @@
|
||||
#!/bin/sh
|
||||
# apt-get install for the CI's two architectures (amd64 + arm64 multiarch).
|
||||
#
|
||||
# ports.ubuntu.com (arm64) often lags behind the main mirror (amd64). A
|
||||
# "Multi-Arch: same" library must have one version on both architectures, so
|
||||
# when the image already has a newer amd64 build (libpcre2, glib...) apt
|
||||
# gives up ("held broken packages"). Then this script takes the arm64
|
||||
# packages apt complains about, and pins every installed package of the same
|
||||
# source package on both architectures to the arm64 candidate version
|
||||
# (a downgrade on amd64), and tries again.
|
||||
#
|
||||
# Usage: tools/ci-apt.sh <packages...>
|
||||
set -u
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
pins=""
|
||||
for try in 1 2 3 4; do
|
||||
if apt-get install -y --no-install-recommends --allow-downgrades "$@" $pins >/tmp/apt.log 2>&1; then
|
||||
[ -n "$pins" ] && echo "installed with aligned versions:$pins"
|
||||
exit 0
|
||||
fi
|
||||
names=$(sed -n 's/.*Depends: \([a-z0-9.+-]*\):arm64.*/\1/p' /tmp/apt.log | sort -u)
|
||||
if [ -z "$names" ] || [ "$try" = 4 ]; then
|
||||
sed -n '/following packages have unmet/,$p' /tmp/apt.log | head -60
|
||||
tail -20 /tmp/apt.log
|
||||
exit 1
|
||||
fi
|
||||
for n in $names; do
|
||||
src=$(apt-cache show "$n:arm64" 2>/dev/null | sed -n 's/^Source: \([^ ]*\).*/\1/p' | head -1)
|
||||
[ -n "$src" ] || src=$n
|
||||
ver=$(apt-cache policy "$n:arm64" | sed -n 's/^ *Candidate: //p')
|
||||
[ -n "$ver" ] && [ "$ver" != "(none)" ] || continue
|
||||
# The package itself and its installed siblings from the same source.
|
||||
sibs=$(dpkg-query -W -f '${Package} ${source:Package}\n' 2>/dev/null | awk -v s="$src" '$2 == s { print $1 }' | sed 's/:.*//' | sort -u)
|
||||
for p in $n $sibs; do
|
||||
v=$(apt-cache policy "$p:arm64" | sed -n 's/^ *Candidate: //p')
|
||||
[ -n "$v" ] && [ "$v" != "(none)" ] || v=$ver
|
||||
case " $pins " in *" $p=$v "*) ;; *) pins="$pins $p=$v $p:arm64=$v" ;; esac
|
||||
done
|
||||
done
|
||||
echo "apt: aligning to the arm64 versions:$pins"
|
||||
done
|
||||
15
ui/app.slint
15
ui/app.slint
@@ -11,7 +11,7 @@ import { TvWindow, Tv, SfText, GlassRect, MenuItem } from "@sf-ui/sf-ui.slint";
|
||||
import { Line, Chip, Card, Check, QueueItem } from "types.slint";
|
||||
import { LinePage } from "page.slint";
|
||||
import { NowPlayingScreen } from "nowplaying.slint";
|
||||
import { ConnectScreen, InputScreen, MessageScreen } from "signin.slint";
|
||||
import { ConnectScreen, InputScreen, MessageScreen, KeyScreen } from "signin.slint";
|
||||
import { SelectOverlay, Toast } from "overlays.slint";
|
||||
|
||||
export { Tv, SfText, MenuItem, Line, Chip, Card, Check, QueueItem }
|
||||
@@ -20,7 +20,7 @@ export component App inherits TvWindow {
|
||||
title: "Spotify";
|
||||
forward-focus: keys;
|
||||
|
||||
// "message", "signin", "page", "nowplaying"
|
||||
// "message", "signin", "solokey", "page", "nowplaying"
|
||||
in property <string> screen: "message";
|
||||
// The key text (Slint's Key codes) and whether it repeats; true = handled.
|
||||
callback key(string, bool) -> bool;
|
||||
@@ -29,6 +29,8 @@ export component App inherits TvWindow {
|
||||
animate message-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
out property <float> signin-t: self.screen == "signin" ? 1 : 0;
|
||||
animate signin-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
out property <float> solokey-t: self.screen == "solokey" ? 1 : 0;
|
||||
animate solokey-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
out property <float> page-t: self.screen == "page" ? 1 : 0;
|
||||
animate page-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
out property <float> np-t: self.screen == "nowplaying" ? 1 : 0;
|
||||
@@ -79,6 +81,14 @@ export component App inherits TvWindow {
|
||||
visible: self.alpha > 0.001;
|
||||
}
|
||||
|
||||
// ---- Soloist key ----
|
||||
in property <image> solokey-qr <=> solokey.qr;
|
||||
in property <string> solokey-url <=> solokey.url;
|
||||
solokey := KeyScreen {
|
||||
alpha: root.vis(root.solokey-t) * root.under;
|
||||
visible: root.solokey-t > 0.001;
|
||||
}
|
||||
|
||||
// ---- page ----
|
||||
in property <[Line]> page-lines <=> page.lines;
|
||||
in property <int> page-focus <=> page.focus-line;
|
||||
@@ -185,6 +195,7 @@ export component App inherits TvWindow {
|
||||
|
||||
// ---- glass, in drawing order (listed by src/main.rs) ----
|
||||
out property <[GlassRect]> glass-signin: signin.glass;
|
||||
out property <[GlassRect]> glass-solokey: solokey.glass;
|
||||
out property <[GlassRect]> glass-page: page.glass;
|
||||
out property <[GlassRect]> glass-page-keyboard: page.glass-keyboard;
|
||||
out property <[GlassRect]> glass-np: np.glass;
|
||||
|
||||
131
ui/signin.slint
131
ui/signin.slint
@@ -66,19 +66,6 @@ export component ConnectScreen inherits Rectangle {
|
||||
font-size: 26 * Tv.u;
|
||||
color: Tv.text;
|
||||
}
|
||||
Rectangle { height: 10 * Tv.u; }
|
||||
Text {
|
||||
text: "A SPOTIFY APPBÓL";
|
||||
font-size: 20 * Tv.u;
|
||||
font-weight: 700;
|
||||
letter-spacing: 3 * Tv.u;
|
||||
color: #1ed760;
|
||||
}
|
||||
Body {
|
||||
text: "Ha a telefon ugyanazon a Wi-Fin van: indíts el egy számot, koppints az eszközök ikonjára, és válaszd: „" + root.device + "”.";
|
||||
font-size: 26 * Tv.u;
|
||||
color: Tv.text;
|
||||
}
|
||||
Rectangle { }
|
||||
HorizontalLayout {
|
||||
spacing: 16 * Tv.u;
|
||||
@@ -242,3 +229,121 @@ export component MessageScreen inherits Rectangle {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The Soloist API key: a QR code to a page on this TV where the phone pastes
|
||||
// the key (src/keyserver.rs). OK types it on the TV, Back: later.
|
||||
export component KeyScreen inherits Rectangle {
|
||||
in property <float> alpha: 1;
|
||||
in property <image> qr;
|
||||
in property <string> url;
|
||||
|
||||
pane := GlassPane {
|
||||
x: (root.width - self.width) / 2;
|
||||
y: (root.height - self.height) / 2 - 20 * Tv.u;
|
||||
width: 1640 * Tv.u;
|
||||
height: 760 * Tv.u;
|
||||
radius: 56 * Tv.u;
|
||||
frost: 3.6;
|
||||
tint: Tv.smoke.with-alpha(0.46);
|
||||
glow: #1ed760;
|
||||
alpha: root.alpha;
|
||||
|
||||
VerticalLayout {
|
||||
x: 80 * Tv.u;
|
||||
y: 72 * Tv.u;
|
||||
width: 860 * Tv.u;
|
||||
height: parent.height - 144 * Tv.u;
|
||||
spacing: 18 * Tv.u;
|
||||
opacity: root.alpha;
|
||||
HorizontalLayout {
|
||||
spacing: 24 * Tv.u;
|
||||
alignment: start;
|
||||
Rectangle {
|
||||
width: 80 * Tv.u;
|
||||
height: 80 * Tv.u;
|
||||
border-radius: self.width / 2;
|
||||
background: #1ed760;
|
||||
SpIcon {
|
||||
name: "audio";
|
||||
size: 44 * Tv.u;
|
||||
ink: #121317;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
Title { text: "Még egy lépés: a lejátszó"; }
|
||||
Caption { text: "A Spotify Soloist saját kulccsal indul"; }
|
||||
}
|
||||
}
|
||||
Rectangle { height: 14 * Tv.u; }
|
||||
Body {
|
||||
text: "A zenét a Spotify saját TV-s lejátszója, a Soloist játssza. Ehhez kell egy kulcs a Spotify-fiókodból (Premium).";
|
||||
font-size: 26 * Tv.u;
|
||||
color: Tv.text;
|
||||
}
|
||||
Text {
|
||||
text: "1. A TELEFONON";
|
||||
font-size: 20 * Tv.u;
|
||||
font-weight: 700;
|
||||
letter-spacing: 3 * Tv.u;
|
||||
color: #1ed760;
|
||||
}
|
||||
Body {
|
||||
text: "Nyisd meg: developer.spotify.com/dashboard/soloist, és hozz létre egy kulcsot.";
|
||||
font-size: 26 * Tv.u;
|
||||
color: Tv.text;
|
||||
}
|
||||
Text {
|
||||
text: "2. QR-KÓDDAL A TV-RE";
|
||||
font-size: 20 * Tv.u;
|
||||
font-weight: 700;
|
||||
letter-spacing: 3 * Tv.u;
|
||||
color: #1ed760;
|
||||
}
|
||||
Body {
|
||||
text: "Olvasd be a kódot, és illeszd be a kulcsot. A telefon ugyanazon a Wi-Fin legyen, mint a TV.";
|
||||
font-size: 26 * Tv.u;
|
||||
color: Tv.text;
|
||||
}
|
||||
Rectangle { }
|
||||
Caption { text: "OK: beírás a TV-n · Vissza: később (a Beállításokban is megadhatod)"; }
|
||||
}
|
||||
|
||||
qr-box := Rectangle {
|
||||
x: parent.width - self.width - 96 * Tv.u;
|
||||
y: 80 * Tv.u;
|
||||
width: 440 * Tv.u;
|
||||
height: 440 * Tv.u;
|
||||
border-radius: 28 * Tv.u;
|
||||
background: #ffffff;
|
||||
opacity: root.alpha;
|
||||
clip: true;
|
||||
if root.qr.width > 0: Image {
|
||||
x: 20 * Tv.u;
|
||||
y: 20 * Tv.u;
|
||||
width: parent.width - 40 * Tv.u;
|
||||
height: parent.height - 40 * Tv.u;
|
||||
source: root.qr;
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
if root.qr.width == 0: Text {
|
||||
text: "Nincs hálózat";
|
||||
color: #121317;
|
||||
font-size: 26 * Tv.u;
|
||||
}
|
||||
}
|
||||
Text {
|
||||
x: qr-box.x;
|
||||
y: qr-box.y + qr-box.height + 28 * Tv.u;
|
||||
width: qr-box.width;
|
||||
horizontal-alignment: center;
|
||||
text: root.url;
|
||||
font-size: 26 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text-secondary;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
}
|
||||
|
||||
out property <[GlassRect]> glass: [pane.glass];
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user