Spotify for Fennec OS: native TV client
All checks were successful
release / release (push) Successful in 12m14s

Rust + Slint on sf-ui's Liquid Glass, with the page engine of Netflex TV.
librespot plays (GStreamer on the TV) and makes the TV a Spotify Connect
device; the Web API (token from the session) feeds the pages.

- Sign-in with the phone: a pairing code / QR code (spotify.com/pair,
  OAuth device flow) or picking the TV in the Spotify app (zeroconf).
- Home, search, library, playlist / album / liked songs / podcast pages,
  artist pages, settings; the user's picture top right.
- Now playing: seek, shuffle, repeat, like, synced lyrics, queue.
- package.sh builds x86-64 and aarch64 (Raspberry Pi); the Gitea CI
  releases both on a tag.
- tools/mock_server.py and SPOTIFY_MOCK for work without an account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-11-03 17:23:34 +01:00
commit 3a66e0c7c7
34 changed files with 17083 additions and 0 deletions

643
src/api.rs Normal file
View File

@@ -0,0 +1,643 @@
//! Spotify Web API (api.spotify.com/v1): browsing, the library, search, the
//! queue. The access token comes from the librespot session (spotify::Engine).
//!
//! Every answer is parsed leniently (missing fields default), since Spotify's
//! objects differ a bit between endpoints. GET answers are cached for a short
//! while: a TV jumps back and forth between the same pages, and Spotify
//! rate-limits busy clients (429 + Retry-After, honoured once).
use std::collections::HashMap;
use std::io::Read;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use serde::Deserialize;
use serde::de::DeserializeOwned;
use crate::spotify::Engine;
pub const API: &str = "https://api.spotify.com/v1";
const CACHE_FOR: Duration = Duration::from_secs(90);
// ---------------------------------------------------------------------------- objects
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Image {
pub url: String,
pub width: Option<u32>,
}
/// The picture closest to `want` px wide (Spotify lists them largest first).
pub fn pick(images: &[Image], want: u32) -> String {
let mut best: Option<&Image> = None;
for i in images {
let w = i.width.unwrap_or(640);
best = match best {
None => Some(i),
Some(b) => {
let bw = b.width.unwrap_or(640);
// Prefer the smallest that is still big enough.
let better = if w >= want && bw >= want { w < bw } else { w > bw };
Some(if better { i } else { b })
}
};
}
best.map(|i| i.url.clone()).unwrap_or_default()
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Named {
pub id: String,
pub name: String,
pub uri: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Album {
pub id: String,
pub name: String,
pub uri: String,
pub images: Vec<Image>,
pub artists: Vec<Named>,
pub release_date: String,
pub total_tracks: u32,
pub album_type: String,
pub label: String,
pub tracks: Option<Paging<Track>>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Track {
pub id: String,
pub name: String,
pub uri: String,
/// "track" | "episode"
#[serde(rename = "type")]
pub kind: String,
pub duration_ms: u32,
pub explicit: bool,
pub artists: Vec<Named>,
pub album: Option<Album>,
pub track_number: u32,
pub is_playable: Option<bool>,
// episodes
pub images: Vec<Image>,
pub show: Option<Show>,
pub release_date: String,
pub description: String,
pub resume_point: Option<ResumePoint>,
}
impl Track {
pub fn artist_names(&self) -> String {
if let Some(s) = &self.show {
return s.name.clone();
}
self.artists.iter().map(|a| a.name.as_str()).collect::<Vec<_>>().join(", ")
}
pub fn image(&self, want: u32) -> String {
if !self.images.is_empty() {
return pick(&self.images, want);
}
self.album.as_ref().map(|a| pick(&a.images, want)).or_else(|| self.show.as_ref().map(|s| pick(&s.images, want))).unwrap_or_default()
}
pub fn playable(&self) -> bool {
self.is_playable != Some(false) && !self.uri.is_empty() && !self.uri.starts_with("spotify:local:")
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct ResumePoint {
pub fully_played: bool,
pub resume_position_ms: u32,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Owner {
pub id: String,
pub display_name: Option<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Total {
pub total: u32,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Playlist {
pub id: String,
pub name: String,
pub uri: String,
pub images: Option<Vec<Image>>,
pub description: String,
pub owner: Owner,
pub tracks: Option<Total>,
pub items: Option<Total>,
pub followers: Option<Total>,
}
impl Playlist {
pub fn image(&self, want: u32) -> String {
self.images.as_deref().map(|i| pick(i, want)).unwrap_or_default()
}
pub fn count(&self) -> u32 {
self.tracks.as_ref().or(self.items.as_ref()).map(|t| t.total).unwrap_or(0)
}
pub fn owner_name(&self) -> String {
self.owner.display_name.clone().unwrap_or_else(|| self.owner.id.clone())
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Artist {
pub id: String,
pub name: String,
pub uri: String,
pub images: Vec<Image>,
pub followers: Option<Total>,
pub genres: Vec<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Show {
pub id: String,
pub name: String,
pub uri: String,
pub images: Vec<Image>,
pub publisher: String,
pub description: String,
pub total_episodes: u32,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct Paging<T> {
/// Search answers may hold nulls.
pub items: Vec<Option<T>>,
pub next: Option<String>,
pub total: u32,
pub offset: u32,
}
impl<T> Default for Paging<T> {
fn default() -> Self {
Paging { items: Vec::new(), next: None, total: 0, offset: 0 }
}
}
impl<T: Clone> Paging<T> {
pub fn list(&self) -> Vec<T> {
self.items.iter().flatten().cloned().collect()
}
pub fn more(&self) -> bool {
self.next.is_some()
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct User {
pub id: String,
pub display_name: Option<String>,
pub product: String,
pub country: String,
pub images: Vec<Image>,
}
impl User {
pub fn name(&self) -> String {
self.display_name.clone().filter(|n| !n.is_empty()).unwrap_or_else(|| self.id.clone())
}
}
#[derive(Debug, Clone, Deserialize)]
struct Saved<T> {
track: Option<T>,
album: Option<T>,
show: Option<T>,
episode: Option<T>,
/// Playlist entries: newer answers call it "item".
item: Option<T>,
}
impl<T> Saved<T> {
fn into_inner(self) -> Option<T> {
self.track.or(self.item).or(self.album).or(self.show).or(self.episode)
}
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct PlayContext {
pub uri: String,
#[serde(rename = "type")]
pub kind: String,
}
#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
pub struct Played {
pub track: Track,
pub context: Option<PlayContext>,
}
#[derive(Debug, Clone, Default)]
pub struct SearchResult {
pub tracks: Vec<Track>,
pub artists: Vec<Artist>,
pub albums: Vec<Album>,
pub playlists: Vec<Playlist>,
pub shows: Vec<Show>,
}
// ---------------------------------------------------------------------------- errors
#[derive(Debug)]
pub struct ApiError {
pub status: u16,
pub message: String,
}
impl std::fmt::Display for ApiError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.message, self.status)
}
}
impl std::error::Error for ApiError {}
pub fn status_of(e: &anyhow::Error) -> Option<u16> {
e.downcast_ref::<ApiError>().map(|a| a.status)
}
/// A short Hungarian message for the screen.
pub fn describe(e: &anyhow::Error) -> String {
if let Some(a) = e.downcast_ref::<ApiError>() {
return a.message.clone();
}
for cause in e.chain() {
if let Some(u) = cause.downcast_ref::<ureq::Error>() {
return match u {
ureq::Error::Timeout(_) => "A Spotify nem válaszolt időben.".into(),
ureq::Error::Io(_) | ureq::Error::ConnectionFailed | ureq::Error::HostNotFound => "A Spotify nem érhető el. Ellenőrizd a hálózatot.".into(),
other => format!("Hálózati hiba: {other}"),
};
}
}
format!("{e:#}")
}
pub fn enc(s: &str) -> String {
let mut out = String::new();
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
// ---------------------------------------------------------------------------- client
/// Cheap to clone; usable from any thread (blocking calls).
#[derive(Clone)]
pub struct Api {
base: String,
engine: Engine,
agent: ureq::Agent,
cache: Arc<Mutex<HashMap<String, (Instant, String)>>>,
}
impl Api {
pub fn new(engine: Engine) -> Api {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(30)))
.timeout_connect(Some(Duration::from_secs(8)))
.http_status_as_error(false)
.user_agent(concat!("FennecSpotifyTV/", env!("CARGO_PKG_VERSION")))
.build()
.into();
let base = std::env::var("SPOTIFY_API").unwrap_or_else(|_| API.to_string());
Api { base: base.trim_end_matches('/').to_string(), engine, agent, cache: Arc::default() }
}
/// Forgets cached answers (after a change to the library).
pub fn forget(&self, prefix: &str) {
let full = format!("{}{prefix}", self.base);
self.cache.lock().unwrap().retain(|k, _| !k.starts_with(&full));
}
fn url(&self, path: &str) -> String {
if path.starts_with("http") { path.to_string() } else { format!("{}{path}", self.base) }
}
fn call(&self, method: &str, path: &str, cache: bool) -> Result<String> {
let url = self.url(path);
if cache && method == "GET" {
if let Some((at, body)) = self.cache.lock().unwrap().get(&url) {
if at.elapsed() < CACHE_FOR {
return Ok(body.clone());
}
}
}
let mut tries = 0;
loop {
tries += 1;
let auth = format!("Bearer {}", self.engine.token()?);
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(),
"PUT" => self.agent.put(&url).header("Authorization", &auth).send_empty(),
_ => self.agent.delete(&url).header("Authorization", &auth).call(),
}
.with_context(|| format!("{method} {path}"))?;
let status = resp.status().as_u16();
let retry = resp.headers().get("retry-after").and_then(|v| v.to_str().ok()).and_then(|v| v.parse::<u64>().ok());
let mut text = String::new();
resp.into_body().into_reader().take(16 << 20).read_to_string(&mut text)?;
if status == 429 && tries == 1 {
let wait = retry.unwrap_or(2).min(8);
log::warn!("{path}: rate limited, waiting {wait} s");
std::thread::sleep(Duration::from_secs(wait));
continue;
}
if status == 502 || status == 503 {
if tries < 3 {
std::thread::sleep(Duration::from_millis(600));
continue;
}
}
if !(200..300).contains(&status) {
let v: serde_json::Value = serde_json::from_str(&text).unwrap_or_default();
let detail = v["error"]["message"].as_str().unwrap_or("").to_string();
log::warn!("{method} {path}: {status} {detail}");
let message = match status {
401 => "A Spotify bejelentkezés lejárt".into(),
403 => "A Spotify ezt nem engedi".to_string(),
404 => "Nem található".into(),
429 => "A Spotify túl sok kérést kapott, próbáld újra kicsit később".into(),
s => format!("A Spotify hibát jelzett ({s})"),
};
return Err(ApiError { status, message }.into());
}
if cache && method == "GET" {
let mut c = self.cache.lock().unwrap();
if c.len() > 300 {
c.retain(|_, (at, _)| at.elapsed() < CACHE_FOR);
}
c.insert(url.clone(), (Instant::now(), text.clone()));
}
return Ok(text);
}
}
fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let text = self.call("GET", path, true)?;
let text = if text.trim().is_empty() { "null" } else { text.as_str() };
serde_json::from_str(text).with_context(|| format!("GET {path}: unexpected answer"))
}
fn send(&self, method: &str, path: &str) -> Result<()> {
self.call(method, path, false).map(|_| ())
}
/// A page of saved things ({ items: [{ track | album | show | item }] }).
fn saved<T: DeserializeOwned + Clone>(&self, path: &str) -> Result<Paging<T>> {
let p: Paging<Saved<T>> = self.get(path)?;
Ok(Paging { items: p.items.into_iter().map(|s| s.and_then(Saved::into_inner)).collect(), next: p.next, total: p.total, offset: p.offset })
}
// ---- account ----
pub fn me(&self) -> Result<User> {
self.get("/me")
}
// ---- home ----
pub fn recently_played(&self) -> Result<Vec<Played>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
items: Vec<Played>,
}
Ok(self.get::<R>("/me/player/recently-played?limit=50")?.items)
}
pub fn top_artists(&self) -> Result<Vec<Artist>> {
Ok(self.get::<Paging<Artist>>("/me/top/artists?limit=20&time_range=short_term")?.list())
}
pub fn top_tracks(&self) -> Result<Vec<Track>> {
Ok(self.get::<Paging<Track>>("/me/top/tracks?limit=20&time_range=short_term")?.list())
}
pub fn new_releases(&self) -> Result<Vec<Album>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
albums: Paging<Album>,
}
Ok(self.get::<R>("/browse/new-releases?limit=20")?.albums.list())
}
// ---- library ----
pub fn my_playlists(&self, offset: u32) -> Result<Paging<Playlist>> {
self.get(&format!("/me/playlists?limit=50&offset={offset}"))
}
pub fn liked(&self, offset: u32) -> Result<Paging<Track>> {
self.saved(&format!("/me/tracks?limit=50&offset={offset}"))
}
pub fn saved_albums(&self, offset: u32) -> Result<Paging<Album>> {
self.saved(&format!("/me/albums?limit=50&offset={offset}"))
}
pub fn saved_shows(&self, offset: u32) -> Result<Paging<Show>> {
self.saved(&format!("/me/shows?limit=50&offset={offset}"))
}
/// Followed artists (cursor paging: `after` is the last artist's id).
pub fn followed_artists(&self, after: &str) -> Result<(Vec<Artist>, Option<String>)> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct Cursors {
after: Option<String>,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct P {
items: Vec<Artist>,
cursors: Cursors,
}
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
artists: P,
}
let q = if after.is_empty() { String::new() } else { format!("&after={}", enc(after)) };
let r: R = self.get(&format!("/me/following?type=artist&limit=50{q}"))?;
Ok((r.artists.items, r.artists.cursors.after))
}
pub fn liked_contains(&self, ids: &[String]) -> Result<Vec<bool>> {
if ids.is_empty() {
return Ok(Vec::new());
}
let mut out = Vec::new();
for chunk in ids.chunks(50) {
let v: Vec<bool> = self.get(&format!("/me/tracks/contains?ids={}", chunk.join(",")))?;
out.extend(v);
}
Ok(out)
}
pub fn set_liked(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/tracks");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/tracks?ids={id}"))
}
pub fn album_saved(&self, id: &str) -> Result<bool> {
Ok(self.get::<Vec<bool>>(&format!("/me/albums/contains?ids={id}"))?.first().copied().unwrap_or(false))
}
pub fn set_album_saved(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/albums");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/albums?ids={id}"))
}
pub fn show_saved(&self, id: &str) -> Result<bool> {
Ok(self.get::<Vec<bool>>(&format!("/me/shows/contains?ids={id}"))?.first().copied().unwrap_or(false))
}
pub fn set_show_saved(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/shows");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/shows?ids={id}"))
}
pub fn following_artist(&self, id: &str) -> Result<bool> {
Ok(self.get::<Vec<bool>>(&format!("/me/following/contains?type=artist&ids={id}"))?.first().copied().unwrap_or(false))
}
pub fn set_following_artist(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/following");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/me/following?type=artist&ids={id}"))
}
pub fn following_playlist(&self, id: &str, user: &str) -> Result<bool> {
let r = self.get::<Vec<bool>>(&format!("/playlists/{id}/followers/contains?ids={}", enc(user)));
Ok(r?.first().copied().unwrap_or(false))
}
pub fn set_following_playlist(&self, id: &str, on: bool) -> Result<()> {
self.forget("/me/playlists");
self.send(if on { "PUT" } else { "DELETE" }, &format!("/playlists/{id}/followers"))
}
// ---- pages ----
pub fn playlist(&self, id: &str) -> Result<Playlist> {
self.get(&format!("/playlists/{id}?fields=id,name,uri,images,description,owner(id,display_name),followers(total),tracks(total)"))
}
pub fn playlist_tracks(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
let path = format!("/playlists/{id}/tracks?limit=100&offset={offset}&additional_types=track,episode");
match self.saved(&path) {
// Newer API versions moved the list to /items.
Err(e) if matches!(status_of(&e), Some(403 | 404 | 410)) => self.saved(&format!("/playlists/{id}/items?limit=100&offset={offset}&additional_types=track,episode")),
r => r,
}
}
pub fn album(&self, id: &str) -> Result<Album> {
self.get(&format!("/albums/{id}"))
}
pub fn album_tracks(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
self.get(&format!("/albums/{id}/tracks?limit=50&offset={offset}"))
}
pub fn artist(&self, id: &str) -> Result<Artist> {
self.get(&format!("/artists/{id}"))
}
pub fn artist_top(&self, id: &str, market: &str) -> Result<Vec<Track>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
tracks: Vec<Track>,
}
let m = if market.is_empty() { "from_token".to_string() } else { market.to_string() };
Ok(self.get::<R>(&format!("/artists/{id}/top-tracks?market={m}"))?.tracks)
}
/// `groups`: "album" | "single" | "appears_on" | "compilation", comma separated.
pub fn artist_albums(&self, id: &str, groups: &str) -> Result<Vec<Album>> {
Ok(self.get::<Paging<Album>>(&format!("/artists/{id}/albums?include_groups={groups}&limit=30"))?.list())
}
pub fn show(&self, id: &str) -> Result<Show> {
self.get(&format!("/shows/{id}"))
}
pub fn show_episodes(&self, id: &str, offset: u32) -> Result<Paging<Track>> {
self.get(&format!("/shows/{id}/episodes?limit=50&offset={offset}"))
}
// ---- search ----
pub fn search(&self, q: &str) -> Result<SearchResult> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
tracks: Paging<Track>,
artists: Paging<Artist>,
albums: Paging<Album>,
playlists: Paging<Playlist>,
shows: Paging<Show>,
}
let r: R = self.get(&format!("/search?q={}&type=track,artist,album,playlist,show&limit=10", enc(q)))?;
Ok(SearchResult { tracks: r.tracks.list(), artists: r.artists.list(), albums: r.albums.list(), playlists: r.playlists.list(), shows: r.shows.list() })
}
// ---- player ----
/// What comes next on the active device.
pub fn queue(&self) -> Result<Vec<Track>> {
#[derive(Deserialize, Default)]
#[serde(default)]
struct R {
queue: Vec<Track>,
}
let text = self.call("GET", "/me/player/queue", false)?;
Ok(serde_json::from_str::<R>(&text).unwrap_or_default().queue)
}
pub fn add_to_queue(&self, uri: &str) -> Result<()> {
self.send("POST", &format!("/me/player/queue?uri={}", enc(uri)))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn picks_the_right_picture() {
let imgs = vec![
Image { url: "640".into(), width: Some(640) },
Image { url: "300".into(), width: Some(300) },
Image { url: "64".into(), width: Some(64) },
];
assert_eq!(pick(&imgs, 250), "300");
assert_eq!(pick(&imgs, 400), "640");
assert_eq!(pick(&imgs, 1000), "640");
assert_eq!(pick(&imgs, 10), "64");
assert_eq!(pick(&[], 10), "");
}
#[test]
fn parses_saved_and_null_items() {
let p: Paging<Saved<Track>> = serde_json::from_str(r#"{"items":[{"track":{"id":"a","name":"A","uri":"spotify:track:a","type":"track"}},null,{"item":{"id":"b","type":"episode"}}],"total":3,"next":null}"#).unwrap();
let list: Vec<Track> = p.items.into_iter().flatten().filter_map(Saved::into_inner).collect();
assert_eq!(list.len(), 2);
assert_eq!(list[1].kind, "episode");
let s: Paging<Playlist> = serde_json::from_str(r#"{"items":[null,{"id":"p","name":"P","images":null,"owner":{"id":"u"}}]}"#).unwrap();
assert_eq!(s.list().len(), 1);
assert_eq!(s.list()[0].owner_name(), "u");
}
#[test]
fn encodes_queries() {
assert_eq!(enc("Dűne ä&b"), "D%C5%B1ne%20%C3%A4%26b");
}
}

1052
src/app.rs Normal file

File diff suppressed because it is too large Load Diff

123
src/config.rs Normal file
View File

@@ -0,0 +1,123 @@
//! What this TV remembers: its Connect identity and the playback settings.
//! `$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).
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
pub const DEFAULT_NAME: &str = "Fennec TV";
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
/// Spotify Connect device id (stays the same, so phones remember the TV).
#[serde(default)]
pub device_id: String,
/// 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,
/// "auto" | "full" | "light" | "off" (Material)
#[serde(default = "auto")]
pub glass: String,
}
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() }
}
}
pub fn home() -> PathBuf {
std::env::var_os("HOME").or_else(|| std::env::var_os("APPDATA")).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
}
fn path() -> PathBuf {
home().join(".config").join("spotify-tv").join("config.toml")
}
/// 40 hex digits, random enough for a device id.
fn new_device_id() -> String {
use std::collections::hash_map::RandomState;
use std::hash::{BuildHasher, Hasher};
let mut out = String::new();
while out.len() < 40 {
let mut h = RandomState::new().build_hasher();
h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
h.write_u32(std::process::id());
out.push_str(&format!("{:016x}", h.finish()));
}
out.truncate(40);
out
}
impl Config {
pub fn load() -> Config {
let mut c: Config = std::fs::read_to_string(path()).ok().and_then(|t| toml::from_str(&t).ok()).unwrap_or_default();
if c.device_id.len() != 40 || !c.device_id.chars().all(|ch| ch.is_ascii_hexdigit()) {
c.device_id = new_device_id();
c.save();
}
if c.device_name.trim().is_empty() {
c.device_name = default_name();
}
c
}
pub fn save(&self) {
let p = path();
let result = (|| -> anyhow::Result<()> {
std::fs::create_dir_all(p.parent().unwrap())?;
let tmp = p.with_extension("tmp");
std::fs::write(&tmp, toml::to_string(self)?)?;
std::fs::rename(&tmp, &p)?;
Ok(())
})();
if let Err(e) = result {
log::warn!("saving {}: {e:#}", p.display());
}
}
}
/// Applies the glass look. "auto": sf-ui measures the GPU and picks full,
/// light or the matte Material style; "off" (shown as "Matt") is Material.
pub fn apply_look(glass: &sf_ui::Glass, look: &str) {
match look {
"full" => glass.set_quality(sf_ui::Quality::Full),
"light" => glass.set_quality(sf_ui::Quality::Light),
"off" => glass.set_quality(sf_ui::Quality::Material),
_ => glass.set_auto_quality(),
}
}
#[cfg(test)]
mod tests {
#[test]
fn device_ids_are_hex() {
let id = super::new_device_id();
assert_eq!(id.len(), 40);
assert!(id.chars().all(|c| c.is_ascii_hexdigit()));
}
}

104
src/format.rs Normal file
View File

@@ -0,0 +1,104 @@
//! Hungarian texts: times, counts, dates.
/// 214000 -> "3:34", 3725000 -> "1:02:05".
pub fn clock(ms: u32) -> String {
let s = ms / 1000;
let (h, m, s) = (s / 3600, (s / 60) % 60, s % 60);
if h > 0 { format!("{h}:{m:02}:{s:02}") } else { format!("{m}:{s:02}") }
}
/// A list's length: "1 óra 12 perc", "48 perc".
pub fn total(ms: u64) -> String {
let min = (ms / 60_000) as u32;
match (min / 60, min % 60) {
(0, m) => format!("{m} perc"),
(h, 0) => format!("{h} óra"),
(h, m) => format!("{h} óra {m} perc"),
}
}
/// 1234567 -> "1 234 567".
pub fn thousands(n: u32) -> String {
let s = n.to_string();
let mut out = String::new();
for (i, ch) in s.chars().enumerate() {
if i > 0 && (s.len() - i) % 3 == 0 {
out.push('\u{a0}');
}
out.push(ch);
}
out
}
/// Followers: "12 345 követő", "1,2 millió követő".
pub fn followers(n: u32) -> String {
if n >= 1_000_000 {
let m = n as f64 / 1_000_000.0;
let t = if m >= 100.0 { format!("{m:.0}") } else { format!("{m:.1}").replace('.', ",") };
format!("{} millió követő", t.trim_end_matches(",0"))
} else {
format!("{} követő", thousands(n))
}
}
/// "2023-05-12" -> "2023".
pub fn year(date: &str) -> String {
date.split('-').next().unwrap_or("").to_string()
}
/// "2023-05-12" -> "2023. máj. 12."
pub fn date(d: &str) -> String {
const MONTHS: [&str; 12] = ["jan.", "febr.", "márc.", "ápr.", "máj.", "jún.", "júl.", "aug.", "szept.", "okt.", "nov.", "dec."];
let p: Vec<&str> = d.split('-').collect();
match p.as_slice() {
[y, m, day] => match m.parse::<usize>().ok().and_then(|m| MONTHS.get(m.wrapping_sub(1))) {
Some(mn) => format!("{y}. {mn} {}.", day.trim_start_matches('0')),
None => d.to_string(),
},
[y, ..] => y.to_string(),
_ => d.to_string(),
}
}
/// Album types as Spotify's Hungarian UI calls them.
pub fn album_type(t: &str) -> &'static str {
match t {
"single" => "Kislemez",
"compilation" => "Válogatás",
"ep" => "EP",
_ => "Album",
}
}
/// Strips the HTML Spotify puts into playlist descriptions.
pub fn plain(html: &str) -> String {
let mut out = String::new();
let mut tag = false;
for ch in html.chars() {
match ch {
'<' => tag = true,
'>' => tag = false,
c if !tag => out.push(c),
_ => {}
}
}
out.replace("&amp;", "&").replace("&#x27;", "'").replace("&quot;", "\"").replace("&lt;", "<").replace("&gt;", ">").replace("&#39;", "'")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn formats() {
assert_eq!(clock(214_000), "3:34");
assert_eq!(clock(3_725_000), "1:02:05");
assert_eq!(total(4_320_000), "1 óra 12 perc");
assert_eq!(total(2_880_000), "48 perc");
assert_eq!(thousands(1234567), "1\u{a0}234\u{a0}567");
assert_eq!(followers(1_200_000), "1,2 millió követő");
assert_eq!(followers(2_000_000), "2 millió követő");
assert_eq!(date("2023-05-02"), "2023. máj. 2.");
assert_eq!(plain("Hits <a href=\"x\">here</a> &amp; more"), "Hits here & more");
}
}

58
src/main.rs Normal file
View File

@@ -0,0 +1,58 @@
//! Spotify for Fennec OS: a native TV client.
//!
//! - UI: Slint (ui/*.slint) on sf-ui's Liquid Glass layer; the page engine
//! and controller come from Netflex TV.
//! - Spotify: librespot (src/spotify.rs) for the session, Spotify Connect,
//! the zeroconf sign-in and playback; the Web API (src/api.rs) for
//! browsing.
mod api;
mod app;
mod config;
mod format;
mod nowplaying;
mod page;
mod screens;
mod spotify;
mod task;
use slint::{ComponentHandle, Model};
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();
sf_ui::init()?;
let ui = App::new()?;
ui.sf_ui_setup();
if std::env::var_os("SF_UI_SIZE").is_none() && std::env::var_os("SPOTIFY_WINDOWED").is_none() {
ui.window().set_fullscreen(true);
}
// Development: where the window opens ("x,y", physical px), e.g. on a
// second monitor.
if let Some((x, y)) = std::env::var("SPOTIFY_WINDOW_POS").ok().and_then(|v| v.split_once(',').and_then(|(x, y)| Some((x.trim().parse().ok()?, y.trim().parse().ok()?)))) {
ui.window().set_position(slint::PhysicalPosition::new(x, y));
}
let glass = sf_ui::Glass::install(&ui, |ui, p| {
p.extend(ui.get_glass_signin().iter());
p.extend(ui.get_glass_page().iter());
p.extend(ui.get_glass_page_keyboard().iter());
p.extend(ui.get_glass_np().iter());
p.extend(ui.get_glass_input().iter());
p.extend(ui.get_glass_input_keyboard().iter());
p.extend(ui.get_glass_select().iter());
p.extend(ui.get_glass_toast().iter());
})?;
glass.set_palette(sf_ui::Palette::from_hex(app::PALETTE));
let images = sf_ui::images::Images::new(256 << 20);
let app = app::Controller::new(&ui, glass, images);
ui.run()?;
app.shutdown();
// Background threads (image loader, audio, network) need no goodbye.
std::process::exit(0)
}

524
src/nowplaying.rs Normal file
View File

@@ -0,0 +1,524 @@
//! Most szól: the big cover, the title, the progress, the controls (shuffle,
//! previous, play/pause, next, repeat, like, lyrics, queue), synced lyrics
//! and the queue. Also keeps the playback state that the engine reports
//! (pages show it in the "now playing" capsule of the nav).
//!
//! Keys: left/right between the buttons, OK presses one, up goes to the
//! progress bar (left/right seek there), Back returns to the pages. Space
//! (play/pause on a keyboard) works everywhere.
use std::rc::Rc;
use std::time::{Duration, Instant};
use slint::{Model, ModelRc, VecModel};
use crate::api;
use crate::app::{Action, Controller, Look};
use crate::spotify::{Cmd, Event, Track};
use crate::{QueueItem, format, task};
/// The buttons, left to right.
const BUTTONS: [&str; 8] = ["shuffle", "prev", "play", "next", "repeat", "like", "lyrics", "queue"];
const PLAY: usize = 2;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Panel {
#[default]
None,
Lyrics,
Queue,
}
#[derive(Default)]
pub struct NowPlaying {
pub track: Option<Track>,
pub playing: bool,
pub loading: bool,
pos_ms: u32,
since: Option<Instant>,
pub shuffle: bool,
pub repeat: (bool, bool),
liked: Option<bool>,
/// (track id, lines, synced); empty lines = none.
lyrics: Option<(String, Vec<(u32, String)>, bool)>,
lyrics_loading: bool,
queue: Vec<api::Track>,
panel: Panel,
focus: usize,
/// 0: the buttons, 1: the progress bar.
area: u8,
/// Another device that plays now (its name).
elsewhere: String,
}
impl NowPlaying {
pub fn position(&self) -> u32 {
let p = match (self.playing, self.since) {
(true, Some(at)) => self.pos_ms + at.elapsed().as_millis() as u32,
_ => self.pos_ms,
};
match &self.track {
Some(t) if t.duration_ms > 0 => p.min(t.duration_ms),
_ => p,
}
}
fn set_pos(&mut self, ms: u32) {
self.pos_ms = ms;
self.since = Some(Instant::now());
}
}
pub fn on_event(c: &Controller, ev: Event) {
let mut new_track = false;
{
let mut st = c.state.borrow_mut();
let np = &mut st.np;
match ev {
Event::Track(t) => {
new_track = np.track.as_ref().map(|o| &o.uri) != Some(&t.uri);
if new_track {
np.liked = None;
np.set_pos(0);
}
np.track = Some(t);
np.elsewhere.clear();
}
Event::Loading => np.loading = true,
Event::Playing(p) => {
np.playing = true;
np.loading = false;
np.elsewhere.clear();
np.set_pos(p);
}
Event::Paused(p) => {
np.playing = false;
np.loading = false;
np.set_pos(p);
}
Event::Seeked(p) => np.set_pos(p),
Event::Stopped => {
let p = np.position();
np.playing = false;
np.loading = false;
np.set_pos(p);
}
Event::Unavailable => {
drop(st);
c.toast("Ez a szám most nem játszható le.", true);
return;
}
Event::Shuffle(on) => np.shuffle = on,
Event::Repeat(ctx, track) => np.repeat = (ctx, track),
Event::Active(true) => {
let open = st.screen == "page" && st.np.track.is_some();
drop(st);
if open {
self::open(c);
}
return;
}
Event::Active(false) => {
let p = np.position();
np.playing = false;
np.set_pos(p);
}
Event::Client(name) => {
if !name.is_empty() {
np.elsewhere = name;
}
}
Event::Status(_) | Event::Pair(_) => {}
}
}
if new_track {
track_changed(c);
}
sync(c);
c.track_changed();
}
/// 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();
(st.np.track.clone(), st.np.panel)
};
let Some(t) = track else { return };
if c.state.borrow().screen == "nowplaying" {
c.backdrop(&t.cover, Look::Soft, &format!("np:{}", t.uri));
}
load_cover(c, &t);
if !t.episode && !t.id.is_empty() {
let api = c.api();
let c2 = c.clone();
let id = t.id.clone();
task::spawn(
move || api.liked_contains(std::slice::from_ref(&id)).map(|v| v.first().copied().unwrap_or(false)),
move |r| {
if let Ok(liked) = r {
let mut st = c2.state.borrow_mut();
if st.np.track.as_ref().is_some_and(|x| x.id == t.id) {
st.np.liked = Some(liked);
}
drop(st);
sync(&c2);
}
},
);
}
match panel {
Panel::Lyrics => load_lyrics(c),
Panel::Queue => load_queue(c),
Panel::None => {}
}
}
fn load_cover(c: &Controller, t: &Track) {
let Some(ui) = c.ui() else { return };
ui.set_np_cover(Default::default());
if t.cover.is_empty() {
return;
}
let px = c.px();
let w = c.ui.clone();
let uri = t.uri.clone();
let c2 = c.clone();
c.images.load(&t.cover, ((600.0 * px) as u32, (600.0 * px) as u32), move |img| {
if c2.state.borrow().np.track.as_ref().is_some_and(|x| x.uri == uri) {
if let Some(ui) = w.upgrade() {
ui.set_np_cover(img);
}
}
});
}
fn load_lyrics(c: &Controller) {
let id = {
let mut st = c.state.borrow_mut();
let Some(t) = st.np.track.clone() else { return };
if t.episode || st.np.lyrics.as_ref().is_some_and(|l| l.0 == t.id) || st.np.lyrics_loading {
return;
}
st.np.lyrics_loading = true;
t.id
};
sync(c);
let engine = c.engine.clone();
let c2 = c.clone();
let id2 = id.clone();
task::spawn(
move || engine.lyrics(&id2),
move |r| {
{
let mut st = c2.state.borrow_mut();
st.np.lyrics_loading = false;
let (lines, synced) = r.unwrap_or_else(|e| {
log::info!("lyrics: {e:#}");
(Vec::new(), false)
});
st.np.lyrics = Some((id, lines, synced));
}
// The track may have changed meanwhile.
let again = {
let st = c2.state.borrow();
st.np.panel == Panel::Lyrics && st.np.track.as_ref().is_some_and(|t| st.np.lyrics.as_ref().is_none_or(|l| l.0 != t.id))
};
if again {
load_lyrics(&c2);
}
sync(&c2);
},
);
}
fn load_queue(c: &Controller) {
let api = c.api();
let c2 = c.clone();
task::spawn(
move || api.queue(),
move |r| {
match r {
Ok(q) => c2.state.borrow_mut().np.queue = q,
Err(e) => log::info!("queue: {e:#}"),
}
sync_queue(&c2);
},
);
}
fn sync_queue(c: &Controller) {
let Some(ui) = c.ui() else { return };
let queue = c.state.borrow().np.queue.clone();
let model = Rc::new(VecModel::from(
queue
.iter()
.take(30)
.map(|t| QueueItem { title: t.name.clone().into(), artist: t.artist_names().into(), image: Default::default() })
.collect::<Vec<_>>(),
));
ui.set_np_queue(ModelRc::from(model.clone()));
let px = c.px();
for (i, t) in queue.iter().take(12).enumerate() {
let url = t.image(64);
if url.is_empty() {
continue;
}
let m = model.clone();
c.images.load(&url, ((64.0 * px) as u32, (64.0 * px) as u32), move |img| {
if let Some(mut row) = m.row_data(i) {
row.image = img;
m.set_row_data(i, row);
}
});
}
}
/// Shows the screen.
pub fn open(c: &Controller) {
{
let mut st = c.state.borrow_mut();
if st.screen == "nowplaying" {
return;
}
st.np.area = 0;
st.np.focus = PLAY;
}
let track = c.state.borrow().np.track.clone();
match &track {
Some(t) => c.backdrop(&t.cover, Look::Soft, &format!("np:{}", t.uri)),
None => c.clear_backdrop(),
}
c.show("nowplaying");
sync(c);
let panel = c.state.borrow().np.panel;
match panel {
Panel::Lyrics => load_lyrics(c),
Panel::Queue => load_queue(c),
Panel::None => {}
}
let k = c.clone();
c.np_timer.start(slint::TimerMode::Repeated, Duration::from_millis(250), move || {
if k.state.borrow().screen == "nowplaying" {
sync_time(&k);
} else {
k.np_timer.stop();
}
});
}
fn close(c: &Controller) {
c.np_timer.stop();
c.back_to_pages();
}
pub fn key(c: &Controller, a: Action, repeat: bool) {
enum Then {
Sync,
Press(usize),
Seek(i64),
Close,
Toggle,
Nothing,
}
let then = {
let mut st = c.state.borrow_mut();
let np = &mut st.np;
match (np.area, a) {
(_, Action::PlayPause) => Then::Toggle,
(_, Action::Back) if np.area == 1 => {
np.area = 0;
Then::Sync
}
(_, Action::Back) => Then::Close,
(0, Action::Left) => {
np.focus = np.focus.saturating_sub(1);
Then::Sync
}
(0, Action::Right) => {
np.focus = (np.focus + 1).min(BUTTONS.len() - 1);
Then::Sync
}
(0, Action::Up) if np.track.as_ref().is_some_and(|t| t.duration_ms > 0) => {
np.area = 1;
Then::Sync
}
(0, Action::Ok) => Then::Press(np.focus),
(1, Action::Left) => Then::Seek(if repeat { -30_000 } else { -10_000 }),
(1, Action::Right) => Then::Seek(if repeat { 30_000 } else { 10_000 }),
(1, Action::Down) | (1, Action::Ok) => {
np.area = 0;
Then::Sync
}
_ => Then::Nothing,
}
};
match then {
Then::Nothing => {}
Then::Sync => sync(c),
Then::Close => close(c),
Then::Toggle => c.engine.send(Cmd::PlayPause),
Then::Seek(d) => {
let target = {
let mut st = c.state.borrow_mut();
let dur = st.np.track.as_ref().map(|t| t.duration_ms).unwrap_or(0);
let t = (st.np.position() as i64 + d).clamp(0, dur.saturating_sub(1000) as i64) as u32;
st.np.set_pos(t);
t
};
c.engine.send(Cmd::Seek(target));
sync_time(c);
}
Then::Press(i) => press(c, BUTTONS[i]),
}
}
fn press(c: &Controller, button: &str) {
let (shuffle, repeat, liked, track, panel) = {
let st = c.state.borrow();
(st.np.shuffle, st.np.repeat, st.np.liked, st.np.track.clone(), st.np.panel)
};
match button {
"play" => c.engine.send(if c.state.borrow().np.playing { Cmd::Pause } else { Cmd::Play }),
"prev" => c.engine.send(Cmd::Prev),
"next" => c.engine.send(Cmd::Next),
"shuffle" => {
c.state.borrow_mut().np.shuffle = !shuffle;
c.engine.send(Cmd::Shuffle(!shuffle));
c.toast(if shuffle { "Keverés kikapcsolva" } else { "Keverés bekapcsolva" }, false);
}
"repeat" => {
// off -> the list -> this track -> off
let next = match repeat {
(false, false) => (true, false),
(true, false) => (true, true),
_ => (false, false),
};
c.state.borrow_mut().np.repeat = next;
c.engine.send(Cmd::Repeat(next.0, next.1));
c.toast(
match next {
(true, false) => "Ismétlés: a lista",
(true, true) => "Ismétlés: ez a szám",
_ => "Ismétlés kikapcsolva",
},
false,
);
}
"like" => {
let Some(t) = track.filter(|t| !t.episode && !t.id.is_empty()) else { return };
let on = !liked.unwrap_or(false);
let api = c.api();
let c2 = c.clone();
let id = t.id.clone();
task::spawn(
move || api.set_liked(&id, on),
move |r| match r {
Ok(()) => {
c2.state.borrow_mut().np.liked = Some(on);
c2.toast(if on { "Hozzáadva a Kedvelt dalokhoz" } else { "Eltávolítva a Kedvelt dalok közül" }, false);
sync(&c2);
}
Err(e) => c2.toast(&api::describe(&e), true),
},
);
}
"lyrics" => {
let next = if panel == Panel::Lyrics { Panel::None } else { Panel::Lyrics };
c.state.borrow_mut().np.panel = next;
if next == Panel::Lyrics {
load_lyrics(c);
}
}
"queue" => {
let next = if panel == Panel::Queue { Panel::None } else { Panel::Queue };
c.state.borrow_mut().np.panel = next;
if next == Panel::Queue {
load_queue(c);
}
}
_ => {}
}
sync(c);
}
/// Everything but the time to Slint.
pub fn sync(c: &Controller) {
let Some(ui) = c.ui() else { return };
{
let st = c.state.borrow();
let np = &st.np;
match &np.track {
Some(t) => {
ui.set_np_title(t.name.clone().into());
ui.set_np_artist(t.artist_names().into());
ui.set_np_album(if t.episode { "Podcast".into() } else { t.album.clone().into() });
ui.set_np_explicit(t.explicit);
ui.set_np_episode(t.episode);
}
None => {
ui.set_np_title("Most nem szól semmi".into());
ui.set_np_artist("Indíts el egy számot, vagy válaszd ki ezt a TV-t a telefonod Spotify appjában.".into());
ui.set_np_album("".into());
}
}
ui.set_np_playing(np.playing);
ui.set_np_loading(np.loading);
ui.set_np_shuffle(np.shuffle);
ui.set_np_repeat(match np.repeat {
(_, true) => 2,
(true, false) => 1,
_ => 0,
});
ui.set_np_liked(match np.liked {
Some(true) => 1,
Some(false) => 0,
None => -1,
});
ui.set_np_focus(np.focus as i32);
ui.set_np_area(np.area as i32);
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());
// Lyrics.
let (lines, note) = match (&np.lyrics, &np.track) {
(_, Some(t)) if t.episode => (Vec::new(), "Podcastokhoz nincs dalszöveg."),
(Some((id, lines, _)), Some(t)) if *id == t.id && !lines.is_empty() => (lines.iter().map(|l| l.1.clone().into()).collect(), ""),
(Some((id, _, _)), Some(t)) if *id == t.id => (Vec::new(), "Ehhez a számhoz nincs dalszöveg."),
_ if np.lyrics_loading => (Vec::new(), "Dalszöveg betöltése…"),
_ => (Vec::new(), ""),
};
let n = lines.len();
if ui.get_np_lyrics().row_count() != n || n == 0 {
ui.set_np_lyrics(ModelRc::new(VecModel::from(lines)));
}
ui.set_np_lyrics_note(note.into());
if np.panel == Panel::Queue && np.queue.is_empty() {
ui.set_np_queue_note("A lejátszási sor üres.".into());
} else {
ui.set_np_queue_note("".into());
}
}
sync_time(c);
}
/// The progress and the current lyrics line.
fn sync_time(c: &Controller) {
let Some(ui) = c.ui() else { return };
let st = c.state.borrow();
let np = &st.np;
let pos = np.position();
let dur = np.track.as_ref().map(|t| t.duration_ms).unwrap_or(0);
ui.set_np_progress(if dur > 0 { pos as f32 / dur as f32 } else { 0.0 });
ui.set_np_time(format::clock(pos).into());
ui.set_np_duration(if dur > 0 { format::clock(dur).into() } else { "".into() });
let line = match (&np.lyrics, &np.track) {
(Some((id, lines, true)), Some(t)) if *id == t.id => lines.iter().rposition(|l| l.0 <= pos + 300).map(|i| i as i32).unwrap_or(-1),
_ => -1,
};
ui.set_np_lyric_line(line);
ui.set_np_lyrics_synced(matches!(&np.lyrics, Some((_, _, true))));
}

1020
src/page.rs Normal file

File diff suppressed because it is too large Load Diff

146
src/screens/artist.rs Normal file
View File

@@ -0,0 +1,146 @@
//! An artist: photo, followers, Lejátszás / Keverés / Követés, the popular
//! tracks, then albums, singles and appearances.
use std::any::Any;
use crate::api::{self, Album, Artist, Track};
use crate::app::{Cx, Look, Screen};
use crate::format;
use crate::page::{Ch, Frame, Kind, L, Spec};
use crate::screens::{self, Load, album_card, row_index, track_line};
use crate::spotify::Cmd;
#[derive(Default)]
struct Data {
artist: Artist,
top: Vec<Track>,
albums: Vec<Album>,
singles: Vec<Album>,
appears: Vec<Album>,
}
pub struct ArtistPage {
id: String,
data: Load<Data>,
following: Option<bool>,
started: bool,
}
impl ArtistPage {
pub fn new(id: &str) -> ArtistPage {
ArtistPage { id: id.into(), data: Load::Loading, following: None, started: false }
}
fn load(&mut self, cx: &Cx) {
let api = cx.api();
let id = self.id.clone();
let market = cx.user().country;
cx.spawn::<ArtistPage, _>(
move || -> anyhow::Result<(Data, Option<bool>)> {
let artist = api.artist(&id)?;
let (top, albums, singles, appears, following) = std::thread::scope(|s| {
let top = s.spawn(|| api.artist_top(&id, &market).unwrap_or_default());
let albums = s.spawn(|| api.artist_albums(&id, "album").unwrap_or_default());
let singles = s.spawn(|| api.artist_albums(&id, "single").unwrap_or_default());
let appears = s.spawn(|| api.artist_albums(&id, "appears_on,compilation").unwrap_or_default());
let following = s.spawn(|| api.following_artist(&id).ok());
(top.join().unwrap_or_default(), albums.join().unwrap_or_default(), singles.join().unwrap_or_default(), appears.join().unwrap_or_default(), following.join().ok().flatten())
});
Ok((Data { artist, top, albums, singles, appears }, following))
},
|s, cx, r| match r {
Ok((d, following)) => {
s.following = following;
let img = api::pick(&d.artist.images, 960);
cx.backdrop(&img, Look::Sharp, &format!("ar:{}", s.id));
s.data = Load::Ready(d);
}
Err(e) => s.data = Load::Failed(api::describe(&e)),
},
);
}
}
impl Screen for ArtistPage {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let frame = Frame::default();
let Some(d) = self.data.ready() else {
return Spec { lines: vec![self.data.status("status").unwrap()], frame };
};
let a = &d.artist;
let mut hero = L::new("hero", Kind::Hero).cover(api::pick(&a.images, 400), true);
hero.style = "ELŐADÓ".into();
hero.title = a.name.clone();
hero.subtitle = a.followers.as_ref().map(|f| format::followers(f.total)).unwrap_or_default();
hero.meta = a.genres.iter().take(4).cloned().collect::<Vec<_>>().join(" · ");
let mut chips = vec![Ch::new("play", "Lejátszás").icon("play").tone("primary"), Ch::new("shuffle", "Keverés").icon("shuffle")];
if let Some(f) = self.following {
chips.push(if f { Ch::new("follow", "Követed").icon("check").active(true) } else { Ch::new("follow", "Követés").icon("plus") });
}
hero.chips = chips;
let mut lines = vec![hero];
let playing = cx.playing_uri();
if !d.top.is_empty() {
lines.push(L::heading("top-h", "Népszerű"));
for (i, t) in d.top.iter().take(10).enumerate() {
lines.push(track_line(format!("trk#{i}"), t, None, true, &playing));
}
}
for (id, title, list) in [("albums", "Albumok", &d.albums), ("singles", "Kislemezek és EP-k", &d.singles), ("appears", "Közreműködések", &d.appears)] {
if !list.is_empty() {
lines.push(L::cards(id, title, "square", list.iter().map(album_card).collect()).captions());
}
}
Spec { lines, frame }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
let Some(d) = self.data.ready() else { return };
let uri = d.artist.uri.clone();
if line == "hero" {
match item {
"play" | "shuffle" => cx.play(Cmd::Context { uri, start: None, shuffle: item == "shuffle" }),
"follow" => {
let Some(on) = self.following.map(|f| !f) else { return };
let api = cx.api();
let id = self.id.clone();
cx.call::<ArtistPage>("follow", move || api.set_following_artist(&id, on), move |s, cx, ok| {
if ok {
s.following = Some(on);
cx.toast(if on { "Követed" } else { "Már nem követed" });
}
});
}
_ => {}
}
return;
}
if line.starts_with("trk#") {
let Some(i) = row_index(line) else { return };
let top: Vec<Track> = d.top.iter().take(10).cloned().collect();
if item == "more" {
if let Some(t) = top.get(i) {
screens::track_menu(cx, t);
}
} else {
screens::play_from(cx, &uri, &top, i);
}
return;
}
screens::open_card(cx, item);
}
fn shown(&mut self, cx: &Cx) {
if let Some(d) = self.data.ready() {
cx.backdrop(&api::pick(&d.artist.images, 960), Look::Sharp, &format!("ar:{}", self.id));
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

343
src/screens/collection.rs Normal file
View File

@@ -0,0 +1,343 @@
//! A list of tracks with a header: a playlist, an album, the liked songs or a
//! podcast's episodes. Lejátszás / Keverés / Mentés, then the rows; long
//! lists load page by page while the focus moves down.
use std::any::Any;
use crate::api::{self, Api, Paging, Track};
use crate::app::{Cx, Look, Screen};
use crate::format;
use crate::page::{Ch, Frame, Kind, L, Spec};
use crate::screens::{self, Load, row_index, track_line};
use crate::spotify::Cmd;
#[derive(Debug, Clone, PartialEq, Eq)]
enum What {
Playlist(String),
Album(String),
Liked,
Show(String),
}
#[derive(Debug, Clone, Default)]
struct Head {
label: String,
title: String,
subtitle: String,
meta: String,
text: String,
cover: String,
uri: String,
/// Your own playlist (no follow button).
own: bool,
}
pub struct Collection {
what: What,
head: Load<Head>,
tracks: Vec<Track>,
next: Option<u32>,
loading_more: bool,
/// Saved / followed (None: unknown or not applicable).
saved: Option<bool>,
started: bool,
}
impl Collection {
fn new(what: What) -> Collection {
Collection { what, head: Load::Loading, tracks: Vec::new(), next: Some(0), loading_more: false, saved: None, started: false }
}
pub fn playlist(id: &str) -> Collection {
Collection::new(What::Playlist(id.into()))
}
pub fn album(id: &str) -> Collection {
Collection::new(What::Album(id.into()))
}
pub fn liked() -> Collection {
Collection::new(What::Liked)
}
pub fn show(id: &str) -> Collection {
Collection::new(What::Show(id.into()))
}
/// What Spotify plays when this page plays.
fn context(&self, cx: &Cx) -> String {
match &self.what {
What::Liked => {
let user = cx.user().id;
if user.is_empty() { String::new() } else { format!("spotify:user:{user}:collection") }
}
_ => self.head.ready().map(|h| h.uri.clone()).unwrap_or_default(),
}
}
fn load(&mut self, cx: &Cx) {
let api = cx.api();
let what = self.what.clone();
let me = cx.user().id;
cx.spawn::<Collection, _>(
move || -> anyhow::Result<(Head, Paging<Track>, Option<bool>)> {
Ok(match &what {
What::Playlist(id) => {
let p = api.playlist(id)?;
let tracks = api.playlist_tracks(id, 0)?;
let own = p.owner.id == me;
let saved = if own || me.is_empty() { None } else { api.following_playlist(id, &me).ok() };
let mut meta = vec![format!("{} dal", p.count())];
if let Some(f) = p.followers.as_ref().filter(|f| f.total > 0) {
meta.push(format::followers(f.total).replace("követő", "kedvelés"));
}
let head = Head {
label: "LEJÁTSZÁSI LISTA".into(),
title: p.name.clone(),
subtitle: p.owner_name(),
meta: meta.join(" · "),
text: format::plain(&p.description),
cover: p.image(400),
uri: p.uri.clone(),
own,
};
(head, tracks, saved)
}
What::Album(id) => {
let a = api.album(id)?;
let mut tracks = a.tracks.clone().unwrap_or_default();
// Album tracks come without the album: add it (art, menus).
let bare = api::Album { tracks: None, ..a.clone() };
for t in tracks.items.iter_mut().flatten() {
t.album = Some(bare.clone());
}
let saved = api.album_saved(id).ok();
let artists = a.artists.iter().map(|x| x.name.as_str()).collect::<Vec<_>>().join(", ");
let length: u64 = tracks.items.iter().flatten().map(|t| t.duration_ms as u64).sum();
let mut meta = vec![format::year(&a.release_date), format!("{} dal", a.total_tracks)];
if !tracks.more() {
meta.push(format::total(length));
}
let head = Head {
label: format::album_type(&a.album_type).to_uppercase(),
title: a.name.clone(),
subtitle: artists,
meta: meta.into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · "),
text: if a.label.is_empty() { String::new() } else { format!("Kiadó: {}", a.label) },
cover: api::pick(&a.images, 400),
uri: a.uri.clone(),
own: false,
};
(head, tracks, saved)
}
What::Liked => {
let tracks = api.liked(0)?;
let head = Head {
label: "LEJÁTSZÁSI LISTA".into(),
title: "Kedvelt dalok".into(),
subtitle: String::new(),
meta: format!("{} dal", tracks.total),
text: "A dalok, amiket a szívvel jelöltél meg.".into(),
cover: String::new(),
uri: String::new(),
own: true,
};
(head, tracks, None)
}
What::Show(id) => {
let s = api.show(id)?;
let mut tracks = api.show_episodes(id, 0)?;
let bare = api::Show { ..s.clone() };
for t in tracks.items.iter_mut().flatten() {
t.show = Some(bare.clone());
t.kind = "episode".into();
}
let saved = api.show_saved(id).ok();
let head = Head {
label: "PODCAST".into(),
title: s.name.clone(),
subtitle: s.publisher.clone(),
meta: format!("{} epizód", s.total_episodes),
text: format::plain(&s.description),
cover: api::pick(&s.images, 400),
uri: s.uri.clone(),
own: false,
};
(head, tracks, saved)
}
})
},
|s, cx, r| match r {
Ok((head, tracks, saved)) => {
s.next = tracks.more().then_some(tracks.offset + tracks.items.len() as u32);
s.tracks = tracks.list();
s.saved = saved;
let cover = head.cover.clone();
s.head = Load::Ready(head);
cx.backdrop(&cover, Look::Soft, &format!("col:{:?}", s.what));
}
Err(e) => s.head = Load::Failed(api::describe(&e)),
},
);
}
fn load_more(&mut self, cx: &Cx) {
let Some(offset) = self.next.filter(|_| !self.loading_more) else { return };
self.loading_more = true;
let api = cx.api();
let what = self.what.clone();
let album = self.tracks.first().and_then(|t| t.album.clone());
let show = self.tracks.first().and_then(|t| t.show.clone());
cx.spawn::<Collection, _>(
move || fetch_page(&api, &what, offset),
move |s, cx, r| {
s.loading_more = false;
match r {
Ok(mut p) => {
s.next = p.more().then_some(p.offset + p.items.len() as u32);
for t in p.items.iter_mut().flatten() {
if t.album.is_none() {
t.album = album.clone();
}
if what_is_show(&s.what) {
t.show = show.clone();
t.kind = "episode".into();
}
}
s.tracks.extend(p.list());
}
Err(e) => {
s.next = None;
cx.error("more", &e);
}
}
},
);
}
fn toggle_saved(&mut self, cx: &Cx) {
let Some(on) = self.saved.map(|s| !s) else { return };
let api = cx.api();
let what = self.what.clone();
cx.call::<Collection>(
"save",
move || match &what {
What::Playlist(id) => api.set_following_playlist(id, on),
What::Album(id) => api.set_album_saved(id, on),
What::Show(id) => api.set_show_saved(id, on),
What::Liked => Ok(()),
},
move |s, cx, ok| {
if ok {
s.saved = Some(on);
cx.toast(if on { "Hozzáadva a könyvtáradhoz" } else { "Eltávolítva a könyvtáradból" });
}
},
);
}
}
fn what_is_show(w: &What) -> bool {
matches!(w, What::Show(_))
}
fn fetch_page(api: &Api, what: &What, offset: u32) -> anyhow::Result<Paging<Track>> {
match what {
What::Playlist(id) => api.playlist_tracks(id, offset),
What::Album(id) => api.album_tracks(id, offset),
What::Liked => api.liked(offset),
What::Show(id) => api.show_episodes(id, offset),
}
}
impl Screen for Collection {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let frame = Frame::default();
let Some(h) = self.head.ready() else {
let lines = vec![self.head.status("status").unwrap()];
return Spec { lines, frame };
};
let mut hero = L::new("hero", Kind::Hero).cover(h.cover.clone(), false);
hero.style = h.label.clone();
hero.title = h.title.clone();
hero.subtitle = h.subtitle.clone();
hero.meta = h.meta.clone();
hero.text = h.text.clone();
if h.cover.is_empty() && self.what == What::Liked {
hero.icon = "liked".into();
}
let mut chips = vec![Ch::new("play", "Lejátszás").icon("play").tone("primary")];
if !matches!(self.what, What::Show(_)) {
chips.push(Ch::new("shuffle", "Keverés").icon("shuffle"));
}
if let Some(saved) = self.saved.filter(|_| !h.own) {
chips.push(if saved { Ch::new("save", "A könyvtáradban").icon("check").active(true) } else { Ch::new("save", "Mentés").icon("plus") });
}
hero.chips = chips;
let mut lines = vec![hero];
if self.tracks.is_empty() {
lines.push(L::notice("empty", "info", "Ez a lista üres", ""));
}
let playing = cx.playing_uri();
let numbered = matches!(self.what, What::Album(_));
let with_album = matches!(self.what, What::Playlist(_) | What::Liked);
for (i, t) in self.tracks.iter().enumerate() {
let n = if numbered { Some(t.track_number.max(i as u32 + 1)) } else { None };
lines.push(track_line(format!("trk#{i}"), t, n, with_album, &playing));
}
if self.next.is_some() {
lines.push(L::text("more", "További dalok betöltése…", "caption"));
}
Spec { lines, frame }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line == "hero" {
let context = self.context(cx);
match item {
"play" | "shuffle" => {
let shuffle = item == "shuffle";
if context.is_empty() {
let uris: Vec<String> = self.tracks.iter().filter(|t| t.playable()).map(|t| t.uri.clone()).collect();
if !uris.is_empty() {
cx.play(Cmd::Tracks { uris, start: 0 });
}
} else {
cx.play(Cmd::Context { uri: context, start: None, shuffle });
}
}
"save" => self.toggle_saved(cx),
_ => {}
}
return;
}
let Some(i) = row_index(line) else { return };
match item {
"more" => {
if let Some(t) = self.tracks.get(i) {
screens::track_menu(cx, t);
}
}
_ => {
let context = self.context(cx);
screens::play_from(cx, &context, &self.tracks, i);
}
}
}
fn more(&mut self, cx: &Cx, list: &str) {
if list == "trk" {
self.load_more(cx);
}
}
fn shown(&mut self, cx: &Cx) {
if let Some(h) = self.head.ready() {
cx.backdrop(&h.cover, Look::Soft, &format!("col:{:?}", self.what));
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

154
src/screens/home.rs Normal file
View File

@@ -0,0 +1,154 @@
//! Kezdőlap: rows: recently played, your playlists (with the
//! liked songs first), your top artists and tracks, saved albums, new
//! releases. Every row loads on its own; a failing one just stays away.
use std::any::Any;
use crate::api::{Album, Artist, Playlist, Played, Track};
use crate::app::{Cx, Look, Screen};
use crate::page::{Frame, L, Spec};
use crate::screens::{self, album_card, artist_card, liked_card, playlist_card, track_card};
#[derive(Default)]
struct Data {
recent: Option<Vec<Played>>,
playlists: Option<Vec<Playlist>>,
liked_total: Option<u32>,
top_artists: Option<Vec<Artist>>,
top_tracks: Option<Vec<Track>>,
albums: Option<Vec<Album>>,
releases: Option<Vec<Album>>,
errors: Vec<String>,
}
pub struct Home {
data: Data,
loading: bool,
started: bool,
}
impl Home {
pub fn new() -> Home {
Home { data: Data::default(), loading: true, started: false }
}
fn load(&mut self, cx: &Cx) {
self.loading = true;
let api = cx.api();
cx.spawn::<Home, _>(
move || {
std::thread::scope(|s| {
let recent = s.spawn(|| api.recently_played());
let playlists = s.spawn(|| api.my_playlists(0));
let liked = s.spawn(|| api.liked(0));
let artists = s.spawn(|| api.top_artists());
let tracks = s.spawn(|| api.top_tracks());
let albums = s.spawn(|| api.saved_albums(0));
let releases = s.spawn(|| api.new_releases());
let mut d = Data::default();
let e = &mut d.errors;
let recent = keep(recent.join(), e);
let playlists = keep(playlists.join(), e).map(|p| p.list());
let liked_total = keep(liked.join(), e).map(|p| p.total);
let top_artists = keep(artists.join(), e);
let top_tracks = keep(tracks.join(), e);
let albums = keep(albums.join(), e).map(|p| p.list());
let releases = keep(releases.join(), e);
Data { recent, playlists, liked_total, top_artists, top_tracks, albums, releases, ..d }
})
},
|s, cx, d| {
s.data = d;
s.loading = false;
// The first picture of the page tints the background.
let first = s.data.recent.as_ref().and_then(|r| r.first()).map(|p| p.track.image(640)).unwrap_or_default();
cx.backdrop(&first, Look::Soft, "home");
},
);
}
}
/// A row's result: the data, or its error noted.
fn keep<T>(r: std::thread::Result<anyhow::Result<T>>, errors: &mut Vec<String>) -> Option<T> {
match r {
Ok(Ok(t)) => Some(t),
Ok(Err(e)) => {
log::warn!("home: {e:#}");
errors.push(crate::api::describe(&e));
None
}
Err(_) => None,
}
}
/// Recently played tracks, each once (newest first).
fn recent_cards(items: &[Played]) -> Vec<crate::page::C> {
let mut seen = std::collections::HashSet::new();
items
.iter()
.filter(|p| seen.insert(p.track.uri.clone()))
.take(20)
.map(|p| track_card(&p.track, p.context.as_ref().map(|c| c.uri.as_str()).unwrap_or("")))
.collect()
}
impl Screen for Home {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx);
}
let frame = Frame { nav: Some(0), ..Frame::default() };
let mut lines = Vec::new();
if self.loading {
lines.push(L::text("loading", "Betöltés…", "caption"));
return Spec { lines, frame };
}
let d = &self.data;
if let Some(r) = d.recent.as_ref().filter(|r| !r.is_empty()) {
lines.push(L::cards("recent", "Legutóbb játszott", "square", recent_cards(r)).captions());
}
let mut pl = vec![liked_card(d.liked_total)];
pl.extend(d.playlists.iter().flatten().map(playlist_card));
lines.push(L::cards("playlists", "Lejátszási listáid", "square", pl).captions());
if let Some(a) = d.top_artists.as_ref().filter(|a| !a.is_empty()) {
lines.push(L::cards("artists", "Kedvenc előadóid", "round", a.iter().map(artist_card).collect()).captions());
}
if let Some(t) = d.top_tracks.as_ref().filter(|t| !t.is_empty()) {
lines.push(L::cards("top", "Mostanában sokat hallgatod", "square", t.iter().map(|t| track_card(t, "")).collect()).captions());
}
if let Some(a) = d.albums.as_ref().filter(|a| !a.is_empty()) {
lines.push(L::cards("albums", "Elmentett albumaid", "square", a.iter().map(album_card).collect()).captions());
}
if let Some(a) = d.releases.as_ref().filter(|a| !a.is_empty()) {
lines.push(L::cards("releases", "Új megjelenések", "square", a.iter().map(album_card).collect()).captions());
}
if d.recent.is_none() && d.playlists.is_none() && d.top_artists.is_none() {
let why = d.errors.first().cloned().unwrap_or_default();
lines.push(L::notice("error", "bad", "Nem sikerült betölteni a kezdőlapot", why));
}
Spec { lines, frame }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line == "top" {
// Top tracks play as a list, from the chosen one.
if let Some(t) = &self.data.top_tracks {
let i = t.iter().position(|x| item == format!("t:{}|", x.uri)).unwrap_or(0);
screens::play_from(cx, "", t, i);
return;
}
}
screens::open_card(cx, item);
}
fn shown(&mut self, cx: &Cx) {
let first = self.data.recent.as_ref().and_then(|r| r.first()).map(|p| p.track.image(640)).unwrap_or_default();
cx.backdrop(&first, Look::Soft, "home");
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

151
src/screens/library.rs Normal file
View File

@@ -0,0 +1,151 @@
//! Könyvtár: playlists (the liked songs first), albums, artists, podcasts,
//! one at a time, as a grid. More loads while the focus moves down.
use std::any::Any;
use crate::api::{Album, Artist, Playlist, Show};
use crate::app::{Cx, Screen};
use crate::page::{C, Ch, Frame, GRID, L, Spec, grid_lines};
use crate::screens::{self, Load, album_card, artist_card, liked_card, playlist_card, show_card};
const TABS: [(&str, &str); 4] = [("playlists", "Lejátszási listák"), ("albums", "Albumok"), ("artists", "Előadók"), ("shows", "Podcastok")];
enum Items {
Playlists(Vec<Playlist>, Option<u32>),
Albums(Vec<Album>),
Artists(Vec<Artist>),
Shows(Vec<Show>),
}
pub struct Library {
tab: usize,
items: Load<Items>,
/// Next page: an offset, or the last artist's id (cursor).
next: Option<String>,
loading_more: bool,
started: bool,
}
impl Library {
pub fn new() -> Library {
Library { tab: 0, items: Load::Loading, next: None, loading_more: false, started: false }
}
fn load(&mut self, cx: &Cx, more: bool) {
if more && (self.loading_more || self.next.is_none()) {
return;
}
let next = if more { self.next.clone().unwrap_or_default() } else { String::new() };
if more {
self.loading_more = true;
} else {
self.items = Load::Loading;
self.next = None;
}
let api = cx.api();
let tab = self.tab;
cx.spawn::<Library, _>(
move || -> anyhow::Result<(Items, Option<String>)> {
let offset: u32 = next.parse().unwrap_or(0);
Ok(match tab {
0 => {
let p = api.my_playlists(offset)?;
let liked = if offset == 0 { api.liked(0).ok().map(|p| p.total) } else { None };
let n = p.more().then(|| (p.offset + p.items.len() as u32).to_string());
(Items::Playlists(p.list(), liked), n)
}
1 => {
let p = api.saved_albums(offset)?;
let n = p.more().then(|| (p.offset + p.items.len() as u32).to_string());
(Items::Albums(p.list()), n)
}
2 => {
let (a, after) = api.followed_artists(&next)?;
(Items::Artists(a), after)
}
_ => {
let p = api.saved_shows(offset)?;
let n = p.more().then(|| (p.offset + p.items.len() as u32).to_string());
(Items::Shows(p.list()), n)
}
})
},
move |s, cx, r| {
if s.tab != tab {
return;
}
s.loading_more = false;
match r {
Ok((items, n)) => {
s.next = n;
match (s.items.ready_mut(), items) {
(Some(Items::Playlists(a, _)), Items::Playlists(b, _)) if more => a.extend(b),
(Some(Items::Albums(a)), Items::Albums(b)) if more => a.extend(b),
(Some(Items::Artists(a)), Items::Artists(b)) if more => a.extend(b),
(Some(Items::Shows(a)), Items::Shows(b)) if more => a.extend(b),
(_, items) => s.items = Load::Ready(items),
}
}
Err(e) if more => {
s.next = None;
cx.error("library", &e);
}
Err(e) => s.items = Load::Failed(crate::api::describe(&e)),
}
},
);
}
}
impl Screen for Library {
fn spec(&mut self, cx: &Cx) -> Spec {
if !self.started {
self.started = true;
self.load(cx, false);
}
let tabs = TABS.iter().enumerate().map(|(i, (id, t))| Ch::new(*id, *t).active(i == self.tab)).collect();
let mut lines = vec![L::page_title("title", "Könyvtár", ""), L::chips("tabs", "", tabs)];
if let Some(st) = self.items.status("status") {
lines.push(st);
} else {
let (cards, style, empty): (Vec<C>, &str, &str) = match self.items.ready().unwrap() {
Items::Playlists(p, liked) => {
let mut c = vec![liked_card(*liked)];
c.extend(p.iter().map(playlist_card));
(c, "square", "")
}
Items::Albums(a) => (a.iter().map(album_card).collect(), "square", "Még nincs elmentett albumod."),
Items::Artists(a) => (a.iter().map(artist_card).collect(), "round", "Még nem követsz előadót."),
Items::Shows(s) => (s.iter().map(show_card).collect(), "square", "Még nem követsz podcastot."),
};
if cards.is_empty() {
lines.push(L::notice("empty", "info", empty, "A telefonos Spotify appban mentett dolgok itt is megjelennek."));
}
lines.extend(grid_lines("grid", "", style, cards, GRID));
}
Spec { lines, frame: Frame { nav: Some(2), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line == "tabs" {
if let Some(i) = TABS.iter().position(|t| t.0 == item) {
if i != self.tab {
self.tab = i;
self.load(cx, false);
}
}
return;
}
screens::open_card(cx, item);
}
fn more(&mut self, cx: &Cx, list: &str) {
if list == "grid" {
self.load(cx, true);
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

283
src/screens/mod.rs Normal file
View File

@@ -0,0 +1,283 @@
//! The browsing screens. Each one describes its page as lines (src/page.rs)
//! and reacts to OK; see app::Screen.
//!
//! Card ids say what a card opens: "al:<id>" album, "pl:<id>" playlist,
//! "ar:<id>" artist, "sh:<id>" podcast, "liked" the liked songs,
//! "t:<track uri>|<context uri>" plays a track (in its context, if any).
pub mod artist;
pub mod collection;
pub mod home;
pub mod library;
pub mod search;
pub mod settings;
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::task;
/// The screen of a top navigation section.
pub fn section(n: usize) -> Box<dyn Screen> {
match n {
1 => Box::new(search::Search::new()),
2 => Box::new(library::Library::new()),
3 => Box::new(settings::Settings::new()),
_ => Box::new(home::Home::new()),
}
}
/// Data that loads.
#[derive(Debug, Clone, Default)]
pub enum Load<T> {
#[default]
Loading,
Ready(T),
Failed(String),
}
impl<T> Load<T> {
pub fn ready(&self) -> Option<&T> {
match self {
Load::Ready(t) => Some(t),
_ => None,
}
}
pub fn ready_mut(&mut self) -> Option<&mut T> {
match self {
Load::Ready(t) => Some(t),
_ => None,
}
}
pub fn from(r: anyhow::Result<T>) -> Load<T> {
match r {
Ok(t) => Load::Ready(t),
Err(e) => Load::Failed(api::describe(&e)),
}
}
/// The loading / error line, or None when ready.
pub fn status(&self, id: &str) -> Option<L> {
match self {
Load::Loading => Some(L::text(id, "Betöltés…", "caption")),
Load::Failed(e) => Some(L::notice(id, "bad", "Nem sikerült betölteni", e.clone())),
Load::Ready(_) => None,
}
}
}
/// Picture size asked for cards (design px; Spotify's 300 px images fit).
const CARD_IMG: u32 = CARD as u32 + 60;
pub fn album_card(a: &Album) -> C {
let mut c = C::new(format!("al:{}", a.id), a.name.clone(), api::pick(&a.images, CARD_IMG));
c.caption = a.name.clone();
let artists = a.artists.iter().map(|x| x.name.as_str()).collect::<Vec<_>>().join(", ");
let y = format::year(&a.release_date);
c.detail = [y, artists].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
c
}
pub fn playlist_card(p: &Playlist) -> C {
let mut c = C::new(format!("pl:{}", p.id), p.name.clone(), p.image(CARD_IMG));
c.caption = p.name.clone();
c.detail = format!("Lejátszási lista · {}", p.owner_name());
c
}
pub fn artist_card(a: &Artist) -> C {
let mut c = C::new(format!("ar:{}", a.id), a.name.clone(), api::pick(&a.images, CARD_IMG));
c.caption = a.name.clone();
c.detail = "Előadó".into();
c
}
pub fn show_card(s: &Show) -> C {
let mut c = C::new(format!("sh:{}", s.id), s.name.clone(), api::pick(&s.images, CARD_IMG));
c.caption = s.name.clone();
c.detail = if s.publisher.is_empty() { "Podcast".into() } else { s.publisher.clone() };
c
}
/// A track as a card (album art): plays it, in `context` if given.
pub fn track_card(t: &Track, context: &str) -> C {
let mut c = C::new(format!("t:{}|{context}", t.uri), t.name.clone(), t.image(CARD_IMG));
c.caption = t.name.clone();
c.detail = t.artist_names();
c
}
pub fn liked_card(total: Option<u32>) -> C {
let mut c = C::new("liked", "Kedvelt dalok", "");
c.caption = "Kedvelt dalok".into();
c.mark = "liked";
c.detail = match total {
Some(n) => format!("Lejátszási lista · {n} dal"),
None => "Lejátszási lista".into(),
};
c
}
/// A track row. `number`: the album's track number, else the art shows.
pub fn track_line(id: String, t: &Track, number: Option<u32>, with_album: bool, playing: &str) -> L {
let meta = if t.kind == "episode" {
let mut p = vec![format::date(&t.release_date)];
if let Some(r) = &t.resume_point {
if r.fully_played {
p.push("Meghallgatva".into());
} else if r.resume_position_ms > 0 {
p.push(format!("Még {}", format::clock(t.duration_ms.saturating_sub(r.resume_position_ms))));
}
}
p.join(" · ")
} else {
let mut m = t.artist_names();
if with_album {
if let Some(a) = &t.album {
m = format!("{m} · {}", a.name);
}
}
if t.explicit {
m = format!("E · {m}");
}
m
};
let mut l = L::track(id, t.name.clone(), meta, format::clock(t.duration_ms));
match number {
Some(n) => l.note = n.to_string(),
None => l.image = t.image(64),
}
if !playing.is_empty() && t.uri == playing {
l.tone = "playing".into();
}
if !t.playable() {
l.tone = "dim".into();
}
l
}
/// The index in a "<list>#<i>" line id.
pub fn row_index(line: &str) -> Option<usize> {
line.rsplit_once('#')?.1.parse().ok()
}
/// Plays `t` from a list: in `context` if given, else the list's tracks.
pub fn play_from(cx: &Cx, context: &str, tracks: &[Track], i: usize) {
let Some(t) = tracks.get(i) else { return };
if !t.playable() {
cx.toast("Ez a szám nem játszható le.");
return;
}
let shuffle = cx.c.state.borrow().np.shuffle;
if context.is_empty() {
let uris: Vec<String> = tracks.iter().filter(|t| t.playable()).map(|t| t.uri.clone()).collect();
let start = uris.iter().position(|u| *u == t.uri).unwrap_or(0) as u32;
cx.play(Cmd::Tracks { uris, start });
} else {
cx.play(Cmd::Context { uri: context.to_string(), start: Some(Start::Uri(t.uri.clone())), shuffle });
}
}
/// Opens the page of a card id (see the module docs); true if it was one.
pub fn open_card(cx: &Cx, key: &str) -> bool {
if key == "liked" {
cx.push(Box::new(collection::Collection::liked()));
} else if let Some(id) = key.strip_prefix("al:") {
cx.push(Box::new(collection::Collection::album(id)));
} else if let Some(id) = key.strip_prefix("pl:") {
cx.push(Box::new(collection::Collection::playlist(id)));
} else if let Some(id) = key.strip_prefix("sh:") {
cx.push(Box::new(collection::Collection::show(id)));
} 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 });
}
} else {
return false;
}
true
}
/// The "+" of a track row: queue, like, album, artist.
pub fn track_menu(cx: &Cx, t: &Track) {
let c = cx.c.clone();
let t = t.clone();
let api = cx.api();
let id = t.id.clone();
let episode = t.kind == "episode";
task::spawn(
move || if episode || id.is_empty() { None } else { api.liked_contains(&[id]).ok().and_then(|v| v.first().copied()) },
move |liked| open_track_menu(&c, t, liked),
);
}
fn open_track_menu(c: &Controller, t: Track, liked: Option<bool>) {
let mut items: Vec<(String, String, bool)> = vec![("Hozzáadás a lejátszási sorhoz".into(), String::new(), false)];
let mut actions: Vec<&str> = vec!["queue"];
if let Some(l) = liked {
items.push((if l { "Eltávolítás a Kedvelt dalok közül" } else { "Hozzáadás a Kedvelt dalokhoz" }.into(), String::new(), false));
actions.push(if l { "unlike" } else { "like" });
}
if let Some(a) = t.album.as_ref().filter(|a| !a.id.is_empty()) {
items.push(("Album megnyitása".into(), a.name.clone(), false));
actions.push("album");
}
for a in t.artists.iter().filter(|a| !a.id.is_empty()).take(3) {
items.push(("Előadó megnyitása".into(), a.name.clone(), false));
actions.push("artist");
}
if let Some(s) = t.show.as_ref().filter(|s| !s.id.is_empty()) {
items.push(("Podcast megnyitása".into(), s.name.clone(), false));
actions.push("show");
}
let title = t.name.clone();
c.open_select(
&title,
items,
Box::new(move |c: &Controller, i: usize| {
let api = c.api();
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),
},
);
}
Some(a @ ("like" | "unlike")) => {
let on = a == "like";
let id = t.id.clone();
task::spawn(
move || api.set_liked(&id, on),
move |r| match r {
Ok(()) => c2.toast(if on { "Hozzáadva a Kedvelt dalokhoz" } else { "Eltávolítva a Kedvelt dalok közül" }, false),
Err(e) => c2.toast(&api::describe(&e), true),
},
);
}
Some("album") => c.push_screen(Box::new(collection::Collection::album(&t.album.as_ref().unwrap().id))),
Some("artist") => {
// Which artist: the n-th artist entry of the menu.
let first = actions.iter().position(|a| *a == "artist").unwrap_or(i);
if let Some(a) = t.artists.iter().filter(|a| !a.id.is_empty()).nth(i - first) {
c.push_screen(Box::new(artist::ArtistPage::new(&a.id)));
}
}
Some("show") => c.push_screen(Box::new(collection::Collection::show(&t.show.as_ref().unwrap().id))),
_ => {}
}
}),
);
}

101
src/screens/search.rs Normal file
View File

@@ -0,0 +1,101 @@
//! Keresés: the on-screen keyboard, then songs (rows), artists, albums,
//! playlists and podcasts (cards).
use std::any::Any;
use crate::api::SearchResult;
use crate::app::{Cx, Screen};
use crate::page::{Frame, Kind, L, Spec};
use crate::screens::{self, Load, album_card, artist_card, playlist_card, row_index, show_card, track_line};
pub struct Search {
searched: String,
result: Option<Load<SearchResult>>,
}
impl Search {
pub fn new() -> Search {
Search { searched: String::new(), result: None }
}
}
impl Screen for Search {
fn spec(&mut self, cx: &Cx) -> Spec {
let mut lines = vec![L::page_title("title", "Mit hallgatnál?", "Dalok, előadók, albumok, lejátszási listák és podcastok."), L::new("kb", Kind::Keyboard)];
match &self.result {
None => lines.push(L::notice("hint", "info", "Kezdj el gépelni", "Két betű elég.")),
Some(Load::Loading) => lines.push(L::text("loading", "Keresés…", "caption")),
Some(Load::Failed(e)) => lines.push(L::notice("error", "bad", "Nem sikerült keresni", e.clone())),
Some(Load::Ready(r)) if r.tracks.is_empty() && r.artists.is_empty() && r.albums.is_empty() && r.playlists.is_empty() && r.shows.is_empty() => {
lines.push(L::notice("none", "info", "Erre nincs találat", "Próbáld másképp írni."))
}
Some(Load::Ready(r)) => {
let playing = cx.playing_uri();
if !r.tracks.is_empty() {
lines.push(L::heading("songs", "Dalok"));
for (i, t) in r.tracks.iter().take(6).enumerate() {
lines.push(track_line(format!("trk#{i}"), t, None, true, &playing));
}
}
if !r.artists.is_empty() {
lines.push(L::cards("artists", "Előadók", "round", r.artists.iter().map(artist_card).collect()).captions());
}
if !r.albums.is_empty() {
lines.push(L::cards("albums", "Albumok", "square", r.albums.iter().map(album_card).collect()).captions());
}
if !r.playlists.is_empty() {
lines.push(L::cards("playlists", "Lejátszási listák", "square", r.playlists.iter().map(playlist_card).collect()).captions());
}
if !r.shows.is_empty() {
lines.push(L::cards("shows", "Podcastok", "square", r.shows.iter().map(show_card).collect()).captions());
}
}
}
Spec { lines, frame: Frame { nav: Some(1), keyboard: Some("Előadó, dal vagy podcast".into()), ..Frame::default() } }
}
fn query(&mut self, cx: &Cx, text: &str, _submit: bool) {
let q = text.trim().to_string();
if q.chars().count() < 2 {
self.result = None;
self.searched.clear();
cx.refresh();
return;
}
if q == self.searched {
return;
}
self.searched = q.clone();
self.result = Some(Load::Loading);
let api = cx.api();
cx.spawn::<Search, _>(move || (api.search(&q), q), |s, _cx, (r, q)| {
if s.searched == q {
s.result = Some(Load::from(r));
}
});
cx.refresh();
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
if line.starts_with("trk#") {
let Some(Load::Ready(r)) = &self.result else { return };
let Some(i) = row_index(line) else { return };
let tracks: Vec<_> = r.tracks.iter().take(6).cloned().collect();
if item == "more" {
if let Some(t) = tracks.get(i) {
screens::track_menu(cx, t);
}
} else if let Some(t) = tracks.get(i) {
// A found song plays in its album.
let context = t.album.as_ref().map(|a| a.uri.clone()).unwrap_or_default();
screens::play_from(cx, &context, &tracks, i);
}
return;
}
screens::open_card(cx, item);
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

96
src/screens/settings.rs Normal file
View File

@@ -0,0 +1,96 @@
//! Beállítások: the account (sign out), the Connect name, sound quality,
//! loudness normalisation, autoplay, the look.
use std::any::Any;
use crate::app::{Cx, Input, Screen};
use crate::page::{Ch, Frame, L, Spec};
pub struct Settings;
impl Settings {
pub fn new() -> Settings {
Settings
}
}
const RESTART: &str = "Az app következő indításakor lép életbe.";
impl Screen for Settings {
fn spec(&mut self, cx: &Cx) -> Spec {
let cfg = cx.cfg();
let user = cx.user();
let mut lines = vec![L::page_title("title", "Beállítások", "")];
lines.push(L::heading("acc-h", "Fiók"));
let plan = match user.product.as_str() {
"premium" => "Premium",
"" => "",
_ => "Ingyenes fiók: a lejátszáshoz Premium kell",
};
let meta = [plan.to_string(), user.country.clone()].into_iter().filter(|s| !s.is_empty()).collect::<Vec<_>>().join(" · ");
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("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"));
Spec { lines, frame: Frame { nav: Some(3), ..Frame::default() } }
}
fn activate(&mut self, cx: &Cx, line: &str, item: &str) {
match line {
"account" => cx.select::<Settings>(
"Kijelentkezel?",
vec![("Kijelentkezés".into(), String::new(), false), ("Mégse".into(), String::new(), true)],
|_, cx, i| {
if i == 0 {
cx.c.sign_out();
}
},
),
"name" => {
let cur = cx.cfg().device_name;
cx.input::<Settings>(
Input { title: "A TV neve".into(), subtitle: "Ezen a néven látod a telefon Spotify appjában".into(), placeholder: "Fennec TV".into(), value: cur, submit: "Mentés".into(), min: 1 },
|_, cx, text| {
let t = text.trim().to_string();
if !t.is_empty() {
cx.set_cfg(|c| c.device_name = t);
cx.toast(RESTART);
}
},
);
}
"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"),
"glass" => {
cx.set_cfg(|c| c.glass = item.to_string());
crate::config::apply_look(&cx.c.glass, item);
}
_ => {}
}
}
fn as_any(&mut self) -> &mut dyn Any {
self
}
}

690
src/spotify.rs Normal file
View File

@@ -0,0 +1,690 @@
//! 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.
//!
//! 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.
//!
//! 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.
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::{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 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";
/// The track (or episode) that plays.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Track {
pub uri: String,
/// Base62 id.
pub id: String,
pub name: String,
pub artists: Vec<(String, String)>,
pub album: String,
pub cover: String,
pub duration_ms: u32,
pub episode: bool,
pub explicit: bool,
}
impl Track {
pub fn artist_names(&self) -> String {
self.artists.iter().map(|a| a.1.as_str()).collect::<Vec<_>>().join(", ")
}
}
#[derive(Debug, Clone, PartialEq)]
pub enum Status {
/// No credentials: waiting for a phone (device name).
SignIn(String),
Connecting,
/// Signed in (user name).
Ready(String),
Failed(String),
}
/// A pairing code for spotify.com/pair.
#[derive(Debug, Clone, PartialEq)]
pub struct Pair {
pub code: String,
/// Opens the pairing page with the code filled in (the QR code).
pub url: String,
}
#[derive(Debug, Clone)]
pub enum Event {
Status(Status),
/// A new pairing code (None: none could be had, e.g. no network).
Pair(Option<Pair>),
Track(Track),
Loading,
Playing(u32),
Paused(u32),
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),
}
pub enum Cmd {
/// Plays `context` (an album, playlist, artist, show, "spotify:user:<u>:collection"),
/// from track `start` (a uri) or index, optionally shuffled.
Context { uri: String, start: Option<Start>, shuffle: bool },
/// Plays a list of track uris from index `start`.
Tracks { uris: Vec<String>, start: u32 },
PlayPause,
Play,
Pause,
Next,
Prev,
Seek(u32),
Shuffle(bool),
/// (context, track)
Repeat(bool, bool),
SignOut,
/// The app closes: leave Spotify Connect cleanly.
Quit,
}
#[derive(Debug, Clone)]
pub enum Start {
Uri(String),
}
/// Cheap to clone; usable from any thread.
#[derive(Clone)]
pub struct Engine {
rt: Arc<tokio::runtime::Runtime>,
cmd: mpsc::UnboundedSender<Cmd>,
session: Arc<Mutex<Option<Session>>>,
/// Mock mode (UI work without an account): no librespot at all.
mock: bool,
/// Set when the engine's loop has ended (after `Cmd::Quit`).
stopped: Arc<std::sync::atomic::AtomicBool>,
}
fn cache_dir() -> PathBuf {
crate::config::home().join(".cache").join("spotify-tv")
}
impl Engine {
/// Starts the engine; `events` is called on a runtime thread.
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 session = Arc::new(Mutex::new(None));
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 events: Arc<dyn Fn(Event) + Send + Sync> = Arc::new(events);
let cfg = cfg.clone();
rt.spawn(async move {
if mock {
mock_loop(rx, events).await;
} else {
run(cfg, rx, session, events).await;
}
stopped.store(true, std::sync::atomic::Ordering::SeqCst);
});
// The TV closes background apps with SIGTERM: leave like Back does.
#[cfg(unix)]
rt.spawn(async {
if let Ok(mut term) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
term.recv().await;
log::info!("SIGTERM");
let _ = slint::invoke_from_event_loop(|| {
let _ = slint::quit_event_loop();
});
}
});
engine
}
/// Leaves Spotify Connect (the phone sees the TV go), waiting at most
/// `limit` for it.
pub fn shutdown(&self, limit: Duration) {
self.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);
}
fn session(&self) -> anyhow::Result<Session> {
self.session.lock().unwrap().clone().filter(|s| !s.is_invalid()).ok_or_else(|| anyhow::anyhow!("Nincs kapcsolat a Spotifyjal"))
}
/// A Web API access token (blocking; call it off the UI thread).
pub fn token(&self) -> anyhow::Result<String> {
if self.mock {
return Ok("mock".into());
}
let s = self.session()?;
let t = self.rt.block_on(async move { tokio::time::timeout(Duration::from_secs(15), s.token_provider().get_token(SCOPES)).await });
match t {
Ok(Ok(t)) => Ok(t.access_token),
Ok(Err(e)) => Err(anyhow::anyhow!("token: {e}")),
Err(_) => Err(anyhow::anyhow!("A Spotify nem válaszolt")),
}
}
/// Lyrics of a track: (start ms, line), and whether they are synced.
pub fn lyrics(&self, track_id: &str) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
if self.mock {
let lines = ["Ez itt egy dal szövege", "A második sor jön utána", "Aztán a refrén, hangosan", "És még egyszer, halkabban", "", "Vége a versszaknak"];
return Ok((lines.iter().enumerate().map(|(i, l)| (i as u32 * 4000, l.to_string())).collect(), true));
}
let s = self.session()?;
let id = SpotifyId::from_base62(track_id).map_err(|e| anyhow::anyhow!("{e}"))?;
let body = self.rt.block_on(async move { s.spclient().get_lyrics(&id).await }).map_err(|e| anyhow::anyhow!("{e}"))?;
parse_lyrics(&body)
}
}
/// Spotify's color-lyrics JSON -> lines.
pub fn parse_lyrics(body: &[u8]) -> anyhow::Result<(Vec<(u32, String)>, bool)> {
let v: serde_json::Value = serde_json::from_slice(body)?;
let l = &v["lyrics"];
let synced = l["syncType"].as_str() == Some("LINE_SYNCED");
let lines = l["lines"]
.as_array()
.map(|a| {
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();
(t, w)
})
.collect()
})
.unwrap_or_default();
Ok((lines, synced))
}
fn track_of(item: &AudioItem) -> Track {
let id = item.track_id.to_id().unwrap_or_default();
let cover = item.covers.iter().max_by_key(|c| c.width).map(|c| c.url.clone()).unwrap_or_default();
let (artists, album, episode) = match &item.unique_fields {
UniqueFields::Track { artists, album, .. } => (
artists.0.iter().map(|a| (a.id.to_id().unwrap_or_default(), a.name.clone())).collect(),
album.clone(),
false,
),
UniqueFields::Episode { show_name, .. } => (vec![(String::new(), show_name.clone())], show_name.clone(), true),
UniqueFields::Local { artists, album, .. } => (artists.iter().map(|a| (String::new(), a.clone())).collect(), album.clone().unwrap_or_default(), false),
};
Track { uri: item.uri.clone(), id, name: item.name.clone(), artists, album, cover, duration_ms: item.duration_ms, episode, explicit: item.is_explicit }
}
fn bitrate(b: u32) -> Bitrate {
match b {
96 => Bitrate::Bitrate96,
320 => Bitrate::Bitrate320,
_ => Bitrate::Bitrate160,
}
}
fn load_request(c: Cmd) -> Option<LoadRequest> {
match c {
Cmd::Context { uri, start, shuffle } => {
let options = LoadRequestOptions {
start_playing: true,
seek_to: 0,
context_options: Some(LoadContextOptions::Options(Options { shuffle, repeat: false, repeat_track: false })),
playing_track: start.map(|Start::Uri(u)| PlayingTrack::Uri(u)),
};
Some(LoadRequest::from_context_uri(uri, options))
}
Cmd::Tracks { uris, start } => {
let options = LoadRequestOptions { start_playing: true, seek_to: 0, context_options: None, playing_track: Some(PlayingTrack::Index(start)) };
Some(LoadRequest::from_tracks(uris, options))
}
_ => None,
}
}
async fn run(cfg: Config, mut rx: mpsc::UnboundedReceiver<Cmd>, shared: Arc<Mutex<Option<Session>>>, events: Arc<dyn Fn(Event) + Send + Sync>) {
let dir = cache_dir();
let cache = match Cache::new(Some(dir.clone()), Some(dir.clone()), Some(dir.join("audio")), Some(512 << 20)) {
Ok(c) => Some(c),
Err(e) => {
log::warn!("cache: {e}");
None
}
};
let mut session_config = SessionConfig::default();
session_config.device_id = cfg.device_id.clone();
session_config.autoplay = Some(cfg.autoplay);
let connect_config = ConnectConfig {
name: cfg.device_name.clone(),
device_type: DeviceType::Tv,
is_group: false,
// The TV sets the loudness; Spotify plays at full scale.
initial_volume: u16::MAX,
disable_volume: false,
volume_steps: 64,
};
let player_config = PlayerConfig { bitrate: bitrate(cfg.bitrate), normalisation: cfg.normalise, gapless: true, ..PlayerConfig::default() };
let mixer = match mixer::find(None).map(|m| m(MixerConfig::default())) {
Some(Ok(m)) => m,
_ => {
events(Event::Status(Status::Failed("A hangkeverő nem indult el".into())));
return;
}
};
#[cfg(target_os = "linux")]
let backend = audio_backend::find(Some("gstreamer".into()));
#[cfg(not(target_os = "linux"))]
let backend = audio_backend::find(None);
let Some(backend) = backend else {
events(Event::Status(Status::Failed("Nincs hangkimenet".into())));
return;
};
let mut session = Session::new(session_config.clone(), cache.clone());
let player = Player::new(player_config, session.clone(), mixer.get_soft_volume(), move || backend(None, AudioFormat::default()));
*shared.lock().unwrap() = Some(session.clone());
// Player events -> UI.
{
let mut ch = player.get_player_event_channel();
let events = events.clone();
tokio::spawn(async move {
while let Some(ev) = ch.recv().await {
if let Some(e) = player_event(ev) {
events(e);
}
}
});
}
// Zeroconf: the phone signs in (or switches the account).
let mut discovery = match librespot_discovery::Discovery::builder(session_config.device_id.clone(), session_config.client_id.clone())
.name(cfg.device_name.clone())
.device_type(DeviceType::Tv)
.launch()
{
Ok(d) => Some(d),
Err(e) => {
log::warn!("discovery: {e}");
None
}
};
// Pairing codes: run while signed out.
let (pair_tx, mut pair_rx) = mpsc::unbounded_channel::<Credentials>();
let mut pairing: Option<tokio::task::JoinHandle<()>> = None;
let start_pairing = |pairing: &mut Option<tokio::task::JoinHandle<()>>| {
if pairing.as_ref().is_none_or(|p| p.is_finished()) {
*pairing = Some(tokio::spawn(pair_loop(session_config.client_id.clone(), events.clone(), pair_tx.clone())));
}
};
let mut credentials: Option<Credentials> = cache.as_ref().and_then(Cache::credentials);
let mut connecting = credentials.is_some();
if connecting {
events(Event::Status(Status::Connecting));
} else {
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
start_pairing(&mut pairing);
}
let mut spirc: Option<Spirc> = None;
let mut spirc_task: Option<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>> = None;
let mut failures = 0u32;
// Commands that came before Spirc was up (a load right after sign-in).
let mut waiting: Vec<Cmd> = Vec::new();
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(); }
credentials = Some(creds);
failures = 0;
connecting = true;
events(Event::Status(Status::Connecting));
}
_ = async {}, if connecting => {
connecting = false;
if session.is_invalid() {
session = Session::new(session_config.clone(), cache.clone());
player.set_session(session.clone());
*shared.lock().unwrap() = Some(session.clone());
}
let 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())));
}
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; }
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."))));
events(Event::Status(Status::SignIn(cfg.device_name.clone())));
start_pairing(&mut pairing);
} else {
failures += 1;
events(Event::Status(Status::Failed(format!("Nem sikerült csatlakozni a Spotifyhoz: {msg}"))));
let delay = Duration::from_secs((2u64 << failures.min(5)).min(60));
tokio::time::sleep(delay).await;
connecting = credentials.is_some();
if connecting { events(Event::Status(Status::Connecting)); }
}
}
}
}
_ = async { if let Some(t) = spirc_task.as_mut() { t.await } else { std::future::pending().await } } => {
// Spirc ended: the connection broke. Reconnect.
log::warn!("connect ended, reconnecting");
spirc_task = None;
spirc = None;
if credentials.is_some() {
failures += 1;
tokio::time::sleep(Duration::from_secs((1u64 << failures.min(5)).min(30))).await;
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),
}
}
}
}
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;
}
}
// ---------------------------------------------------------------------------- pairing
const ACCOUNTS: &str = "https://accounts.spotify.com";
/// The scopes librespot asks for when signing in with a token.
const PAIR_SCOPES: &str = "app-remote-control playlist-modify playlist-modify-private playlist-modify-public playlist-read playlist-read-collaborative playlist-read-private streaming ugc-image-upload user-follow-modify user-follow-read user-library-modify user-library-read user-modify user-modify-playback-state user-modify-private user-personalized user-read-currently-playing user-read-email user-read-play-history user-read-playback-position user-read-playback-state user-read-private user-read-recently-played user-top-read";
struct DeviceCode {
device_code: String,
pair: Pair,
interval: u64,
expires: u64,
}
enum Poll {
Pending,
SlowDown,
Token(String),
/// Expired or refused: a new code is needed.
Over,
}
fn form(pairs: &[(&str, &str)]) -> String {
pairs.iter().map(|(k, v)| format!("{k}={}", crate::api::enc(v))).collect::<Vec<_>>().join("&")
}
fn post_form(path: &str, body: String) -> anyhow::Result<(u16, serde_json::Value)> {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(Duration::from_secs(20))).http_status_as_error(false).build().into();
let resp = agent.post(&format!("{ACCOUNTS}{path}")).header("Content-Type", "application/x-www-form-urlencoded").send(body)?;
let status = resp.status().as_u16();
let text = resp.into_body().read_to_string()?;
Ok((status, serde_json::from_str(&text).unwrap_or_default()))
}
fn request_code(client_id: &str) -> anyhow::Result<DeviceCode> {
let (status, v) = post_form("/oauth2/device/authorize", form(&[("client_id", client_id), ("scope", PAIR_SCOPES)]))?;
let s = |k: &str| v[k].as_str().unwrap_or("").to_string();
if status != 200 || s("device_code").is_empty() {
anyhow::bail!("pairing code: {status} {v}");
}
let url = if s("verification_uri_complete").is_empty() { s("verification_uri") } else { s("verification_uri_complete") };
Ok(DeviceCode {
device_code: s("device_code"),
pair: Pair { code: s("user_code"), url },
interval: v["interval"].as_u64().unwrap_or(5).max(2),
expires: v["expires_in"].as_u64().unwrap_or(600),
})
}
fn poll_token(client_id: &str, device_code: &str) -> anyhow::Result<Poll> {
let (status, v) = post_form("/api/token", form(&[("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), ("device_code", device_code), ("client_id", client_id)]))?;
if status == 200 {
if let Some(t) = v["access_token"].as_str() {
return Ok(Poll::Token(t.to_string()));
}
}
Ok(match v["error"].as_str().unwrap_or("") {
"authorization_pending" => Poll::Pending,
"slow_down" => Poll::SlowDown,
_ => Poll::Over,
})
}
/// Shows pairing codes (a new one when one expires) until the phone signs in.
async fn pair_loop(client_id: String, events: Arc<dyn Fn(Event) + Send + Sync>, done: mpsc::UnboundedSender<Credentials>) {
loop {
let cid = client_id.clone();
let code = match tokio::task::spawn_blocking(move || request_code(&cid)).await {
Ok(Ok(c)) => c,
other => {
if let Ok(Err(e)) = other {
log::warn!("{e:#}");
}
events(Event::Pair(None));
tokio::time::sleep(Duration::from_secs(15)).await;
continue;
}
};
events(Event::Pair(Some(code.pair.clone())));
let deadline = std::time::Instant::now() + Duration::from_secs(code.expires.saturating_sub(10));
let mut interval = code.interval;
while std::time::Instant::now() < deadline {
tokio::time::sleep(Duration::from_secs(interval)).await;
let (cid, dc) = (client_id.clone(), code.device_code.clone());
match tokio::task::spawn_blocking(move || poll_token(&cid, &dc)).await {
Ok(Ok(Poll::Token(t))) => {
let _ = done.send(Credentials::with_access_token(t));
return;
}
Ok(Ok(Poll::SlowDown)) => interval += 5,
Ok(Ok(Poll::Over)) => break,
Ok(Ok(Poll::Pending)) => {}
// Network trouble: keep the code, try again.
Ok(Err(e)) => log::info!("pairing poll: {e:#}"),
Err(_) => {}
}
}
}
}
fn apply(s: &Spirc, c: Cmd) {
let r = match c {
Cmd::Context { .. } | Cmd::Tracks { .. } => {
let req = load_request(c).unwrap();
// The TV takes the playback over (it may be on the phone).
let _ = s.activate();
s.load(req)
}
Cmd::PlayPause => s.play_pause(),
Cmd::Play => s.activate().and_then(|_| s.play()),
Cmd::Pause => s.pause(),
Cmd::Next => s.next(),
Cmd::Prev => s.prev(),
Cmd::Seek(ms) => s.set_position_ms(ms),
Cmd::Shuffle(on) => s.shuffle(on),
Cmd::Repeat(ctx, track) => s.repeat(ctx).and_then(|_| s.repeat_track(track)),
Cmd::SignOut | Cmd::Quit => Ok(()),
};
if let Err(e) = r {
log::warn!("command: {e}");
}
}
fn player_event(ev: PlayerEvent) -> Option<Event> {
Some(match ev {
PlayerEvent::TrackChanged { audio_item } => Event::Track(track_of(&audio_item)),
PlayerEvent::Loading { .. } => Event::Loading,
PlayerEvent::Playing { position_ms, .. } => Event::Playing(position_ms),
PlayerEvent::Paused { position_ms, .. } => Event::Paused(position_ms),
PlayerEvent::Seeked { position_ms, .. } | PlayerEvent::PositionCorrection { position_ms, .. } => Event::Seeked(position_ms),
PlayerEvent::Stopped { .. } => Event::Stopped,
PlayerEvent::Unavailable { .. } => Event::Unavailable,
PlayerEvent::ShuffleChanged { shuffle } => Event::Shuffle(shuffle),
PlayerEvent::RepeatChanged { context, track } => Event::Repeat(context, track),
PlayerEvent::SessionConnected { .. } => Event::Active(true),
PlayerEvent::SessionDisconnected { .. } => Event::Active(false),
PlayerEvent::SessionClientChanged { client_name, .. } => Event::Client(client_name),
_ => return None,
})
}
/// Mock mode: signed in at once; "plays" a made-up track for every load.
async fn mock_loop(mut rx: mpsc::UnboundedReceiver<Cmd>, events: Arc<dyn Fn(Event) + Send + Sync>) {
tokio::time::sleep(Duration::from_millis(300)).await;
if std::env::var("SPOTIFY_MOCK").as_deref() == Ok("signin") {
events(Event::Status(Status::SignIn("Fennec TV".into())));
events(Event::Pair(Some(Pair { code: "5HWPC6".into(), url: "https://spotify.com/pair?code=5HWPC6".into() })));
std::future::pending::<()>().await;
}
events(Event::Status(Status::Ready("demo".into())));
let mut playing = false;
let mut n = 0u32;
let track = |n: u32| Track {
uri: format!("spotify:track:mock{n}"),
id: format!("mock{n}"),
name: ["Hajnali fények", "Nyári éjszaka", "Városi zaj", "Csend a víz felett"][n as usize % 4].into(),
artists: vec![("mockartist".into(), "Demó Előadó".into())],
album: "Demó album".into(),
cover: format!("https://picsum.photos/seed/cover{}/640/640", n % 4),
duration_ms: 214_000,
episode: false,
explicit: false,
};
while let Some(c) = rx.recv().await {
match c {
Cmd::Context { .. } | Cmd::Tracks { .. } => {
n += 1;
events(Event::Active(true));
events(Event::Track(track(n)));
events(Event::Playing(0));
playing = true;
}
Cmd::PlayPause => {
playing = !playing;
events(if playing { Event::Playing(30_000) } else { Event::Paused(30_000) });
}
Cmd::Play => events(Event::Playing(30_000)),
Cmd::Pause => events(Event::Paused(30_000)),
Cmd::Next | Cmd::Prev => {
n += 1;
events(Event::Track(track(n)));
events(Event::Playing(0));
}
Cmd::Seek(ms) => events(Event::Seeked(ms)),
Cmd::Shuffle(on) => events(Event::Shuffle(on)),
Cmd::Repeat(c, t) => events(Event::Repeat(c, t)),
Cmd::SignOut => events(Event::Status(Status::SignIn("Fennec TV".into()))),
Cmd::Quit => break,
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn parses_lyrics() {
let body = br#"{"lyrics":{"syncType":"LINE_SYNCED","lines":[{"startTimeMs":"1200","words":"Hello"},{"startTimeMs":"5300","words":""}]},"colors":{}}"#;
let (lines, synced) = super::parse_lyrics(body).unwrap();
assert!(synced);
assert_eq!(lines, vec![(1200, "Hello".to_string()), (5300, String::new())]);
}
}

40
src/task.rs Normal file
View File

@@ -0,0 +1,40 @@
//! Blocking work (HTTP calls) on a thread, its result back on the UI thread.
//!
//! `done` runs on the Slint event loop, so it may touch the UI and `Rc`
//! state; it is kept in a thread-local table while the work runs.
use std::cell::RefCell;
use std::collections::HashMap;
use std::sync::atomic::{AtomicU64, Ordering};
type Done = Box<dyn FnOnce(Box<dyn std::any::Any + Send>)>;
thread_local! {
static WAITING: RefCell<HashMap<u64, Done>> = RefCell::new(HashMap::new());
}
static NEXT: AtomicU64 = AtomicU64::new(1);
/// Runs `work` on a new thread; `done(result)` runs on the UI thread. Call it
/// from the UI thread.
pub fn spawn<T: Send + 'static>(work: impl FnOnce() -> T + Send + 'static, done: impl FnOnce(T) + 'static) {
let id = NEXT.fetch_add(1, Ordering::Relaxed);
WAITING.with(|w| {
w.borrow_mut().insert(
id,
Box::new(move |any: Box<dyn std::any::Any + Send>| {
if let Ok(v) = any.downcast::<T>() {
done(*v);
}
}),
)
});
std::thread::spawn(move || {
let result: Box<dyn std::any::Any + Send> = Box::new(work());
let _ = slint::invoke_from_event_loop(move || {
if let Some(done) = WAITING.with(|w| w.borrow_mut().remove(&id)) {
done(result);
}
});
});
}