0.2.0: play through Spotify Soloist
Spotify refuses librespot the audio keys ("error audio key 0 1",
librespot #1649), so nothing played. Playback now goes through Spotify
Soloist, Spotify's own headless Linux player:
- The TV downloads it from Spotify (redistribution is not allowed), keeps
it fresh (builds expire after 90 days), runs and restarts it, and drives
it over its local WebSocket API; its events feed Most szól.
- It needs the user's own Soloist API key: the key screen shows a QR code
to a small page on the TV where the phone pastes it (or type it on the
TV); asked once after sign-in, also in Settings. Then the TV is picked
once in the phone's Spotify app (pairing); home shows that step.
- Soloist is the Connect device; librespot only signs in (pairing code)
and browses. Its player, Connect and zeroconf are gone, and with them
GStreamer.
- A track from a list plays and the next ones are queued (Soloist's play
takes one URI). The queue panel is back (Soloist reports the queue).
- Settings: the player's state and key instead of quality/normalisation/
autoplay (Soloist decides those).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -45,14 +45,10 @@ 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"
|
||||
# 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)
|
||||
libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev
|
||||
libgstreamer1.0-0:arm64 libgstreamer-plugins-base1.0-0:arm64"
|
||||
$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
|
||||
|
||||
@@ -11,7 +11,9 @@ 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/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
|
||||
@@ -30,7 +32,7 @@ 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 lyrics panel
|
||||
ui/signin.slint ConnectScreen (QR code + Spotify app), InputScreen, MessageScreen
|
||||
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)
|
||||
```
|
||||
@@ -44,7 +46,7 @@ The public Web API is not used against Spotify: librespot's client id gets 429 (
|
||||
|
||||
- **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).
|
||||
|
||||
788
Cargo.lock
generated
788
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
23
Cargo.toml
23
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.1"
|
||||
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,26 +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, features = ["std"] }
|
||||
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"
|
||||
|
||||
17
README.md
17
README.md
@@ -3,15 +3,12 @@
|
||||
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.
|
||||
|
||||
A belépés megmarad (`$HOME/.cache/spotify-tv`).
|
||||
- **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. 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).
|
||||
- **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).
|
||||
|
||||
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.
|
||||
|
||||
@@ -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.1"
|
||||
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
|
||||
|
||||
14
src/api.rs
14
src/api.rs
@@ -437,22 +437,18 @@ impl Api {
|
||||
pub fn search(&self, q: &str) -> Result<SearchResult> {
|
||||
both!(self, search(q))
|
||||
}
|
||||
pub fn add_to_queue(&self, uri: &str) -> Result<()> {
|
||||
both!(self, add_to_queue(uri))
|
||||
}
|
||||
}
|
||||
|
||||
/// The Web API client (the mock server).
|
||||
#[derive(Clone)]
|
||||
pub struct Web {
|
||||
base: String,
|
||||
engine: Engine,
|
||||
agent: ureq::Agent,
|
||||
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
|
||||
}
|
||||
|
||||
impl Web {
|
||||
pub fn new(engine: Engine) -> 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)))
|
||||
@@ -461,7 +457,7 @@ impl Web {
|
||||
.build()
|
||||
.into();
|
||||
let base = std::env::var("SPOTIFY_API").unwrap_or_else(|_| API.to_string());
|
||||
Web { 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).
|
||||
@@ -486,7 +482,8 @@ impl Web {
|
||||
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(),
|
||||
@@ -722,9 +719,6 @@ impl Web {
|
||||
|
||||
// ---- player ----
|
||||
|
||||
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() }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
//! songs and saved albums, "artist", "show")
|
||||
//! - recently played: /recently-played/v3 (JSON)
|
||||
//! - search: the "spotify:search:" context (songs), artists and albums from them
|
||||
//! - queue: a Connect player command to this device
|
||||
//!
|
||||
//! Answers come back as the same objects the Web API code uses (api.rs).
|
||||
|
||||
@@ -711,21 +710,6 @@ impl Internal {
|
||||
Ok(SearchResult { artists: self.artists(&artist_uris)?, albums, tracks, playlists: Vec::new(), shows: Vec::new() })
|
||||
}
|
||||
|
||||
/// Adds `uri` to the queue of this device (a Connect player command).
|
||||
pub fn add_to_queue(&self, uri: &str) -> Result<()> {
|
||||
let s = self.session()?;
|
||||
let dev = s.device_id().to_string();
|
||||
let body = serde_json::json!({
|
||||
"command": {
|
||||
"endpoint": "add_to_queue",
|
||||
"track": { "uri": uri, "metadata": { "is_queued": "true" }, "provider": "queue" },
|
||||
}
|
||||
})
|
||||
.to_string();
|
||||
let path = format!("/connect-state/v1/player/command/from/{dev}/to/{dev}");
|
||||
self.engine.block(s.spclient().request_as_json(&Method::POST, &path, None, Some(&body))).map_err(e)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
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");
|
||||
}
|
||||
}
|
||||
12
src/main.rs
12
src/main.rs
@@ -2,18 +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 sign-in and playback; Spotify's internal endpoints through the
|
||||
//! same session (src/internal.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;
|
||||
|
||||
@@ -23,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()?;
|
||||
@@ -39,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,6 +1,6 @@
|
||||
//! Most szól: the big cover, the title, the progress, the controls (shuffle,
|
||||
//! previous, play/pause, next, repeat, like, lyrics) and synced lyrics.
|
||||
//! Also keeps the playback state that the engine reports
|
||||
//! previous, play/pause, next, repeat, like, lyrics, queue), synced lyrics
|
||||
//! 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
|
||||
@@ -14,10 +14,12 @@ use slint::{Model, ModelRc, VecModel};
|
||||
use crate::api;
|
||||
use crate::app::{Action, Controller, Look};
|
||||
use crate::spotify::{Cmd, Event, Track};
|
||||
use crate::{format, task};
|
||||
use std::rc::Rc;
|
||||
|
||||
use crate::{QueueItem, format, task};
|
||||
|
||||
/// The buttons, left to right.
|
||||
const BUTTONS: [&str; 7] = ["shuffle", "prev", "play", "next", "repeat", "like", "lyrics"];
|
||||
const BUTTONS: [&str; 8] = ["shuffle", "prev", "play", "next", "repeat", "like", "lyrics", "queue"];
|
||||
const PLAY: usize = 2;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
@@ -25,6 +27,7 @@ pub enum Panel {
|
||||
#[default]
|
||||
None,
|
||||
Lyrics,
|
||||
Queue,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -67,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;
|
||||
@@ -99,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,
|
||||
@@ -119,22 +134,24 @@ 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.
|
||||
/// A new track: its cover behind the screen, its like state, lyrics, queue.
|
||||
fn track_changed(c: &Controller) {
|
||||
let (track, panel) = {
|
||||
let st = c.state.borrow();
|
||||
@@ -165,10 +182,35 @@ fn track_changed(c: &Controller) {
|
||||
}
|
||||
match panel {
|
||||
Panel::Lyrics => load_lyrics(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());
|
||||
@@ -247,6 +289,7 @@ pub fn open(c: &Controller) {
|
||||
let panel = c.state.borrow().np.panel;
|
||||
match panel {
|
||||
Panel::Lyrics => load_lyrics(c),
|
||||
Panel::Queue => sync_queue(c),
|
||||
Panel::None => {}
|
||||
}
|
||||
let k = c.clone();
|
||||
@@ -375,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;
|
||||
@@ -425,6 +475,7 @@ pub fn sync(c: &Controller) {
|
||||
ui.set_np_panel(match np.panel {
|
||||
Panel::None => 0,
|
||||
Panel::Lyrics => 1,
|
||||
Panel::Queue => 2,
|
||||
});
|
||||
let device = if !np.elsewhere.is_empty() && !np.playing { format!("Irányítja: {}", np.elsewhere) } else { format!("Lejátszás itt: {}", st.cfg.device_name) };
|
||||
ui.set_np_device(device.into());
|
||||
|
||||
@@ -97,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),
|
||||
|
||||
@@ -109,6 +109,16 @@ 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", r.iter().map(|e| entity_card(e, d.liked_total)).collect()).captions());
|
||||
@@ -132,7 +142,11 @@ impl Screen for Home {
|
||||
Spec { lines, frame }
|
||||
}
|
||||
|
||||
fn activate(&mut self, cx: &Cx, _line: &str, item: &str) {
|
||||
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
|
||||
if line == "solo" {
|
||||
cx.c.open_key_screen();
|
||||
return;
|
||||
}
|
||||
screens::open_card(cx, item);
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -154,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.
|
||||
@@ -184,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;
|
||||
}
|
||||
@@ -238,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";
|
||||
|
||||
@@ -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}));
|
||||
}
|
||||
}
|
||||
433
src/spotify.rs
433
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,20 +175,77 @@ 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)
|
||||
@@ -194,33 +255,6 @@ impl Engine {
|
||||
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()?;
|
||||
// login5 first: what Spotify's own clients use now. The old keymaster
|
||||
// endpoint answers 403 for most accounts; it is only the fallback.
|
||||
let t = self.rt.block_on(async move {
|
||||
tokio::time::timeout(Duration::from_secs(15), async {
|
||||
match s.login5().auth_token().await {
|
||||
Ok(t) => Ok(t),
|
||||
Err(e) => {
|
||||
log::warn!("login5 token: {e}");
|
||||
s.token_provider().get_token(SCOPES).await
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
});
|
||||
match t {
|
||||
Ok(Ok(t)) => Ok(t.access_token),
|
||||
Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")),
|
||||
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 {
|
||||
@@ -245,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()
|
||||
@@ -254,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}");
|
||||
@@ -307,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<()>>| {
|
||||
@@ -382,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;
|
||||
@@ -421,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."))));
|
||||
@@ -449,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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -604,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;
|
||||
@@ -654,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 {
|
||||
@@ -690,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,
|
||||
}
|
||||
|
||||
17
ui/app.slint
17
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;
|
||||
@@ -139,6 +149,8 @@ export component App inherits TvWindow {
|
||||
in property <int> np-lyric-line <=> np.lyric-line;
|
||||
in property <bool> np-lyrics-synced <=> np.lyrics-synced;
|
||||
in property <string> np-lyrics-note <=> np.lyrics-note;
|
||||
in property <[QueueItem]> np-queue <=> np.queue;
|
||||
in property <string> np-queue-note <=> np.queue-note;
|
||||
in property <string> np-device <=> np.device;
|
||||
np := NowPlayingScreen {
|
||||
alpha: root.vis(root.np-t) * root.under;
|
||||
@@ -183,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;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// Most szól: the cover, the title, the progress and the controls. With the
|
||||
// lyrics open, the cover and the texts move to the left and a glass panel
|
||||
// holds the lyrics on the right.
|
||||
// lyrics or the queue open, the cover and the texts move to the left and a
|
||||
// glass panel holds the lyrics / the queue on the right.
|
||||
//
|
||||
// Rust owns the focus: `button` is the focused button (0..6), `area` 1 means
|
||||
// Rust owns the focus: `button` is the focused button (0..7), `area` 1 means
|
||||
// the progress bar (left/right seek there).
|
||||
|
||||
import { Tv, GlassRect, GlassPane, Spinner, Caption } from "@sf-ui/sf-ui.slint";
|
||||
import { QueueItem } from "types.slint";
|
||||
import { SpIcon } from "icons.slint";
|
||||
import { Accent, Equalizer } from "page.slint";
|
||||
|
||||
@@ -72,12 +73,14 @@ export component NowPlayingScreen inherits Rectangle {
|
||||
in property <int> liked: -1;
|
||||
in property <int> button: 2;
|
||||
in property <int> area;
|
||||
// 0 none, 1 lyrics
|
||||
// 0 none, 1 lyrics, 2 queue
|
||||
in property <int> panel;
|
||||
in property <[string]> lyrics;
|
||||
in property <int> lyric-line: -1;
|
||||
in property <bool> lyrics-synced;
|
||||
in property <string> lyrics-note;
|
||||
in property <[QueueItem]> queue;
|
||||
in property <string> queue-note;
|
||||
in property <string> device;
|
||||
|
||||
// 0: the big layout, 1: side by side with the panel.
|
||||
@@ -266,8 +269,9 @@ export component NowPlayingScreen inherits Rectangle {
|
||||
Rectangle { width: root.mix(24, 6); }
|
||||
b5 := NpButton { y: (parent.height - self.height) / 2; icon: root.liked == 1 ? "heart-filled" : "heart"; size: root.bs; on: root.liked == 1; focused: root.area == 0 && root.button == 5; alpha: root.alpha * (root.liked < 0 ? 0.4 : 1); }
|
||||
b6 := NpButton { y: (parent.height - self.height) / 2; icon: "lyrics"; size: root.bs; on: root.panel == 1; focused: root.area == 0 && root.button == 6; alpha: root.alpha; }
|
||||
b7 := NpButton { y: (parent.height - self.height) / 2; icon: "queue"; size: root.bs; on: root.panel == 2; focused: root.area == 0 && root.button == 7; alpha: root.alpha; }
|
||||
}
|
||||
property <[string]> hints: ["Keverés", "Előző", root.playing ? "Szünet" : "Lejátszás", "Következő", "Ismétlés", "Kedvelés", "Dalszöveg"];
|
||||
property <[string]> hints: ["Keverés", "Előző", root.playing ? "Szünet" : "Lejátszás", "Következő", "Ismétlés", "Kedvelés", "Dalszöveg", "Lejátszási sor"];
|
||||
Caption {
|
||||
x: root.tx;
|
||||
y: controls.y + controls.height + 18 * Tv.u;
|
||||
@@ -276,7 +280,7 @@ export component NowPlayingScreen inherits Rectangle {
|
||||
opacity: root.alpha;
|
||||
}
|
||||
|
||||
// ---- the panel: lyrics ----
|
||||
// ---- the panel: lyrics or the queue ----
|
||||
property <float> pa: root.alpha * clamp(root.t * 1.6 - 0.6, 0, 1);
|
||||
panel-pane := GlassPane {
|
||||
x: 820 * Tv.u;
|
||||
@@ -319,6 +323,66 @@ export component NowPlayingScreen inherits Rectangle {
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
// queue
|
||||
if root.panel == 2: Rectangle {
|
||||
clip: true;
|
||||
opacity: root.pa;
|
||||
Text {
|
||||
x: 56 * Tv.u;
|
||||
y: 44 * Tv.u;
|
||||
text: "Következik";
|
||||
font-size: 38 * Tv.u;
|
||||
font-weight: 700;
|
||||
color: Tv.text;
|
||||
}
|
||||
for q[i] in root.queue: Rectangle {
|
||||
x: 56 * Tv.u;
|
||||
y: (120 + i * 84) * Tv.u;
|
||||
width: parent.width - 112 * Tv.u;
|
||||
height: 72 * Tv.u;
|
||||
Rectangle {
|
||||
x: 0;
|
||||
width: 64 * Tv.u;
|
||||
height: 64 * Tv.u;
|
||||
y: 4 * Tv.u;
|
||||
border-radius: 8 * Tv.u;
|
||||
clip: true;
|
||||
background: #1b1d24;
|
||||
Image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
source: q.image;
|
||||
image-fit: cover;
|
||||
}
|
||||
}
|
||||
Text {
|
||||
x: 88 * Tv.u;
|
||||
y: 6 * Tv.u;
|
||||
width: parent.width - 88 * Tv.u;
|
||||
text: q.title;
|
||||
font-size: 26 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
x: 88 * Tv.u;
|
||||
y: 40 * Tv.u;
|
||||
width: parent.width - 88 * Tv.u;
|
||||
text: q.artist;
|
||||
font-size: 21 * Tv.u;
|
||||
color: Tv.text-tertiary;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if root.queue-note != "": Text {
|
||||
x: 56 * Tv.u;
|
||||
y: 130 * Tv.u;
|
||||
text: root.queue-note;
|
||||
font-size: 26 * Tv.u;
|
||||
color: Tv.text-secondary;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out property <[GlassRect]> glass: [
|
||||
@@ -335,7 +399,7 @@ export component NowPlayingScreen inherits Rectangle {
|
||||
tint: #ffffff.with-alpha(0.14 + 0.1 * root.pf),
|
||||
group: 0,
|
||||
},
|
||||
b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, b6.glass,
|
||||
b0.glass, b1.glass, b2.glass, b3.glass, b4.glass, b5.glass, b6.glass, b7.glass,
|
||||
panel-pane.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