diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 5533261..8f529ab 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -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 diff --git a/AGENTS.md b/AGENTS.md index 1748afc..8bf50f3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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). diff --git a/Cargo.lock b/Cargo.lock index 6098352..75b6b1e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -189,28 +189,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "alsa" -version = "0.9.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43" -dependencies = [ - "alsa-sys", - "bitflags 2.13.2", - "cfg-if", - "libc", -] - -[[package]] -name = "alsa-sys" -version = "0.3.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db8fee663d06c4e303404ef5f40488a53e062f89ba8bfed81f42325aafad1527" -dependencies = [ - "libc", - "pkg-config", -] - [[package]] name = "android-activity" version = "0.6.1" @@ -220,7 +198,7 @@ dependencies = [ "android-properties", "bitflags 2.13.2", "cc", - "jni 0.22.4", + "jni", "libc", "log", "ndk", @@ -529,12 +507,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "atomic_refcell" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" - [[package]] name = "atspi" version = "0.29.0" @@ -870,12 +842,6 @@ dependencies = [ "shlex 2.0.1", ] -[[package]] -name = "cesu8" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" - [[package]] name = "cexpr" version = "0.6.0" @@ -885,16 +851,6 @@ dependencies = [ "nom 7.1.3", ] -[[package]] -name = "cfg-expr" -version = "0.20.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" -dependencies = [ - "smallvec", - "target-lexicon", -] - [[package]] name = "cfg-if" version = "1.0.5" @@ -1125,58 +1081,12 @@ dependencies = [ "libc", ] -[[package]] -name = "core_detect" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" - -[[package]] -name = "coreaudio-rs" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aae284fbaf7d27aa0e292f7677dfbe26503b0d555026f702940805a630eac17" -dependencies = [ - "bitflags 1.3.2", - "libc", - "objc2-audio-toolbox", - "objc2-core-audio", - "objc2-core-audio-types", - "objc2-core-foundation", -] - [[package]] name = "countme" version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636" -[[package]] -name = "cpal" -version = "0.16.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbd307f43cc2a697e2d1f8bc7a1d824b5269e052209e28883e5bc04d095aaa3f" -dependencies = [ - "alsa", - "coreaudio-rs", - "dasp_sample", - "jni 0.21.1", - "js-sys", - "libc", - "mach2", - "ndk", - "ndk-context", - "num-derive", - "num-traits", - "objc2-audio-toolbox", - "objc2-core-audio", - "objc2-core-audio-types", - "wasm-bindgen", - "wasm-bindgen-futures", - "web-sys", - "windows 0.54.0", -] - [[package]] name = "cpufeatures" version = "0.2.17" @@ -1278,15 +1188,6 @@ dependencies = [ "dtor", ] -[[package]] -name = "ctr" -version = "0.9.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0369ee1ad671834580515889b80f2ea915f23b8be8d0daa4bbaf2ac5c7590835" -dependencies = [ - "cipher", -] - [[package]] name = "cursor-icon" version = "1.2.0" @@ -1328,12 +1229,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "dasp_sample" -version = "0.11.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" - [[package]] name = "data-encoding" version = "2.11.1" @@ -1569,20 +1464,6 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" -[[package]] -name = "encoding_rs" -version = "0.8.44" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" -dependencies = [ - "cfg-if", - "core_detect", - "multiversion_no_op", - "rustversion", - "scopeguard", - "simdutf8", -] - [[package]] name = "endi" version = "1.1.1" @@ -2115,19 +1996,6 @@ dependencies = [ "weezl", ] -[[package]] -name = "gio-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0071fe88dba8e40086c8ff9bbb62622999f49628344b1d1bf490a48a29d80f22" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", - "windows-sys 0.61.2", -] - [[package]] name = "gl_generator" version = "0.14.0" @@ -2139,50 +2007,6 @@ dependencies = [ "xml-rs", ] -[[package]] -name = "glib" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16de123c2e6c90ce3b573b7330de19be649080ec612033d397d72da265f1bd8b" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys", - "glib-macros", - "glib-sys", - "gobject-sys", - "libc", - "memchr", - "smallvec", -] - -[[package]] -name = "glib-macros" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf59b675301228a696fe01c3073974643365080a76cc3ed5bc2cbc466ad87f17" -dependencies = [ - "heck", - "proc-macro-crate", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "glib-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2d95e1a3a19ae464a7286e14af9a90683c64d70c02532d88d87ce95056af3e6c" -dependencies = [ - "libc", - "system-deps", -] - [[package]] name = "glob" version = "0.3.4" @@ -2279,17 +2103,6 @@ dependencies = [ "gl_generator", ] -[[package]] -name = "gobject-sys" -version = "0.21.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2dca35da0d19a18f4575f3cb99fe1c9e029a2941af5662f326f738a21edaf294" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - [[package]] name = "governor" version = "0.10.4" @@ -2329,128 +2142,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" -[[package]] -name = "gstreamer" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e8251db223ca38d9aefaf3d19f6f11581a9123cd12dacebd8b9e182da965023" -dependencies = [ - "cfg-if", - "futures-channel", - "futures-core", - "futures-util", - "glib", - "gstreamer-sys", - "itertools 0.14.0", - "kstring", - "libc", - "muldiv", - "num-integer", - "num-rational", - "option-operations", - "pastey 0.2.3", - "pin-project-lite", - "smallvec", - "thiserror 2.0.21", -] - -[[package]] -name = "gstreamer-app" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3da7017b2a2fa5cdf9123b1603947ea24174f6d8cea0ea673411df824c811921" -dependencies = [ - "futures-core", - "futures-sink", - "glib", - "gstreamer", - "gstreamer-app-sys", - "gstreamer-base", - "libc", -] - -[[package]] -name = "gstreamer-app-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4fa9f1b12b546aea543c15a0fdbc5a53617902a74f6d357a32b6a9fb4bc4725c" -dependencies = [ - "glib-sys", - "gstreamer-base-sys", - "gstreamer-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gstreamer-audio" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76c058cce8d32bfb6dd578a3d6d1d874b855a638b738d8bb34cd7aedd65aeddd" -dependencies = [ - "cfg-if", - "glib", - "gstreamer", - "gstreamer-audio-sys", - "gstreamer-base", - "libc", - "smallvec", -] - -[[package]] -name = "gstreamer-audio-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "807e476f555c4e7409d8c8fe4fd10fa9989b8e8f2898762d9551e1adfde98a2d" -dependencies = [ - "glib-sys", - "gobject-sys", - "gstreamer-base-sys", - "gstreamer-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gstreamer-base" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9375f9a12120a8ee17b765c816c9b23861ce258def77b0ee40a05acb00c74972" -dependencies = [ - "atomic_refcell", - "cfg-if", - "glib", - "gstreamer", - "gstreamer-base-sys", - "libc", -] - -[[package]] -name = "gstreamer-base-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b844f3559b6ab0379b4b771261643783ae4e0ffa71d5f5f46e33b7acf66b752" -dependencies = [ - "glib-sys", - "gobject-sys", - "gstreamer-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gstreamer-sys" -version = "0.24.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5d37c1a599ae57b8186948bd5699f2dbfc044baea9d400228b489a85bcf2759" -dependencies = [ - "cfg-if", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - [[package]] name = "h2" version = "0.4.20" @@ -2595,17 +2286,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "hostname" -version = "0.4.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "617aaa3557aef3810a6369d0a99fac8a080891b68bd9f9812a1eeda0c0730cbd" -dependencies = [ - "cfg-if", - "libc", - "windows-link 0.2.1", -] - [[package]] name = "htmlparser" version = "0.2.1" @@ -2671,7 +2351,6 @@ dependencies = [ "http", "http-body", "httparse", - "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -3280,16 +2959,6 @@ dependencies = [ "icu_properties", ] -[[package]] -name = "if-addrs" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf39cc0423ee66021dc5eccface85580e4a001e0c5288bae8bea7ecb69225e90" -dependencies = [ - "libc", - "windows-sys 0.59.0", -] - [[package]] name = "image" version = "0.25.10" @@ -3496,22 +3165,6 @@ dependencies = [ "syn 2.0.119", ] -[[package]] -name = "jni" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" -dependencies = [ - "cesu8", - "cfg-if", - "combine", - "jni-sys 0.3.1", - "log", - "thiserror 1.0.69", - "walkdir", - "windows-sys 0.45.0", -] - [[package]] name = "jni" version = "0.22.4" @@ -3628,15 +3281,6 @@ dependencies = [ "zbus", ] -[[package]] -name = "kstring" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a09b82a7f771ed02dc0dd9b27130a0fa5499fa15ed3027116c1e5e4e591bd9e" -dependencies = [ - "static_assertions", -] - [[package]] name = "kurbo" version = "0.13.1" @@ -3696,24 +3340,6 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" -[[package]] -name = "libmdns" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a00dbe871d2cf9df13f68d152b949fca8cafc854b60ffd259fc6df6e8663d8d7" -dependencies = [ - "byteorder", - "futures-util", - "hostname", - "if-addrs", - "log", - "multimap", - "rand 0.9.5", - "socket2", - "thiserror 2.0.21", - "tokio", -] - [[package]] name = "libredox" version = "0.1.25" @@ -3726,46 +3352,6 @@ dependencies = [ "redox_syscall 0.9.5", ] -[[package]] -name = "librespot-audio" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b3fe76acb49f58165484303edf0e7bd778f0e6d96f5c59e9d6b6fde1a90d36ff" -dependencies = [ - "aes", - "bytes", - "ctr", - "futures-util", - "http-body-util", - "hyper", - "hyper-util", - "librespot-core", - "log", - "tempfile", - "thiserror 2.0.21", - "tokio", -] - -[[package]] -name = "librespot-connect" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4b2a21e9e19b906c6676b1a515fc5529d5414f69049f5a167dfb2ea3206e5a27" -dependencies = [ - "futures-util", - "librespot-core", - "librespot-playback", - "librespot-protocol", - "log", - "protobuf", - "rand 0.9.5", - "serde_json", - "thiserror 2.0.21", - "tokio", - "tokio-stream", - "uuid", -] - [[package]] name = "librespot-core" version = "0.8.0" @@ -3823,34 +3409,6 @@ dependencies = [ "vergen-gitcl", ] -[[package]] -name = "librespot-discovery" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19be30e529532de833cad024d27ad9462f3acb02a3cf1953fbc314527691e0f5" -dependencies = [ - "aes", - "base64 0.22.1", - "bytes", - "ctr", - "form_urlencoded", - "futures-core", - "futures-util", - "hmac", - "http-body-util", - "hyper", - "hyper-util", - "libmdns", - "librespot-core", - "log", - "rand 0.9.5", - "serde_json", - "serde_repr", - "sha1", - "thiserror 2.0.21", - "tokio", -] - [[package]] name = "librespot-metadata" version = "0.8.0" @@ -3883,33 +3441,6 @@ dependencies = [ "url", ] -[[package]] -name = "librespot-playback" -version = "0.8.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88258620bf3e6808ea1fadd11639648d77c06280b9f5a4c9d14ea79f6f998af6" -dependencies = [ - "cpal", - "form_urlencoded", - "futures-util", - "gstreamer", - "gstreamer-app", - "gstreamer-audio", - "librespot-audio", - "librespot-core", - "librespot-metadata", - "log", - "portable-atomic", - "rand 0.9.5", - "rand_distr", - "rodio", - "shell-words", - "symphonia", - "thiserror 2.0.21", - "tokio", - "zerocopy", -] - [[package]] name = "librespot-protocol" version = "0.8.0" @@ -4057,15 +3588,6 @@ dependencies = [ "num-traits", ] -[[package]] -name = "mach2" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d640282b302c0bb0a2a8e0233ead9035e3bed871f0b7e81fe4a1ec829765db44" -dependencies = [ - "libc", -] - [[package]] name = "maybe-rayon" version = "0.1.1" @@ -4171,24 +3693,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "muldiv" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" - -[[package]] -name = "multimap" -version = "0.10.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" - -[[package]] -name = "multiversion_no_op" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" - [[package]] name = "naga" version = "30.0.1" @@ -4529,21 +4033,6 @@ dependencies = [ "objc2-quartz-core 0.3.2", ] -[[package]] -name = "objc2-audio-toolbox" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" -dependencies = [ - "bitflags 2.13.2", - "libc", - "objc2 0.6.5", - "objc2-core-audio", - "objc2-core-audio-types", - "objc2-core-foundation", - "objc2-foundation 0.3.2", -] - [[package]] name = "objc2-cloud-kit" version = "0.2.2" @@ -4568,28 +4057,6 @@ dependencies = [ "objc2-foundation 0.2.2", ] -[[package]] -name = "objc2-core-audio" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e1eebcea8b0dbff5f7c8504f3107c68fc061a3eb44932051c8cf8a68d969c3b2" -dependencies = [ - "dispatch2", - "objc2 0.6.5", - "objc2-core-audio-types", - "objc2-core-foundation", -] - -[[package]] -name = "objc2-core-audio-types" -version = "0.3.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a89f2ec274a0cf4a32642b2991e8b351a404d290da87bb6a9a9d8632490bd1c" -dependencies = [ - "bitflags 2.13.2", - "objc2 0.6.5", -] - [[package]] name = "objc2-core-data" version = "0.2.2" @@ -4876,15 +4343,6 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e" -[[package]] -name = "option-operations" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754" -dependencies = [ - "pastey 0.2.3", -] - [[package]] name = "orbclient" version = "0.3.55" @@ -5901,17 +5359,6 @@ dependencies = [ "windows-sys 0.52.0", ] -[[package]] -name = "rodio" -version = "0.21.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e40ecf59e742e03336be6a3d53755e789fd05a059fa22dfa0ed624722319e183" -dependencies = [ - "cpal", - "dasp_sample", - "num-rational", -] - [[package]] name = "rowan" version = "0.17.0" @@ -6318,12 +5765,6 @@ dependencies = [ "byteorder", ] -[[package]] -name = "shell-words" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc6fe69c597f9c37bfeeeeeb33da3530379845f10be461a66d16d03eca2ded77" - [[package]] name = "shlex" version = "1.3.0" @@ -6659,17 +6100,15 @@ dependencies = [ [[package]] name = "spotify-tv" -version = "0.1.1" +version = "0.2.0" dependencies = [ "anyhow", "env_logger", + "flate2", "futures-util", "hyper", - "librespot-connect", "librespot-core", - "librespot-discovery", "librespot-metadata", - "librespot-playback", "librespot-protocol", "log", "protobuf", @@ -6679,7 +6118,9 @@ dependencies = [ "sf-ui", "slint", "slint-build", + "tar", "tokio", + "tokio-tungstenite", "toml 0.9.12+spec-1.1.0", "ureq", ] @@ -6759,103 +6200,6 @@ dependencies = [ "zeno", ] -[[package]] -name = "symphonia" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" -dependencies = [ - "lazy_static", - "symphonia-bundle-flac", - "symphonia-bundle-mp3", - "symphonia-codec-vorbis", - "symphonia-core", - "symphonia-format-ogg", - "symphonia-metadata", -] - -[[package]] -name = "symphonia-bundle-flac" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" -dependencies = [ - "log", - "symphonia-core", - "symphonia-metadata", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-bundle-mp3" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" -dependencies = [ - "lazy_static", - "log", - "symphonia-core", - "symphonia-metadata", -] - -[[package]] -name = "symphonia-codec-vorbis" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" -dependencies = [ - "log", - "symphonia-core", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-core" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea00cc4f79b7f6bb7ff87eddc065a1066f3a43fe1875979056672c9ef948c2af" -dependencies = [ - "arrayvec", - "bitflags 1.3.2", - "bytemuck", - "lazy_static", - "log", -] - -[[package]] -name = "symphonia-format-ogg" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" -dependencies = [ - "log", - "symphonia-core", - "symphonia-metadata", - "symphonia-utils-xiph", -] - -[[package]] -name = "symphonia-metadata" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "36306ff42b9ffe6e5afc99d49e121e0bd62fe79b9db7b9681d48e29fa19e6b16" -dependencies = [ - "encoding_rs", - "lazy_static", - "log", - "symphonia-core", -] - -[[package]] -name = "symphonia-utils-xiph" -version = "0.5.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" -dependencies = [ - "symphonia-core", - "symphonia-metadata", -] - [[package]] name = "syn" version = "2.0.119" @@ -6945,19 +6289,6 @@ dependencies = [ "libc", ] -[[package]] -name = "system-deps" -version = "7.0.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "396a35feb67335377e0251fcbc1092fc85c484bd4e3a7a54319399da127796e7" -dependencies = [ - "cfg-expr", - "heck", - "pkg-config", - "toml 1.1.8+spec-1.1.0", - "version-compare", -] - [[package]] name = "taffy" version = "0.10.1" @@ -6981,12 +6312,6 @@ dependencies = [ "xattr", ] -[[package]] -name = "target-lexicon" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" - [[package]] name = "task-local" version = "0.1.1" @@ -7738,12 +7063,6 @@ dependencies = [ "rustversion", ] -[[package]] -name = "version-compare" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" - [[package]] name = "version_check" version = "0.9.5" @@ -7997,7 +7316,7 @@ version = "1.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe8d20d0214027baf11b8b0cc307c1da7657d8f4db9aa956f7de27a6fb1acbd5" dependencies = [ - "jni 0.22.4", + "jni", "log", "ndk-context", "objc2 0.6.5", @@ -8230,16 +7549,6 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows" -version = "0.54.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9252e5725dbed82865af151df558e754e4a3c2c30818359eb17465f1346a1b49" -dependencies = [ - "windows-core 0.54.0", - "windows-targets 0.52.6", -] - [[package]] name = "windows" version = "0.61.3" @@ -8283,16 +7592,6 @@ dependencies = [ "windows-core 0.62.2", ] -[[package]] -name = "windows-core" -version = "0.54.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12661b9c89351d684a50a8a643ce5f608e20243b9fb84687800163429f161d65" -dependencies = [ - "windows-result 0.1.2", - "windows-targets 0.52.6", -] - [[package]] name = "windows-core" version = "0.61.2" @@ -8406,15 +7705,6 @@ dependencies = [ "windows-strings 0.5.1", ] -[[package]] -name = "windows-result" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" -dependencies = [ - "windows-targets 0.52.6", -] - [[package]] name = "windows-result" version = "0.3.4" @@ -8451,15 +7741,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "windows-sys" -version = "0.45.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" -dependencies = [ - "windows-targets 0.42.2", -] - [[package]] name = "windows-sys" version = "0.48.0" @@ -8496,21 +7777,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "windows-targets" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-targets" version = "0.48.5" @@ -8560,12 +7826,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.5" @@ -8578,12 +7838,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.48.5" @@ -8596,12 +7850,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.48.5" @@ -8620,12 +7868,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.48.5" @@ -8638,12 +7880,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.48.5" @@ -8656,12 +7892,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.5" @@ -8674,12 +7904,6 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.48.5" diff --git a/Cargo.toml b/Cargo.toml index daf61b9..a2753d8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "spotify-tv" -description = "Spotify for Fennec OS: native TV client with Liquid Glass, Spotify Connect and librespot playback" -version = "0.1.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" diff --git a/README.md b/README.md index bf0bbce..8423ebb 100644 --- a/README.md +++ b/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 diff --git a/app.toml b/app.toml index e136e09..132a8bd 100644 --- a/app.toml +++ b/app.toml @@ -2,7 +2,7 @@ id = "support.bluefox.spotify" name = "Spotify" # Release versions only (1.2.3). Bump it (and Cargo.toml) for every release. -version = "0.1.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"] diff --git a/package.sh b/package.sh index d030239..94e6e02 100755 --- a/package.sh +++ b/package.sh @@ -6,15 +6,12 @@ # ./package.sh --arm adds support.bluefox.spotify--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 diff --git a/src/api.rs b/src/api.rs index 20f2d5f..db4ba1e 100644 --- a/src/api.rs +++ b/src/api.rs @@ -437,22 +437,18 @@ impl Api { pub fn search(&self, q: &str) -> Result { both!(self, search(q)) } - pub fn add_to_queue(&self, uri: &str) -> Result<()> { - both!(self, add_to_queue(uri)) - } } /// The Web API client (the mock server). #[derive(Clone)] pub struct Web { base: String, - engine: Engine, agent: ureq::Agent, cache: Arc>>, } impl 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)] diff --git a/src/app.rs b/src/app.rs index 6acb7ef..c029d38 100644 --- a/src/app.rs +++ b/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, } 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(); diff --git a/src/config.rs b/src/config.rs index 068227d..0857f1b 100644 --- a/src/config.rs +++ b/src/config.rs @@ -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() } } } diff --git a/src/internal.rs b/src/internal.rs index 787a105..8c32a9e 100644 --- a/src/internal.rs +++ b/src/internal.rs @@ -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)] diff --git a/src/keyserver.rs b/src/keyserver.rs new file mode 100644 index 0000000..2ab5904 --- /dev/null +++ b/src/keyserver.rs @@ -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, +} + +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 { + 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 { + // 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("

Kész ✓

A TV megkapta a kulcsot, és elindítja a lejátszót. Ezt az oldalt bezárhatod.

")) + } else { + ("400 Bad Request", page(&format!("

Ez nem tűnik kulcsnak

Másold ki a teljes kulcsot innen: {DASHBOARD}

{}", FORM))) + } + } else { + ("200 OK", page(&format!( + "

Spotify Soloist kulcs

1. Nyisd meg: developer.spotify.com/dashboard/soloist, jelentkezz be a Spotify-fiókoddal (Premium), és hozz létre egy kulcsot.

2. Másold ide, és küldd el a TV-nek.

{FORM}

A kulcs csak a TV-n marad.

" + ))) + }; + 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 = "
"; + +fn page(inner: &str) -> String { + format!( + "Spotify a TV-n{inner}" + ) +} + +/// 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"); + } +} diff --git a/src/main.rs b/src/main.rs index 1ffaa06..28db222 100644 --- a/src/main.rs +++ b/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()); diff --git a/src/nowplaying.rs b/src/nowplaying.rs index d62338b..625c2f5 100644 --- a/src/nowplaying.rs +++ b/src/nowplaying.rs @@ -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); } - sync(c); - c.track_changed(); + 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::>(), + )); + 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()); diff --git a/src/screens/artist.rs b/src/screens/artist.rs index 50e1a6b..7260040 100644 --- a/src/screens/artist.rs +++ b/src/screens/artist.rs @@ -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(); diff --git a/src/screens/collection.rs b/src/screens/collection.rs index 3158906..c06630e 100644 --- a/src/screens/collection.rs +++ b/src/screens/collection.rs @@ -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), diff --git a/src/screens/home.rs b/src/screens/home.rs index 6831862..ec3d7a3 100644 --- a/src/screens/home.rs +++ b/src/screens/home.rs @@ -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); } diff --git a/src/screens/mod.rs b/src/screens/mod.rs index 347ec30..d5a7a68 100644 --- a/src/screens/mod.rs +++ b/src/screens/mod.rs @@ -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 { 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 = 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 }); - } + let uris: Vec = 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 }); } /// 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() { - 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 }); - } + let uri = rest.split('|').next().unwrap_or(rest); + cx.play(Cmd::Tracks { uris: vec![uri.to_string()], start: 0 }); } else { return false; } @@ -238,15 +229,8 @@ fn open_track_menu(c: &Controller, t: Track, liked: Option) { 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"; diff --git a/src/screens/settings.rs b/src/screens/settings.rs index ccc7d47..1cce2f8 100644 --- a/src/screens/settings.rs +++ b/src/screens/settings.rs @@ -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()), + } +} diff --git a/src/soloist.rs b/src/soloist.rs new file mode 100644 index 0000000..755752d --- /dev/null +++ b/src/soloist.rs @@ -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 /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, +} + +/// 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, + mut cmds: mpsc::UnboundedReceiver, + shared: Arc>, + events: Arc, + status: Arc, +) { + 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, + cmds: &mut mpsc::UnboundedReceiver, + shared: &Arc>, + events: &Arc, + status: &Arc, +) -> Option { + 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), 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::().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::(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 { + 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 { + 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>, events: &Arc, status: &Arc, 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 = 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) { + if t.uri != self.track_uri { + self.track_uri = t.uri.clone(); + } + events(Event::Track(t)); + } + + fn active(&mut self, a: bool, shared: &Arc>, events: &Arc) { + 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) { + 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>, events: &Arc) { + 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})); + } +} diff --git a/src/spotify.rs b/src/spotify.rs index 83b284f..3518815 100644 --- a/src/spotify.rs +++ b/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), + /// 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::collection"), - /// from track `start` (a uri) or index, optionally shuffled. - Context { uri: String, start: Option, shuffle: bool }, - /// Plays a list of track uris from index `start`. + /// Plays an album, playlist, artist, show, or "spotify:user::collection". + Context { uri: String, shuffle: bool }, + /// Plays `uris[start]`, the ones after it queued. Tracks { uris: Vec, 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, cmd: mpsc::UnboundedSender, + solo: mpsc::UnboundedSender, + key: Arc>, + shared: Arc>, session: Arc>>, - /// 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, @@ -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 = Arc::new(events); let cfg = cfg.clone(); + if !mock { + let ev = events.clone(); + let status: Arc = 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 { + 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(&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 { - 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 { - 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, shared: Arc>>, events: Arc) { 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, shared: Arc 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::(); let mut pairing: Option> = None; let start_pairing = |pairing: &mut Option>| { @@ -382,38 +318,17 @@ async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver, shared: Arc = None; - let mut spirc_task: Option + Send>>> = None; + let mut session: Option = None; let mut failures = 0u32; - // Commands that came before Spirc was up (a load right after sign-in). - let mut waiting: Vec = 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, shared: Arc { 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, shared: Arc { - // 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(); } - let _ = std::fs::remove_file(cache_dir().join("credentials.json")); - 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), + 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); + } + 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, } } -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 { - 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, events: Arc) { tokio::time::sleep(Duration::from_millis(300)).await; @@ -654,6 +507,11 @@ async fn mock_loop(mut rx: mpsc::UnboundedReceiver, events: Arc().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, events: Arc 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, } diff --git a/ui/app.slint b/ui/app.slint index 988a28a..afea29d 100644 --- a/ui/app.slint +++ b/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 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 signin-t: self.screen == "signin" ? 1 : 0; animate signin-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + out property solokey-t: self.screen == "solokey" ? 1 : 0; + animate solokey-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } out property page-t: self.screen == "page" ? 1 : 0; animate page-t { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } out property 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 solokey-qr <=> solokey.qr; + in property 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 page-focus <=> page.focus-line; @@ -139,6 +149,8 @@ export component App inherits TvWindow { in property np-lyric-line <=> np.lyric-line; in property np-lyrics-synced <=> np.lyrics-synced; in property np-lyrics-note <=> np.lyrics-note; + in property <[QueueItem]> np-queue <=> np.queue; + in property np-queue-note <=> np.queue-note; in property np-device <=> np.device; np := NowPlayingScreen { alpha: root.vis(root.np-t) * root.under; @@ -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; diff --git a/ui/nowplaying.slint b/ui/nowplaying.slint index c4e5760..c9e9f83 100644 --- a/ui/nowplaying.slint +++ b/ui/nowplaying.slint @@ -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 liked: -1; in property button: 2; in property area; - // 0 none, 1 lyrics + // 0 none, 1 lyrics, 2 queue in property panel; in property <[string]> lyrics; in property lyric-line: -1; in property lyrics-synced; in property lyrics-note; + in property <[QueueItem]> queue; + in property queue-note; in property device; // 0: the big layout, 1: side by side with the panel. @@ -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 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, ]; } diff --git a/ui/signin.slint b/ui/signin.slint index 598639a..2dd8c3b 100644 --- a/ui/signin.slint +++ b/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 alpha: 1; + in property qr; + in property 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]; +}