//! 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:" album, "pl:" playlist, //! "ar:" artist, "sh:" podcast, "liked" the liked songs, //! "t:|" 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 { 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 { #[default] Loading, Ready(T), Failed(String), } impl Load { 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) -> Load { 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 { 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::>().join(", "); let y = format::year(&a.release_date); c.detail = [y, artists].into_iter().filter(|s| !s.is_empty()).collect::>().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 } pub fn liked_card(total: Option) -> 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, 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 "#" line id. pub fn row_index(line: &str) -> Option { line.rsplit_once('#')?.1.parse().ok() } /// Plays `t` from a list: in `context` if given, else the list's tracks. pub fn play_from(cx: &Cx, context: &str, tracks: &[Track], i: usize) { let Some(t) = tracks.get(i) else { return }; if !t.playable() { cx.toast("Ez a szám nem játszható le."); return; } let shuffle = cx.c.state.borrow().np.shuffle; if context.is_empty() { let uris: Vec = tracks.iter().filter(|t| t.playable()).map(|t| t.uri.clone()).collect(); let start = uris.iter().position(|u| *u == t.uri).unwrap_or(0) as u32; cx.play(Cmd::Tracks { uris, start }); } else { cx.play(Cmd::Context { uri: context.to_string(), start: Some(Start::Uri(t.uri.clone())), shuffle }); } } /// 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) { 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))), _ => {} } }), ); }