From 57eb805d69686030de97be1c4deb55060b21de33 Mon Sep 17 00:00:00 2001 From: Paul Otto Date: Tue, 10 Nov 2026 12:31:52 +0100 Subject: [PATCH 1/4] feat: YouTube Music's Home as in its apps, a star, problems that stay - Home has YouTube Music's chips for moods like Relax or Workout, which ask for that mood's Home, and the line above a shelf where it has one. Quick picks and Trending songs show as songs in columns of four, play at once with their radio after them, and Play all plays the shelf. - On the second day of use, cloofy asks once for a star on GitHub. Either answer is final; the days count in state.json. - An expired sign-in stays at the bottom until closed or signed in again, and a click copies `cloofy login ytmusic` (#27). - YouTube's bot check is told apart from other yt-dlp errors and said once, at the bottom until something plays, in `cloofy doctor` and in `cloofy play`, instead of skipping song after song in silence. Fixes #27 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 16 + Cargo.lock | 1 + README.md | 1 + crates/cloofy-core/src/home.rs | 45 ++- crates/cloofy-core/src/player.rs | 5 + crates/cloofy-core/src/update.rs | 2 + crates/cloofy-spotify/src/artist.rs | 2 +- crates/cloofy-spotify/src/home.rs | 3 +- crates/cloofy-tui/Cargo.toml | 1 + crates/cloofy-tui/src/app/browsing.rs | 2 +- crates/cloofy-tui/src/app/menu.rs | 10 +- crates/cloofy-tui/src/app/mod.rs | 205 +++++++++++- crates/cloofy-tui/src/app/persist.rs | 8 +- crates/cloofy-tui/src/backend/fake.rs | 73 ++++- crates/cloofy-tui/src/backend/mod.rs | 5 +- crates/cloofy-tui/src/backend/spotify/mod.rs | 2 +- crates/cloofy-tui/src/backend/ytmusic/mod.rs | 4 +- crates/cloofy-tui/src/loader.rs | 5 +- crates/cloofy-tui/src/overlay.rs | 6 +- crates/cloofy-tui/src/scenarios/playback.rs | 95 ++++++ crates/cloofy-tui/src/state.rs | 57 ++++ crates/cloofy-tui/src/ui/artist.rs | 4 + crates/cloofy-tui/src/ui/hints.rs | 47 ++- crates/cloofy-tui/src/ui/home.rs | 294 +++++++++++++++--- crates/cloofy-tui/src/ui/mod.rs | 2 + crates/cloofy-tui/src/ui/picker.rs | 4 +- crates/cloofy-tui/src/ui/star.rs | 70 +++++ crates/cloofy-tui/src/views.rs | 260 +++++++++++++++- crates/cloofy-tui/tests/screens/star.txt | 36 +++ .../cloofy-tui/tests/screens/ytmusic_home.txt | 36 +++ crates/cloofy-ytmusic/examples/ytm.rs | 13 +- crates/cloofy-ytmusic/src/doctor.rs | 2 +- crates/cloofy-ytmusic/src/home.rs | 84 ++++- crates/cloofy-ytmusic/src/lib.rs | 7 +- crates/cloofy-ytmusic/src/parse.rs | 22 +- crates/cloofy-ytmusic/src/player/mod.rs | 19 +- crates/cloofy-ytmusic/src/player/stream.rs | 32 ++ crates/cloofy-ytmusic/tests/live.rs | 2 +- crates/cloofy/examples/demo_fixture.rs | 5 +- crates/cloofy/src/ytmusic/playback.rs | 1 + .../src/content/docs/docs/troubleshooting.md | 3 +- .../src/content/docs/docs/youtube-music.md | 8 + website/src/pages/index.astro | 4 +- 43 files changed, 1374 insertions(+), 129 deletions(-) create mode 100644 crates/cloofy-tui/src/ui/star.rs create mode 100644 crates/cloofy-tui/tests/screens/star.txt create mode 100644 crates/cloofy-tui/tests/screens/ytmusic_home.txt diff --git a/CHANGELOG.md b/CHANGELOG.md index 84544c9..ff588ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to cloofy. The format follows [Keep a Changelog](https://kee ## [Unreleased] +### Added + +- **Moods on YouTube Music's Home.** Chips like Relax, Workout or Focus above the shelves show the Home of that mood, as on music.youtube.com, and picked again the whole Home. ↑ from the first shelf reaches them. +- **Quick picks as songs.** Quick picks and Trending songs show as songs in columns of four, with a small cover and the artists under the title. ↑ ↓ move within a column, ← → from column to column. **Play all** plays the whole shelf in order. +- **The line above a shelf,** like "THE BEST HITS FOR INSTANT MORNING ENERGY.", where YouTube Music has one. +- **A star on GitHub.** On the second day you use cloofy, it asks once whether you'd give it a star on GitHub. Whatever you answer, it doesn't ask again. + +### Changed + +- **Songs on YouTube Music's Home play at once,** with their radio after them, as in YouTube Music's own apps, instead of opening the radio as a page. Their menu is a song's: add to queue, like, add to playlist. + +### Fixed + +- **An expired YouTube Music sign-in** stays at the bottom until you close it, instead of for a few seconds, and a click copies `cloofy login ytmusic` ([#27](https://github.com/parda21/cloofy/issues/27)). +- **YouTube's bot check.** When YouTube asks your connection to prove it isn't a bot, no song plays. cloofy said nothing and skipped song after song; now it says why at the bottom until music plays again, and so do `cloofy doctor` and `cloofy play`. + ## [0.5.1] - 2026-11-05 cloofy takes on your terminal's colors or your own, and song notifications reach every terminal on Linux. diff --git a/Cargo.lock b/Cargo.lock index 8faa208..e990fc7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -554,6 +554,7 @@ dependencies = [ "libc", "librespot", "nucleo-matcher", + "open", "ratatui", "ratatui-image", "reqwest", diff --git a/README.md b/README.md index e5c0fe8..f4d70d4 100644 --- a/README.md +++ b/README.md @@ -31,6 +31,7 @@ cloofy plays Spotify and YouTube Music in the terminal, one of them or both side - **Plays on its own.** Spotify plays through librespot, and cloofy is a Spotify Connect device. It controls your other devices too, and follows them live. YouTube Music plays through mpv, which cloofy starts and stops itself, with no gap between songs. - **Spotify, YouTube Music or both.** Install one, or both side by side: S or the switch in the top bar shows the other's Home, library and pages, as you left them. - **YouTube Music without an account.** Home, search, every page, lyrics and song radios work signed out. Sign in with your browser for your library and likes. +- **YouTube Music's Home, as in its apps.** Moods like Relax or Workout narrow it down, and Quick picks show as songs that play at once, or all in a row. - **Home and the DJ.** Your shelves and mixes, and on Spotify Made For You and the DJ with its voice between tracks. Ask the DJ for something, as in Spotify's apps, or let it pick something different. Crossfade if you like. - **Your library.** Playlists, albums, artists, and on Spotify podcasts, in a sidebar or as a full page with covers. - **Every page.** Playlists, albums and artist pages with popular tracks and releases, plus search with artwork. diff --git a/crates/cloofy-core/src/home.rs b/crates/cloofy-core/src/home.rs index 1316df2..efe3744 100644 --- a/crates/cloofy-core/src/home.rs +++ b/crates/cloofy-core/src/home.rs @@ -2,18 +2,48 @@ use serde::{Deserialize, Serialize}; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Home { pub greeting: String, + /// Moods and kinds of music that narrow Home down, shown above its shelves the way + /// music.youtube.com shows them. Empty for services without. + #[serde(default)] + pub chips: Vec, pub shelves: Vec, } -#[derive(Debug, Clone, Serialize, Deserialize)] +impl Home { + /// The chip Home is narrowed to, if any. + pub fn chip(&self) -> Option<&Chip> { + self.chips.iter().find(|chip| chip.selected) + } +} + +/// A mood or kind of music Home can be narrowed to, e.g. "Relax". +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Chip { + pub title: String, + /// What the service needs to show Home for this chip. + pub id: String, + /// Whether this Home is the chip's. + pub selected: bool, +} + +#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct Shelf { pub uri: String, pub title: String, + /// A line above the title, e.g. "THE BEST HITS FOR INSTANT MORNING ENERGY.". + #[serde(default)] + pub strapline: String, /// The compact grid of shortcuts at the top of Home. pub shortcuts: bool, + /// Songs in columns of a few rows, like YouTube Music's Quick picks, instead of cards. + #[serde(default)] + pub songs: bool, + /// What the shelf's Play all button plays, when it has one. + #[serde(default)] + pub play_all: Option, pub items: Vec, } @@ -37,6 +67,15 @@ pub struct HomeItem { /// Playlist owner, to tell own playlists from the service's. pub owner_id: String, pub owner_name: String, - /// What to play: the show for an episode, the item itself otherwise. + /// What to play: the show for an episode, the song for a song's radio, the item itself + /// otherwise. pub context_uri: String, } + +impl HomeItem { + /// A song shown as its radio: it plays at once, as in the services' own apps, and opens as + /// the radio. + pub fn is_song(&self) -> bool { + self.kind == ItemKind::Playlist && self.context_uri != self.uri + } +} diff --git a/crates/cloofy-core/src/player.rs b/crates/cloofy-core/src/player.rs index 3cedb51..813f21b 100644 --- a/crates/cloofy-core/src/player.rs +++ b/crates/cloofy-core/src/player.rs @@ -66,6 +66,11 @@ pub enum PlayerEvent { uri: String, refused: bool, }, + /// Nothing can play until something outside cloofy changes, such as YouTube asking the + /// connection to prove it isn't a bot. Said once, until music plays again. + Blocked { + reason: String, + }, } /// A track that plays later, as the player listed it. diff --git a/crates/cloofy-core/src/update.rs b/crates/cloofy-core/src/update.rs index fdfc222..c0dc7f3 100644 --- a/crates/cloofy-core/src/update.rs +++ b/crates/cloofy-core/src/update.rs @@ -15,6 +15,8 @@ use sha2::{Digest, Sha256}; use crate::paths::Paths; const REPO: &str = "parda21/cloofy"; +/// cloofy's page on GitHub. +pub const REPO_URL: &str = "https://github.com/parda21/cloofy"; const USER_AGENT: &str = concat!("cloofy/", env!("CARGO_PKG_VERSION")); /// GitHub answers 60 requests an hour without an account; a look every few hours is plenty. const CHECK_INTERVAL: Duration = Duration::from_secs(6 * 60 * 60); diff --git a/crates/cloofy-spotify/src/artist.rs b/crates/cloofy-spotify/src/artist.rs index 51d44ce..ca4300c 100644 --- a/crates/cloofy-spotify/src/artist.rs +++ b/crates/cloofy-spotify/src/artist.rs @@ -29,8 +29,8 @@ fn parse(data: &Value) -> Result { let shelf = |title: &str, items: Vec| Shelf { uri: String::new(), title: title.to_owned(), - shortcuts: false, items, + ..Shelf::default() }; let shelves = [ shelf("Popular releases", releases(&discography["popularReleasesAlbums"], false)), diff --git a/crates/cloofy-spotify/src/home.rs b/crates/cloofy-spotify/src/home.rs index 3388288..843f430 100644 --- a/crates/cloofy-spotify/src/home.rs +++ b/crates/cloofy-spotify/src/home.rs @@ -37,7 +37,7 @@ fn parse(data: &Value) -> Result { .flatten() .filter_map(shelf) .collect(); - Ok(Home { greeting: text(home, "/greeting/transformedLabel"), shelves }) + Ok(Home { greeting: text(home, "/greeting/transformedLabel"), shelves, ..Home::default() }) } fn shelf(section: &Value) -> Option { @@ -56,6 +56,7 @@ fn shelf(section: &Value) -> Option { title: text(section, "/data/title/transformedLabel"), shortcuts: section.pointer("/data/__typename").and_then(Value::as_str) == Some("HomeShortsSectionData"), items, + ..Shelf::default() }) } diff --git a/crates/cloofy-tui/Cargo.toml b/crates/cloofy-tui/Cargo.toml index 504d58f..50a8d4c 100644 --- a/crates/cloofy-tui/Cargo.toml +++ b/crates/cloofy-tui/Cargo.toml @@ -27,6 +27,7 @@ futures.workspace = true icy_sixel.workspace = true image.workspace = true nucleo-matcher.workspace = true +open.workspace = true ratatui.workspace = true ratatui-image.workspace = true reqwest.workspace = true diff --git a/crates/cloofy-tui/src/app/browsing.rs b/crates/cloofy-tui/src/app/browsing.rs index 3c2015b..eb05271 100644 --- a/crates/cloofy-tui/src/app/browsing.rs +++ b/crates/cloofy-tui/src/app/browsing.rs @@ -296,7 +296,7 @@ impl App { self.loader.library(); } if let View::Home(v) = &self.view { - self.loader.home(v.id); + self.loader.home(v.id, v.filter.as_ref().map(|c| c.id.clone())); } if !self.demo { self.load_cache(); diff --git a/crates/cloofy-tui/src/app/menu.rs b/crates/cloofy-tui/src/app/menu.rs index 7a4ff5a..b6bd10d 100644 --- a/crates/cloofy-tui/src/app/menu.rs +++ b/crates/cloofy-tui/src/app/menu.rs @@ -128,6 +128,10 @@ impl App { } fn home_target(&self, item: &HomeItem) -> ContextTarget { + // A song shown as its radio is the song, as in YouTube Music's own menus. + if item.is_song() { + return target(&item.context_uri, &item.title, TargetKind::Track, item.image_url.clone()); + } let kind = match item.kind { ItemKind::Playlist => TargetKind::Playlist, ItemKind::Album => TargetKind::Album, @@ -383,7 +387,11 @@ fn menu_items(target: &ContextTarget, saved: bool) -> Vec<(MenuAction, String)> } /// OSC 52: the terminal puts the text on the clipboard, which also works over SSH. -fn copy_to_clipboard(text: &str) { +pub(super) fn copy_to_clipboard(text: &str) { + // Tests have no terminal to tell. + if cfg!(test) { + return; + } let mut stdout = std::io::stdout(); let _ = write!(stdout, "\x1b]52;c;{}\x07", STANDARD.encode(text)); let _ = stdout.flush(); diff --git a/crates/cloofy-tui/src/app/mod.rs b/crates/cloofy-tui/src/app/mod.rs index b0fe24e..e5322cf 100644 --- a/crates/cloofy-tui/src/app/mod.rs +++ b/crates/cloofy-tui/src/app/mod.rs @@ -58,6 +58,8 @@ use crate::{ pub const COVER_SIZE: Size = Size { width: 6, height: 3 }; const SEARCH_DEBOUNCE: Duration = Duration::from_millis(250); const STATUS_TTL: Duration = Duration::from_secs(4); +/// How long after the start cloofy waits before it asks for a star, so the first screen is up. +const STAR_DELAY: Duration = Duration::from_secs(5); const SEEK_STEP_MS: i64 = 5_000; /// "Previous" restarts the track once it has played this long, as in Spotify's own clients. const RESTART_AFTER_MS: u32 = 3_000; @@ -283,6 +285,14 @@ pub enum Hit { shelf: usize, forward: bool, }, + /// The Play all button of a shelf. + ShelfPlay(usize), + /// The pinned problem in the bottom line, which copies its command… + PinnedCopy, + /// …and the cross that closes it. + PinnedClose, + /// A chip above Home's shelves, such as "Relax". + HomeChip(usize), /// An artist, album or playlist name that leads to its page. Link(Link), Chip(LibraryFilter), @@ -386,6 +396,25 @@ pub struct Status { since: Instant, } +/// A problem that stays in the bottom line until it's solved or closed, rather than for a few +/// seconds: an expired sign-in, or YouTube's bot check. +#[derive(Debug, Clone, PartialEq)] +pub struct Pinned { + pub text: String, + /// What to run in a terminal, e.g. `cloofy login ytmusic`; a click copies it. + pub command: Option, + pub copied: bool, + pub cause: Cause, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Cause { + /// The service doesn't accept the sign-in any more: gone once it does again. + SignIn, + /// Nothing can play: gone once something does. + Blocked, +} + /// A transfer of playback to another device, until that device shows up playing. struct Transfer { device_id: String, @@ -510,6 +539,15 @@ pub struct App { /// The last Home feed, shown instantly while a fresh one loads. home_cache: Option, home_fetched_at: Option, + /// On how many days cloofy was used, and whether it asked for a star. + pub(crate) usage: crate::state::Usage, + /// When to ask for a star on GitHub. + star_due: Option, + /// Links opened in the browser, in tests instead. + #[cfg(test)] + pub opened: Vec, + /// A problem that stays until it's solved or closed. + pub pinned: Option, /// Library, user or Home changed since the data cache was last written. data_dirty: bool, last_cache_save: Instant, @@ -683,6 +721,11 @@ impl App { shown_before: false, home_cache: None, home_fetched_at: None, + usage: crate::state::Usage::default(), + pinned: None, + star_due: None, + #[cfg(test)] + opened: Vec::new(), data_dirty: false, last_cache_save: Instant::now(), cached_tracks: None, @@ -1107,7 +1150,7 @@ impl App { View::Home(v) if v.error.is_some() => { v.error = None; v.loading = true; - self.loader.home(v.id); + self.loader.home(v.id, v.filter.as_ref().map(|c| c.id.clone())); } View::Artist(v) if v.error.is_some() => { v.error = None; @@ -1166,6 +1209,11 @@ impl App { PlayerEvent::Unavailable { refused: false, .. } => { self.notice("A song couldn't load, so it was skipped".into()) } + PlayerEvent::Blocked { reason } => { + self.pinned = + Some(Pinned { text: reason.clone(), command: None, copied: false, cause: Cause::Blocked }); + } + PlayerEvent::Playing { .. } => self.unpin(Cause::Blocked), _ => {} } if matches!(event, PlayerEvent::TrackChanged { .. } | PlayerEvent::Playing { .. }) { @@ -1357,6 +1405,13 @@ impl App { } self.me = Some(user); self.data_dirty = true; + // Signed in again. + if let Some(service) = self.loader.service() + && self.pinned.as_ref().and_then(|p| p.command.as_deref()) + == Some(&*format!("cloofy login {}", service.key())) + { + self.unpin(Cause::SignIn); + } } Err(err) => self.error(err), }, @@ -1414,12 +1469,16 @@ impl App { self.loader.check_saved(uris); } DataEvent::Home { view, result } => { - if let Ok(home) = &result { + // A chip's Home is only for its view; the whole Home is what Home opens with. + if let Some(home) = result.as_ref().ok().filter(|home| home.chip().is_none()) { self.home_cache = Some(home.clone()); self.home_fetched_at = Some(Instant::now()); self.data_dirty = true; } let Some(View::Home(v)) = self.view_mut(view) else { return false }; + if result.as_ref().is_ok_and(|home| !v.wants(home)) { + return false; + } match result { Ok(home) => v.set_home(home), Err(err) => { @@ -1785,6 +1844,8 @@ impl App { redraw = true; } + redraw |= self.ask_for_star(); + if self.status.as_ref().is_some_and(|s| s.since.elapsed() >= STATUS_TTL) { self.status = None; redraw = true; @@ -1915,6 +1976,8 @@ impl App { self.quit = true; } else if matches!(self.overlay, Some(Overlay::Help)) { self.overlay = None; + } else if matches!(self.overlay, Some(Overlay::Star { .. })) { + self.on_star_key(key); } else if matches!(self.overlay, Some(Overlay::Menu(_))) { self.on_menu_key(key); } else { @@ -2169,6 +2232,60 @@ impl App { self.apply_choice(outcome); } + fn on_star_key(&mut self, key: KeyEvent) { + let Some(Overlay::Star { cursor }) = &mut self.overlay else { return }; + match key.code { + KeyCode::Left | KeyCode::Right | KeyCode::Tab | KeyCode::BackTab | KeyCode::Char('h' | 'l') => { + *cursor = 1 - *cursor; + } + KeyCode::Enter => { + let star = *cursor == 0; + self.answer_star(star); + } + KeyCode::Char('s') => self.answer_star(true), + KeyCode::Esc | KeyCode::Char('n') => self.answer_star(false), + _ => {} + } + } + + /// Asks for a star on GitHub once `delay` has passed and nothing else is in the way. + pub(crate) fn ask_for_star_after(&mut self, delay: Duration) { + self.star_due = Some(Instant::now() + delay); + } + + /// Shows the request for a star, if it is due and the screen is calm. It counts as asked + /// the moment it shows: closed in any way, it never comes back. + fn ask_for_star(&mut self) -> bool { + let calm = self.overlay.is_none() && self.focus != Focus::SearchInput && !self.zen && !self.demo; + if !calm || !self.star_due.is_some_and(|due| Instant::now() >= due) { + return false; + } + self.star_due = None; + self.usage.star_asked = true; + self.save_state(); + self.overlay = Some(Overlay::Star { cursor: 0 }); + self.overlay_fx_pending = true; + true + } + + /// Closes the request for a star, opening cloofy's page on GitHub for one. + fn answer_star(&mut self, star: bool) { + self.overlay = None; + if star { + self.open_in_browser(cloofy_core::update::REPO_URL); + self.notice("Thank you!".into()); + } + } + + fn open_in_browser(&mut self, url: &str) { + #[cfg(not(test))] + if let Err(err) = open::that_detached(url) { + self.error(format!("Can't open {url}: {err}")); + } + #[cfg(test)] + self.opened.push(url.to_owned()); + } + fn on_menu_key(&mut self, key: KeyEvent) { let Some(Overlay::Menu(menu)) = &mut self.overlay else { return }; let len = menu.items.len(); @@ -2314,7 +2431,12 @@ impl App { /// Pages the shelf under the mouse sideways by one card. fn scroll_sideways(&mut self, hit: Option, delta: isize) { let shelf = match hit { - Some(Hit::Card { shelf, .. } | Hit::CardPlay { shelf, .. } | Hit::ShelfScroll { shelf, .. }) => shelf, + Some( + Hit::Card { shelf, .. } + | Hit::CardPlay { shelf, .. } + | Hit::ShelfScroll { shelf, .. } + | Hit::ShelfPlay(shelf), + ) => shelf, _ => return, }; match &mut self.view { @@ -2431,11 +2553,18 @@ impl App { Hit::ShelfScroll { shelf, forward } => { let page = |cards: usize| if forward { cards as isize } else { -(cards as isize) }; match &mut self.view { - View::Home(v) => v.scroll_shelf(shelf, page(v.cards)), + View::Home(v) => v.scroll_shelf(shelf, page(v.visible(shelf))), View::Artist(v) => v.scroll_shelf(shelf, page(v.cards)), _ => {} } } + Hit::ShelfPlay(shelf) => self.play_shelf(shelf), + Hit::PinnedCopy => self.on_pinned(false), + Hit::PinnedClose => self.on_pinned(true), + Hit::HomeChip(index) => { + self.focus = Focus::Content; + self.pick_chip(index); + } Hit::Link(link) => self.follow_link(link), Hit::Hint(action) => match action { HintAction::Run(command) => self.run(command), @@ -2480,6 +2609,9 @@ impl App { Hit::OverlayItem(position) if matches!(self.overlay, Some(Overlay::Menu(_))) => { self.choose_menu_item(position); } + Hit::OverlayItem(position) if matches!(self.overlay, Some(Overlay::Star { .. })) => { + self.answer_star(position == 0); + } Hit::OverlayItem(position) => { let outcome = match &self.overlay { Some(Overlay::Palette(picker)) => picker.select(position).map(Choice::Palette), @@ -2526,6 +2658,8 @@ impl App { | Hit::CardPlay { .. } | Hit::RowPlay(_) | Hit::ShelfScroll { .. } + | Hit::ShelfPlay(_) + | Hit::HomeChip(_) | Hit::PageChip(_) | Hit::Header(_) | Hit::SettingStep { .. }, @@ -3111,7 +3245,7 @@ impl App { if self.home_fetched_at.is_some_and(|at| at.elapsed() < HOME_FRESH) { view.loading = false; } else { - self.loader.home(id); + self.loader.home(id, None); } self.push_view(View::Home(view)); self.focus = Focus::Content; @@ -3426,8 +3560,16 @@ impl App { fn activate(&mut self) { match &self.view { View::Home(v) => { + if let Some(chip) = v.chip { + return self.pick_chip(chip); + } if let Some(item) = v.selected().cloned() { - self.open_home_item(item); + // A song plays at once, as in YouTube Music's own apps. + if item.is_song() { + self.play_item(item); + } else { + self.open_home_item(item); + } } } View::Library(v) => { @@ -3548,6 +3690,24 @@ impl App { self.focus = Focus::Content; } + /// Narrows Home to the chip at `index`, or widens it back to the whole Home. + fn pick_chip(&mut self, index: usize) { + let View::Home(v) = &mut self.view else { return }; + if let Some(chip) = v.pick_chip(index) { + let id = v.id; + self.loader.home(id, chip); + } + } + + /// Plays what a shelf's Play all button plays. + fn play_shelf(&mut self, shelf: usize) { + let View::Home(v) = &self.view else { return }; + let Some(context) = v.home.as_ref().and_then(|h| h.shelves.get(shelf)).and_then(|s| s.play_all.clone()) else { + return; + }; + self.play(context, None); + } + fn play_home_item(&mut self) { if let View::Home(v) = &self.view && let Some(item) = v.selected().cloned() @@ -3912,9 +4072,40 @@ impl App { self.status = Some(Status { text, error: false, since: Instant::now() }); } - fn error(&mut self, text: String) { + pub(crate) fn error(&mut self, text: String) { + // An expired sign-in stays, with the command that renews it. + if let Some(command) = sign_in_command(&text) { + self.pinned = Some(Pinned { text, command: Some(command), copied: false, cause: Cause::SignIn }); + return; + } self.status = Some(Status { text, error: true, since: Instant::now() }); } + + /// Closes the pinned problem of `cause`, which went away. + fn unpin(&mut self, cause: Cause) { + if self.pinned.as_ref().is_some_and(|p| p.cause == cause) { + self.pinned = None; + } + } + + /// Copies the pinned problem's command, or closes it. + fn on_pinned(&mut self, close: bool) { + if close { + self.pinned = None; + } else if let Some(pinned) = &mut self.pinned + && let Some(command) = &pinned.command + { + menu::copy_to_clipboard(command); + pinned.copied = true; + } + } +} + +/// The command a message asks to run to sign in again, like `cloofy login ytmusic`. +fn sign_in_command(text: &str) -> Option { + let start = text.find("`cloofy login")? + 1; + let end = start + text[start..].find('`')?; + Some(text[start..end].to_owned()) } /// Images are kept per URL and cell size. diff --git a/crates/cloofy-tui/src/app/persist.rs b/crates/cloofy-tui/src/app/persist.rs index e7f1a2d..f5833dc 100644 --- a/crates/cloofy-tui/src/app/persist.rs +++ b/crates/cloofy-tui/src/app/persist.rs @@ -5,7 +5,7 @@ use std::{collections::HashMap, io, time::Duration}; use cloofy_core::catalog::{AlbumInfo, PlaylistInfo}; -use super::{App, Focus, LIBRARY_PARTS, LibraryFilter}; +use super::{App, Focus, LIBRARY_PARTS, LibraryFilter, STAR_DELAY}; use crate::clock::Instant; use crate::{ backend::Service, @@ -128,6 +128,11 @@ impl App { self.prefs.crossfade = crossfade.min(12); self.save_setting(Setting::Crossfade); } + self.usage = state.usage.clone(); + self.usage.start(state::today()); + if self.usage.wants_star() { + self.ask_for_star_after(STAR_DELAY); + } self.restored_volume = state.volume; // The player starts at this volume too, so the slider can show it right away. if let Some(volume) = state.volume { @@ -277,6 +282,7 @@ impl App { last_track, volume, crossfade: None, + usage: self.usage.clone(), } } diff --git a/crates/cloofy-tui/src/backend/fake.rs b/crates/cloofy-tui/src/backend/fake.rs index 75b634b..27043ec 100644 --- a/crates/cloofy-tui/src/backend/fake.rs +++ b/crates/cloofy-tui/src/backend/fake.rs @@ -13,7 +13,7 @@ use anyhow::{Result, bail}; use cloofy_core::{ artist::ArtistPage, catalog::{AlbumInfo, ArtistInfo, Page, PlaylistInfo, SearchResults, ShowInfo, Track, User}, - home::{Home, HomeItem, ItemKind, Shelf}, + home::{Chip, Home, HomeItem, ItemKind, Shelf}, lyrics::{Lyrics, LyricsQuery}, player::{CurrentTrack, PlayerEvent, QueueTrack}, service::Service, @@ -21,7 +21,7 @@ use cloofy_core::{ use futures::stream::{self, BoxStream, StreamExt}; use tokio::sync::mpsc::UnboundedSender; -use super::{Found, Player}; +use super::{Found, Player, is_track}; use crate::{app::AppEvent, clock::Instant, playback::Repeat, views::TrackSource}; #[derive(Clone)] @@ -304,8 +304,11 @@ impl Fake { Ok(User { id: "tester".into(), name: "Tester".into() }) } - pub async fn home(&self) -> Result { - let (album, playlist) = (album(self.0.service), playlist(self.0.service)); + /// A shelf of cards, and on YouTube Music chips and Quick picks too. A chip's Home has a + /// shelf named after it. + pub async fn home(&self, chip: Option<&str>) -> Result { + let service = self.0.service; + let (album, playlist) = (album(service), playlist(service)); let item = |uri: &str, kind, title: &str| HomeItem { uri: uri.into(), kind, @@ -320,13 +323,56 @@ impl Fake { item(&playlist.uri, ItemKind::Playlist, &playlist.name), item(&album.uri, ItemKind::Album, &album.name), ]; - let shelf = Shelf { - uri: format!("{}:shelf:1", self.0.service.key()), - title: "For you".into(), - shortcuts: false, - items, + let shelf = + Shelf { uri: format!("{}:shelf:1", service.key()), title: "For you".into(), items, ..Shelf::default() }; + let greeting = format!("Hello from {}", service.name()); + if service != Service::YouTubeMusic { + return Ok(Home { greeting, shelves: vec![shelf], ..Home::default() }); + } + let chips: Vec<_> = ["Relax", "Workout"] + .into_iter() + .map(|title| Chip { + title: title.into(), + id: format!("chip-{title}"), + selected: chip == Some(&*format!("chip-{title}")), + }) + .collect(); + let songs = all_tracks(service); + let picks = Shelf { + uri: "ytmusic:shelf:Quick picks".into(), + title: "Quick picks".into(), + songs: true, + play_all: Some(format!( + "ytmusic:songs:{}", + songs.iter().map(|t| &t.uri["ytmusic:track:".len()..]).collect::>().join(",") + )), + items: songs + .iter() + .map(|t| HomeItem { + uri: format!("ytmusic:playlist:RDAMVM{}", &t.uri["ytmusic:track:".len()..]), + kind: ItemKind::Playlist, + title: t.name.clone(), + subtitle: t.artists.join(", "), + image_url: None, + owner_id: String::new(), + owner_name: String::new(), + context_uri: t.uri.clone(), + }) + .collect(), + ..Shelf::default() }; - Ok(Home { greeting: format!("Hello from {}", self.0.service.name()), shelves: vec![shelf] }) + let mut shelves = vec![picks, Shelf { strapline: "MADE FOR YOU".into(), ..shelf }]; + if let Some(chip) = chips.iter().find(|c| c.selected) { + shelves.insert( + 0, + Shelf { + uri: format!("ytmusic:shelf:{}", chip.title), + title: format!("{} mixes", chip.title), + ..shelves[1].clone() + }, + ); + } + Ok(Home { greeting, chips, shelves }) } pub async fn artist(&self, _uri: &str) -> Result { @@ -519,7 +565,12 @@ fn all_tracks(service: Service) -> Vec { } fn tracks_of(service: Service, context: &str) -> Vec { - if context == album(service).uri { + if let Some(ids) = context.strip_prefix("ytmusic:songs:") { + let all = all_tracks(service); + ids.split(',').filter_map(|id| all.iter().find(|t| t.uri == format!("ytmusic:track:{id}")).cloned()).collect() + } else if is_track(context) { + all_tracks(service).into_iter().filter(|t| t.uri == context).collect() + } else if context == album(service).uri { album_tracks(service) } else if context == playlist(service).uri { playlist_tracks(service) diff --git a/crates/cloofy-tui/src/backend/mod.rs b/crates/cloofy-tui/src/backend/mod.rs index a14db38..59bc8ff 100644 --- a/crates/cloofy-tui/src/backend/mod.rs +++ b/crates/cloofy-tui/src/backend/mod.rs @@ -474,8 +474,9 @@ impl Catalog { dispatch!(self, Catalog, catalog => catalog.me().await) } - pub async fn home(&self) -> Result { - dispatch!(self, Catalog, catalog => catalog.home().await) + /// Home, or the Home of the chip with this ID, for services with chips. + pub async fn home(&self, chip: Option<&str>) -> Result { + dispatch!(self, Catalog, catalog => catalog.home(chip).await) } pub async fn artist(&self, uri: &str) -> Result { diff --git a/crates/cloofy-tui/src/backend/spotify/mod.rs b/crates/cloofy-tui/src/backend/spotify/mod.rs index deb59fc..b2fd3c4 100644 --- a/crates/cloofy-tui/src/backend/spotify/mod.rs +++ b/crates/cloofy-tui/src/backend/spotify/mod.rs @@ -146,7 +146,7 @@ impl Catalog { Ok(user) } - pub async fn home(&self) -> Result { + pub async fn home(&self, _chip: Option<&str>) -> Result { home::home(&*self.pathfinder().await?).await } diff --git a/crates/cloofy-tui/src/backend/ytmusic/mod.rs b/crates/cloofy-tui/src/backend/ytmusic/mod.rs index e1d2608..ad68fcd 100644 --- a/crates/cloofy-tui/src/backend/ytmusic/mod.rs +++ b/crates/cloofy-tui/src/backend/ytmusic/mod.rs @@ -153,8 +153,8 @@ impl Catalog { self.client.me().await?.context("Not signed in to YouTube Music") } - pub async fn home(&self) -> Result { - self.client.home().await + pub async fn home(&self, chip: Option<&str>) -> Result { + self.client.home(chip).await } pub async fn artist(&self, uri: &str) -> Result { diff --git a/crates/cloofy-tui/src/loader.rs b/crates/cloofy-tui/src/loader.rs index 736991d..b5540bf 100644 --- a/crates/cloofy-tui/src/loader.rs +++ b/crates/cloofy-tui/src/loader.rs @@ -464,12 +464,13 @@ impl Loader { }); } - pub fn home(&self, view: u64) { + /// Home, or the Home of the chip with this ID. + pub fn home(&self, view: u64, chip: Option) { if let Some(demo) = self.demo() { return self.send_for(DataEvent::Home { view, result: Ok(demo.home.clone()) }); } self.spawn(move |this| async move { - let result = async { this.shown()?.home().await }.await; + let result = async { this.shown()?.home(chip.as_deref()).await }.await; this.send_for(DataEvent::Home { view, result: result.map_err(|e| format!("{e:#}")) }); }); } diff --git a/crates/cloofy-tui/src/overlay.rs b/crates/cloofy-tui/src/overlay.rs index 5160e24..5603d91 100644 --- a/crates/cloofy-tui/src/overlay.rs +++ b/crates/cloofy-tui/src/overlay.rs @@ -25,6 +25,10 @@ pub enum Overlay { suggestions: Vec, loading: bool, }, + /// Asks for a star on GitHub, once; `cursor` is on the star (0) or on no thanks (1). + Star { + cursor: usize, + }, } /// A row of the DJ panel. @@ -109,7 +113,7 @@ impl Overlay { Overlay::Palette(_) => Some("Command or playlist…"), Overlay::AddToPlaylist { .. } => Some("Add to which playlist?"), Overlay::Devices { .. } => Some("Transfer playback to…"), - Overlay::Menu(_) => None, + Overlay::Menu(_) | Overlay::Star { .. } => None, Overlay::Dj { .. } => Some("What should your DJ play?"), } } diff --git a/crates/cloofy-tui/src/scenarios/playback.rs b/crates/cloofy-tui/src/scenarios/playback.rs index d3ae111..550de05 100644 --- a/crates/cloofy-tui/src/scenarios/playback.rs +++ b/crates/cloofy-tui/src/scenarios/playback.rs @@ -141,3 +141,98 @@ async fn liking_a_song_saves_it() { h.fake(SPOTIFY).commands() ); } + +/// YouTube Music's Home as in its own apps: chips above, Quick picks as songs in columns that +/// play at once, and a Play all that plays them in order. +#[tokio::test] +async fn youtube_music_home_has_chips_and_quick_picks() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + assert!(h.shows(" Relax ") && h.shows("Quick picks") && h.shows("MADE FOR YOU"), "{}", h.screen()); + h.assert_screen("ytmusic_home"); + + // Down the first column, then to the next one: the song plays at once. + h.press(Down).await.press(Char('l')).await.press(Enter).await; + assert_eq!(h.fake(YOUTUBE).commands(), ["play ytmusic:track:p1-1"]); + assert!(h.player_bar().contains("YouTube Music Mix Song 1"), "{}", h.player_bar()); + + h.click_on("Play all").await; + let commands = h.fake(YOUTUBE).commands(); + assert!(commands[1].starts_with("play ytmusic:songs:a1-1,a1-2,"), "{commands:?}"); + assert!(h.player_bar().contains("YouTube Music Song 1"), "{}", h.player_bar()); +} + +#[tokio::test] +async fn a_chip_narrows_youtube_music_home_down_and_back() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + h.click_on("Workout").await; + assert!(h.shows("Workout mixes"), "{}", h.screen()); + // Up from the first shelf to the chips; Enter on the picked one shows the whole Home again. + h.press(Char('k')).await.press(Enter).await; + assert!(!h.shows("Workout mixes") && h.shows("Quick picks"), "{}", h.screen()); +} + +/// On the second day of use cloofy asks for a star on GitHub, once, a few seconds in. +#[tokio::test] +async fn the_star_on_github_is_asked_for_once() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + h.app.ask_for_star_after(Duration::from_secs(5)); + h.wait(Duration::from_secs(4)).await; + assert!(!h.shows("Enjoying cloofy?"), "not right at the start"); + h.wait(Duration::from_secs(2)).await; + assert!(h.shows("Enjoying cloofy?"), "{}", h.screen()); + assert!(h.app.usage.star_asked, "it counts as asked the moment it shows"); + h.assert_screen("star"); + + h.press(Enter).await; + assert!(!h.shows("Enjoying cloofy?")); + assert_eq!(h.app.opened, [cloofy_core::update::REPO_URL]); +} + +#[tokio::test] +async fn no_thanks_closes_the_star_for_good() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + h.app.ask_for_star_after(Duration::ZERO); + h.wait(Duration::from_millis(100)).await; + h.click_on("No thanks").await; + assert!(!h.shows("Enjoying cloofy?") && h.app.opened.is_empty()); + assert!(h.app.usage.star_asked); +} + +/// Issue #27: the expired sign-in went away after a few seconds, before anyone read it or +/// could copy the command. It stays now, under other messages, until closed. +#[tokio::test] +async fn an_expired_sign_in_stays_until_closed() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + let expired = "YouTube doesn't accept the saved sign-in any more – run `cloofy login ytmusic` again"; + h.app.error(expired.into()); + h.wait(Duration::from_secs(60)).await; + assert!(h.shows("run `cloofy login ytmusic` again") && h.shows("click to copy"), "{}", h.screen()); + + // A message in between, and the sign-in is back after it. + play_album(&mut h, YOUTUBE).await; + h.fake(YOUTUBE).send(PlayerEvent::Unavailable { uri: "ytmusic:track:a1-2".into(), refused: false }); + h.settle().await; + assert!(h.shows("A song couldn't load"), "{}", h.screen()); + h.wait(Duration::from_secs(5)).await; + assert!(h.shows("cloofy login ytmusic"), "{}", h.screen()); + + h.click_on("click to copy").await; + assert!(h.shows("copied"), "{}", h.screen()); + h.click_on("✕").await; + assert!(!h.shows("cloofy login ytmusic"), "{}", h.screen()); +} + +/// YouTube's bot check stopped every song without a word: it says so now, until music plays. +#[tokio::test] +async fn the_bot_check_says_why_nothing_plays() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + play_album(&mut h, YOUTUBE).await; + let reason = "YouTube asks this connection to prove it isn't a bot, so songs can't play for now."; + h.fake(YOUTUBE).send(PlayerEvent::Blocked { reason: reason.into() }); + h.wait(Duration::from_secs(30)).await; + assert!(h.shows("prove it isn't a bot"), "{}", h.screen()); + assert!(!h.shows("click to copy"), "there's no command to run"); + h.fake(YOUTUBE).send(PlayerEvent::Playing { position_ms: 0 }); + h.settle().await; + assert!(!h.shows("prove it isn't a bot"), "{}", h.screen()); +} diff --git a/crates/cloofy-tui/src/state.rs b/crates/cloofy-tui/src/state.rs index 74e5ca1..eddee59 100644 --- a/crates/cloofy-tui/src/state.rs +++ b/crates/cloofy-tui/src/state.rs @@ -21,6 +21,42 @@ pub struct State { pub volume: Option, /// Only in files from before settings moved to `config.toml`. pub crossfade: Option, + pub usage: Usage, +} + +/// Days of use after which cloofy asks for a star on GitHub, once. +pub const STAR_AFTER_DAYS: u32 = 2; + +/// On how many days cloofy was used, to ask for a star on GitHub once it's clearly in use. +#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Usage { + /// Days cloofy was started on. + pub days: u32, + /// The last of them, in days since 1970 (UTC). + pub last_day: u64, + /// The star was asked for. Whatever the answer, it isn't asked again. + pub star_asked: bool, +} + +impl Usage { + /// Counts a start on `today`; several starts on one day are one day of use. + pub fn start(&mut self, today: u64) { + if today != self.last_day { + self.days += 1; + self.last_day = today; + } + } + + /// Whether to ask for a star now. + pub fn wants_star(&self) -> bool { + !self.star_asked && self.days >= STAR_AFTER_DAYS + } +} + +/// Today, in days since 1970 (UTC). +pub fn today() -> u64 { + std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() / 86_400) } /// Where a service's pages were left: the open one, and the sidebar. @@ -126,6 +162,27 @@ pub fn save(path: &Path, state: &State) -> io::Result<()> { mod tests { use super::*; + #[test] + fn the_star_is_asked_for_on_the_second_day_of_use_once() { + let mut usage = Usage::default(); + for _ in 0..3 { + usage.start(100); + } + assert_eq!(usage.days, 1, "several starts on one day count once"); + assert!(!usage.wants_star(), "not on the day cloofy is tried"); + usage.start(103); + assert!(usage.wants_star()); + usage.star_asked = true; + usage.start(111); + assert!(!usage.wants_star()); + } + + #[test] + fn a_file_from_before_the_star_counts_from_zero() { + let state: State = serde_json::from_str(r#"{"view":{"kind":"home"},"volume":3}"#).unwrap(); + assert_eq!(state.usage, Usage::default()); + } + #[test] fn a_file_from_before_youtube_music_holds_the_page_of_its_one_service() { let old = r#"{"view":{"kind":"artist","uri":"spotify:artist:1","name":"Daft Punk"}, diff --git a/crates/cloofy-tui/src/ui/artist.rs b/crates/cloofy-tui/src/ui/artist.rs index 601adcd..8e228b2 100644 --- a/crates/cloofy-tui/src/ui/artist.rs +++ b/crates/cloofy-tui/src/ui/artist.rs @@ -119,7 +119,11 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { index: track_count + index, y, title: shelf.title.clone(), + // Artist pages keep every shelf the same height: cards, without a strapline. + strapline: String::new(), shortcuts: false, + songs: false, + play_all: false, total: shelf.items.len(), first, items: shelf.items.iter().skip(first).take(cards).cloned().collect(), diff --git a/crates/cloofy-tui/src/ui/hints.rs b/crates/cloofy-tui/src/ui/hints.rs index 20479c9..a195799 100644 --- a/crates/cloofy-tui/src/ui/hints.rs +++ b/crates/cloofy-tui/src/ui/hints.rs @@ -5,7 +5,7 @@ use ratatui::{buffer::Buffer, layout::Rect, style::Style, text::Span}; use unicode_width::UnicodeWidthStr; use crate::{ - app::{App, Focus, HintAction, Hit}, + app::{App, Focus, HintAction, Hit, Pinned}, commands::Command, icons::icons, theme, @@ -40,6 +40,9 @@ pub fn draw(buf: &mut Buffer, app: &mut App, area: Rect) { buf.set_string(area.x + 2, area.y, text, Style::new().fg(color)); return; } + if let Some(pinned) = app.pinned.clone() { + return draw_pinned(buf, app, Rect { width, ..area }, &pinned); + } let mut x = area.x + 2; // Without the commands for what the service lacks, like DJ. @@ -60,6 +63,30 @@ pub fn draw(buf: &mut Buffer, app: &mut App, area: Rect) { } } +/// A problem that stays until it's solved: its text, a button that copies the command that +/// solves it, and a cross that closes it. +fn draw_pinned(buf: &mut Buffer, app: &mut App, area: Rect, pinned: &Pinned) { + let p = theme::palette(); + let close = " ✕".to_owned(); + let copy = match (&pinned.command, pinned.copied) { + (None, _) => String::new(), + (Some(_), false) => " click to copy".to_owned(), + (Some(_), true) => " copied".to_owned(), + }; + let room = (area.width as usize).saturating_sub(2 + copy.width() + close.width()); + let text = crate::ui::text::truncate(&pinned.text, room); + let x = area.x + 2; + buf.set_string(x, area.y, &text, Style::new().fg(p.danger)); + let copy_x = x + text.width() as u16; + buf.set_string(copy_x, area.y, ©, Style::new().fg(if pinned.copied { app.accent.color() } else { p.muted })); + if pinned.command.is_some() { + app.hits.push((Rect::new(x, area.y, text.width() as u16 + copy.width() as u16, 1), Hit::PinnedCopy)); + } + let close_x = copy_x + copy.width() as u16; + buf.set_string(close_x, area.y, &close, Style::new().fg(p.muted)); + app.hits.push((Rect::new(close_x + 1, area.y, close.width() as u16, 1), Hit::PinnedClose)); +} + fn hints(app: &App) -> &'static [Hint] { use Command::*; use HintAction::{Activate, Back, Key, Run, ToggleFocus}; @@ -104,6 +131,24 @@ fn hints(app: &App) -> &'static [Hint] { ("^K", "commands", Some(Run(Palette))), ("?", "help", Some(Run(Help))), ], + (Focus::Content, View::Home(v)) if v.chip.is_some() => &[ + ("enter", "pick", Some(Activate)), + ("← →", "chips", Some(Key(KeyCode::Right))), + ("↓", "shelves", Some(Key(KeyCode::Down))), + ("S", "switch service", Some(Run(SwitchService))), + ("/", "search", Some(Run(Search))), + ("^K", "commands", Some(Run(Palette))), + ("?", "help", Some(Run(Help))), + ], + // A song plays at once. + (Focus::Content, View::Home(v)) if v.selected().is_some_and(|item| item.is_song()) => &[ + ("enter", "play", Some(Activate)), + (".", "actions", Some(Run(Menu))), + ("S", "switch service", Some(Run(SwitchService))), + ("/", "search", Some(Run(Search))), + ("^K", "commands", Some(Run(Palette))), + ("?", "help", Some(Run(Help))), + ], (Focus::Content, View::Home(_)) => &[ ("enter", "open", Some(Activate)), ("p", "play", Some(Key(KeyCode::Char('p')))), diff --git a/crates/cloofy-tui/src/ui/home.rs b/crates/cloofy-tui/src/ui/home.rs index d38153b..6450ddf 100644 --- a/crates/cloofy-tui/src/ui/home.rs +++ b/crates/cloofy-tui/src/ui/home.rs @@ -1,18 +1,19 @@ -//! Home: a greeting, the shortcut grid and shelves of cover cards. +//! Home: a greeting or chips, the shortcut grid, and shelves of cover cards or of songs. -use cloofy_core::home::{HomeItem, ItemKind, Shelf}; +use cloofy_core::home::{Chip, HomeItem, ItemKind, Shelf}; use ratatui::{ Frame, layout::{Rect, Size}, style::{Color, Style}, text::{Line, Span}, }; +use unicode_width::UnicodeWidthStr; use super::{text, wordmark}; use crate::{ app::{App, Focus, Hit}, theme, - views::View, + views::{self, SONG_ROWS, View}, }; /// Card cover in cells; cells are about twice as tall as wide, so this is roughly square. @@ -22,6 +23,15 @@ const CARD_GAP: u16 = 3; pub(super) const SHELF_ROWS: u16 = 1 + 1 + 7 + 2 + 2; const TILE_COVER: Size = Size { width: 6, height: 3 }; const TILE_GAP: u16 = 2; +/// A song's cover in a shelf of songs, as in the sidebar. +const SONG_COVER: Size = Size { width: 4, height: 2 }; +/// Narrowest column of songs, and the room between columns. +const SONG_WIDTH: u16 = 30; +const SONG_GAP: u16 = 3; +/// Title, gap, the songs two rows each with a row between them, and spacing below. +const SONGS_ROWS: u16 = 1 + 1 + SONG_ROWS as u16 * 3 - 1 + 2; +/// The Play all button in a shelf's title row. +const PLAY_ALL: &str = "Play all"; /// What one shelf needs for drawing, copied out of the view. pub(super) struct ShelfLayout { @@ -30,7 +40,10 @@ pub(super) struct ShelfLayout { /// Screen row of the title; may lie above the visible area while scrolling. pub y: i32, pub title: String, + pub strapline: String, pub shortcuts: bool, + pub songs: bool, + pub play_all: bool, pub total: usize, /// Index of the first visible card. pub first: usize, @@ -44,6 +57,11 @@ pub(super) fn visible_cards(width: u16) -> usize { ((width + CARD_GAP) / (COVER.width + CARD_GAP)).max(1) as usize } +/// How many columns of songs fit next to each other. +fn song_columns(width: u16) -> usize { + ((width + SONG_GAP) / (SONG_WIDTH + SONG_GAP)).max(1) as usize +} + /// Cover URLs, and whether they are round, of the pages left and right of the `cards` items /// from `first`. Loading them ahead lets paging show the next cards at once. pub(super) fn nearby(items: &[HomeItem], first: usize, cards: usize) -> Vec<(Option, bool)> { @@ -106,7 +124,7 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { return; }; - // Everything scrolls together, greeting included; positions are rows from the top. + // Everything scrolls together, greeting or chips included; positions are rows from the top. let heights: Vec = home.shelves.iter().map(|s| shelf_height(s, inner.width)).collect(); let mut starts = Vec::with_capacity(heights.len()); let mut total: u16 = 2; @@ -115,7 +133,9 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { total += height; } let viewport = inner.height; - if !view.detached && !heights.is_empty() { + if view.chip.is_some() && !view.detached { + view.scroll = 0; + } else if !view.detached && !heights.is_empty() { let shelf = view.shelf.min(heights.len() - 1); let top = if shelf == 0 { 0 } else { starts[shelf] }; let bottom = starts[shelf] + heights[shelf].saturating_sub(2); @@ -129,18 +149,32 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { view.scroll = view.scroll.min(total.saturating_sub(viewport)); let scroll = view.scroll; + let mut chip_hits = Vec::new(); if scroll == 0 { - let greeting = if home.greeting.is_empty() { "Hello".to_owned() } else { home.greeting.clone() }; - let mut spans = vec![Span::styled(greeting, Style::new().fg(p.text).bold())]; - if view.loading { - spans.push(Span::styled(format!(" {}", text::spinner(frame_no)), p.faint)); + let spinner = view.loading.then(|| Span::styled(format!(" {}", text::spinner(frame_no)), p.faint)); + if home.chips.is_empty() { + let greeting = if home.greeting.is_empty() { "Hello".to_owned() } else { home.greeting.clone() }; + let mut spans = vec![Span::styled(greeting, Style::new().fg(p.text).bold())]; + spans.extend(spinner); + frame.buffer_mut().set_line(inner.x, inner.y, &Line::from(spans), inner.width); + } else { + let cursor = view.chip.filter(|_| focused); + let room = inner.width.saturating_sub(if spinner.is_some() { 4 } else { 0 }); + let (hits, end) = + chips(frame, app.accent.color(), app.accent.selection(), inner, room, &home.chips, cursor); + chip_hits = hits; + if let Some(spinner) = spinner { + frame.buffer_mut().set_span(end, inner.y, &spinner, 4); + } } - frame.buffer_mut().set_line(inner.x, inner.y, &Line::from(spans), inner.width); } view.offsets.resize(home.shelves.len(), 0); let cards = visible_cards(inner.width); + let columns = song_columns(inner.width); view.cards = cards; + view.columns = columns; + let on_shelf = view.chip.is_none(); let mut layouts = Vec::new(); // The first page of the shelf below the screen, so scrolling down finds it loaded. let mut below = Vec::new(); @@ -149,10 +183,12 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { if y + heights[index] as i32 <= inner.y as i32 { continue; } + let page = if shelf.songs { columns * SONG_ROWS } else { cards }; + let size = if shelf.songs { SONG_COVER } else { COVER }; if y >= inner.bottom() as i32 { if !shelf.shortcuts { let first = view.offsets[index]; - below.extend(shelf.items.iter().skip(first).take(cards).map(cover_of)); + below.extend(shelf.items.iter().skip(first).take(page).map(|item| (cover_of(item), size))); } break; } @@ -160,33 +196,48 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { 0 } else { let offset = &mut view.offsets[index]; - if index == view.shelf { - follow(offset, view.item, cards); + if index == view.shelf && on_shelf { + if shelf.songs { + views::follow_songs(offset, view.item, columns); + } else { + follow(offset, view.item, cards); + } } - *offset = (*offset).min(shelf.items.len().saturating_sub(cards)); + let last_page = if shelf.songs { + shelf.items.len().div_ceil(SONG_ROWS).saturating_sub(columns) * SONG_ROWS + } else { + shelf.items.len().saturating_sub(cards) + }; + *offset = (*offset).min(last_page); *offset }; - let count = if shelf.shortcuts { shelf.items.len() } else { cards }; + let count = if shelf.shortcuts { shelf.items.len() } else { page }; layouts.push(ShelfLayout { index, y, title: shelf.title.clone(), + strapline: shelf.strapline.clone(), shortcuts: shelf.shortcuts, + songs: shelf.songs, + play_all: shelf.play_all.is_some(), total: shelf.items.len(), first, items: shelf.items.iter().skip(first).take(count).cloned().collect(), - nearby: if shelf.shortcuts { Vec::new() } else { nearby(&shelf.items, first, cards) }, + nearby: if shelf.shortcuts { Vec::new() } else { nearby(&shelf.items, first, page) }, }); } - let selected = (view.shelf, view.item); - for (url, round) in below { - app.prefetch(url.as_deref(), COVER, round); + let selected = (view.shelf, view.item, on_shelf); + app.hits.extend(chip_hits); + for ((url, round), size) in below { + app.prefetch(url.as_deref(), size, round); } for layout in layouts { - let selected_item = (selected.0 == layout.index).then_some(selected.1); + let selected_item = (selected.0 == layout.index && selected.2).then_some(selected.1); if layout.shortcuts { draw_shortcuts(frame, app, inner, &layout, selected_item, focused); + } else if layout.songs { + draw_songs(frame, app, inner, &layout, selected_item, focused); } else { draw_shelf(frame, app, inner, &layout, selected_item, focused); } @@ -202,6 +253,50 @@ pub fn draw(frame: &mut Frame, app: &mut App, area: Rect) { ); } +/// The chips in the top row of `area`, within `room` columns, scrolled so the one under the +/// cursor shows. Returns where they are, and the column after the last one drawn. +fn chips( + frame: &mut Frame, + accent: Color, + selection: Color, + area: Rect, + room: u16, + chips: &[Chip], + cursor: Option, +) -> (Vec<(Rect, Hit)>, u16) { + const GAP: u16 = 1; + let p = theme::palette(); + let widths: Vec = chips.iter().map(|c| c.title.width() as u16 + 2).collect(); + let right = area.x + room; + // Start as far left as possible while the chip under the cursor still fits. + let mut start = 0; + if let Some(cursor) = cursor.filter(|&c| c < chips.len()) { + while start < cursor && widths[start..=cursor].iter().map(|w| w + GAP).sum::() > room { + start += 1; + } + } + let mut hits = Vec::new(); + let mut x = area.x; + let buf = frame.buffer_mut(); + for (index, chip) in chips.iter().enumerate().skip(start) { + let width = widths[index]; + if x + width > right { + break; + } + let under_cursor = cursor == Some(index); + let style = match (chip.selected, under_cursor) { + (true, true) => Style::new().fg(p.bg).bg(accent).bold().underlined(), + (true, false) => Style::new().fg(p.bg).bg(accent).bold(), + (false, true) => Style::new().fg(p.text).bg(selection).bold(), + (false, false) => Style::new().fg(p.text).bg(p.raised), + }; + buf.set_string(x, area.y, format!(" {} ", chip.title), style); + hits.push((Rect::new(x, area.y, width, 1), Hit::HomeChip(index))); + x += width + GAP; + } + (hits, x) +} + /// The wordmark with a status line, while Home loads for the first time. fn splash(frame: &mut Frame, app: &mut App, area: Rect, message: Span<'static>) { let top = area.y + area.height.saturating_sub(wordmark::HEIGHT + 3) / 2; @@ -212,12 +307,17 @@ fn splash(frame: &mut Frame, app: &mut App, area: Rect, message: Span<'static>) } fn shelf_height(shelf: &Shelf, width: u16) -> u16 { + let strapline = u16::from(!shelf.strapline.is_empty()); if shelf.shortcuts { let columns = shortcut_columns(width); let rows = shelf.items.len().div_ceil(columns as usize) as u16; rows * (TILE_COVER.height + 1) + 1 + } else if shelf.songs { + // A short shelf of songs is only as tall as its longest column. + let rows = shelf.items.len().clamp(1, SONG_ROWS) as u16; + strapline + SONGS_ROWS - (SONG_ROWS as u16 - rows) * 3 } else { - SHELF_ROWS + strapline + SHELF_ROWS } } @@ -254,36 +354,9 @@ pub(super) fn draw_shelf( app.prefetch(url.as_deref(), COVER, *round); } let marker = playing_marker(app); - if let Some(y) = row(area, layout.y) { - let pageable = layout.total > layout.items.len(); - let title_width = area.width.saturating_sub(if pageable { 28 } else { 2 }) as usize; - let buf = frame.buffer_mut(); - buf.set_string(area.x, y, text::truncate(&layout.title, title_width), Style::new().fg(p.text).bold()); - if pageable { - let last = layout.first + layout.items.len(); - let pager = format!("{}–{} of {}", layout.first + 1, last, layout.total); - let style = if selected.is_some() { Style::new().fg(p.muted) } else { Style::new().fg(p.faint) }; - let next_x = area.right().saturating_sub(2); - let prev_x = next_x.saturating_sub(4); - buf.set_string(prev_x.saturating_sub(pager.chars().count() as u16 + 3), y, pager, style); - let icons = crate::icons::icons(); - let arrows = [ - (prev_x, icons.chevron_left, false, layout.first > 0), - (next_x, icons.chevron_right, true, last < layout.total), - ]; - for (x, icon, forward, enabled) in arrows { - let arrow = Rect::new(x.saturating_sub(1), y, 3, 1); - let color = if enabled { p.text } else { p.disabled }; - buf.set_style(arrow, Style::new().bg(p.raised)); - buf.set_string(x, y, icon, Style::new().fg(color)); - if enabled { - app.hits.push((arrow, Hit::ShelfScroll { shelf: layout.index, forward })); - } - } - } - } + let top = header(frame, app, area, layout, selected.is_some()); - let cover_y = layout.y + 2; + let cover_y = top + 2; // A card's box reaches one column past its cover on both sides, the first card's too. let padded = Rect { x: area.x.saturating_sub(1), width: area.width + 2, ..area }; let slots = visible_cards(area.width); @@ -325,6 +398,127 @@ pub(super) fn draw_shelf( } } +/// A shelf's strapline and title, with Play all and the arrows that page it where it has +/// them. Returns the row of the title. +fn header(frame: &mut Frame, app: &mut App, area: Rect, layout: &ShelfLayout, selected: bool) -> i32 { + let p = theme::palette(); + let mut y = layout.y; + if !layout.strapline.is_empty() { + if let Some(row) = row(area, y) { + let strapline = text::truncate(&layout.strapline, area.width as usize); + frame.buffer_mut().set_string(area.x, row, strapline, Style::new().fg(p.muted)); + } + y += 1; + } + let Some(title_y) = row(area, y) else { return y }; + let pageable = layout.total > layout.items.len(); + let play_all_width = if layout.play_all { PLAY_ALL.len() as u16 + 4 } else { 0 }; + let reserved = if pageable { 28 } else { 2 } + play_all_width; + let title_width = area.width.saturating_sub(reserved) as usize; + let buf = frame.buffer_mut(); + buf.set_string(area.x, title_y, text::truncate(&layout.title, title_width), Style::new().fg(p.text).bold()); + let mut right = area.right(); + if pageable { + let last = layout.first + layout.items.len(); + let pager = format!("{}–{} of {}", layout.first + 1, last, layout.total); + let style = if selected { Style::new().fg(p.muted) } else { Style::new().fg(p.faint) }; + let next_x = area.right().saturating_sub(2); + let prev_x = next_x.saturating_sub(4); + right = prev_x.saturating_sub(pager.chars().count() as u16 + 3); + buf.set_string(right, title_y, pager, style); + let icons = crate::icons::icons(); + let arrows = [ + (prev_x, icons.chevron_left, false, layout.first > 0), + (next_x, icons.chevron_right, true, last < layout.total), + ]; + for (x, icon, forward, enabled) in arrows { + let arrow = Rect::new(x.saturating_sub(1), title_y, 3, 1); + let color = if enabled { p.text } else { p.disabled }; + buf.set_style(arrow, Style::new().bg(p.raised)); + buf.set_string(x, title_y, icon, Style::new().fg(color)); + if enabled { + app.hits.push((arrow, Hit::ShelfScroll { shelf: layout.index, forward })); + } + } + } + if layout.play_all { + let width = play_all_width - 1; + let x = right.saturating_sub(width + 2); + let button = Rect::new(x, title_y, width, 1); + let hovered = super::hovered(app, button); + let style = if hovered { Style::new().fg(p.bg).bg(p.text) } else { Style::new().fg(p.text).bg(p.raised) }; + let buf = frame.buffer_mut(); + buf.set_string(x, title_y, format!(" {} {PLAY_ALL} ", crate::icons::icons().play), style); + app.hits.push((button, Hit::ShelfPlay(layout.index))); + } + y +} + +/// A titled shelf of songs in columns of [`SONG_ROWS`], like YouTube Music's Quick picks: +/// a small cover, the title and the artists. `selected` is the song under the cursor. +fn draw_songs( + frame: &mut Frame, + app: &mut App, + area: Rect, + layout: &ShelfLayout, + selected: Option, + focused: bool, +) { + let p = theme::palette(); + let accent = app.accent.color(); + let selection = if focused { app.accent.selection() } else { p.unfocused }; + for (url, round) in &layout.nearby { + app.prefetch(url.as_deref(), SONG_COVER, *round); + } + let marker = playing_marker(app); + let top = header(frame, app, area, layout, selected.is_some()); + let columns = song_columns(area.width); + let width = (area.width.saturating_sub(SONG_GAP * (columns as u16 - 1))) / columns as u16; + let padded = Rect { x: area.x.saturating_sub(1), width: area.width + 2, ..area }; + for (position, item) in layout.items.iter().enumerate() { + let (column, line) = ((position / SONG_ROWS) as u16, (position % SONG_ROWS) as i32); + let x = area.x + column * (width + SONG_GAP); + let y = top + 2 + line * 3; + let index = layout.first + position; + let is_selected = selected == Some(index); + let Some(cell) = clip(padded, x.saturating_sub(1), width + 2, y, SONG_COVER.height) else { continue }; + if is_selected { + frame.buffer_mut().set_style(cell, Style::new().bg(selection)); + } + draw_cover(frame, app, (x, y), area, item, SONG_COVER); + let playing = app.now.track.as_ref().is_some_and(|track| track.uri == item.context_uri); + let hovered = super::hovered(app, cell); + let text_x = x + SONG_COVER.width + 2; + let reserved = SONG_COVER.width + + 2 + + if hovered { + super::PLAY_BUTTON_WIDTH + 1 + } else if playing { + 4 + } else { + 0 + }; + let room = width.saturating_sub(reserved) as usize; + let buf = frame.buffer_mut(); + if let Some(row) = row(area, y) { + let style = card_title_style(accent, playing, is_selected); + buf.set_string(text_x, row, text::truncate(&item.title, room), style); + if playing && !hovered { + buf.set_string(x + width - 3, row, marker, Style::new().fg(accent)); + } + } + if let Some(row) = row(area, y + 1) { + let room = width.saturating_sub(SONG_COVER.width + 2) as usize; + buf.set_string(text_x, row, text::truncate(&item.subtitle, room), Style::new().fg(p.muted)); + } + app.hits.push((cell, Hit::Card { shelf: layout.index, item: index })); + if hovered && let Some(row) = row(area, y) { + let hit = Hit::CardPlay { shelf: layout.index, item: index }; + super::play_button(frame.buffer_mut(), app, x + width, row, hit, false); + } + } +} + fn draw_shortcuts( frame: &mut Frame, app: &mut App, diff --git a/crates/cloofy-tui/src/ui/mod.rs b/crates/cloofy-tui/src/ui/mod.rs index 3aaedab..57ca385 100644 --- a/crates/cloofy-tui/src/ui/mod.rs +++ b/crates/cloofy-tui/src/ui/mod.rs @@ -9,6 +9,7 @@ mod picker; mod player_bar; mod settings; mod sidebar; +mod star; mod text; mod topbar; mod wordmark; @@ -96,6 +97,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) { match &app.overlay { Some(Overlay::Help) => help::draw(frame.buffer_mut(), app, area), Some(Overlay::Menu(_)) => menu::draw(frame.buffer_mut(), app, area), + Some(Overlay::Star { .. }) => star::draw(frame.buffer_mut(), app, area), Some(_) => picker::draw(frame, app, area), None => {} } diff --git a/crates/cloofy-tui/src/ui/picker.rs b/crates/cloofy-tui/src/ui/picker.rs index 7ad6914..315f63f 100644 --- a/crates/cloofy-tui/src/ui/picker.rs +++ b/crates/cloofy-tui/src/ui/picker.rs @@ -41,13 +41,13 @@ pub fn draw(frame: &mut Frame, app: &mut App, screen: Rect) { Overlay::Palette(picker) => (picker.query.clone(), rows(picker)), Overlay::AddToPlaylist { picker, .. } | Overlay::Devices { picker, .. } => (picker.query.clone(), rows(picker)), Overlay::Dj { picker, .. } => (picker.query.clone(), rows(picker)), - Overlay::Help | Overlay::Menu(_) => return, + Overlay::Help | Overlay::Menu(_) | Overlay::Star { .. } => return, }; let cursor = match overlay { Overlay::Palette(picker) => &mut picker.cursor, Overlay::AddToPlaylist { picker, .. } | Overlay::Devices { picker, .. } => &mut picker.cursor, Overlay::Dj { picker, .. } => &mut picker.cursor, - Overlay::Help | Overlay::Menu(_) => return, + Overlay::Help | Overlay::Menu(_) | Overlay::Star { .. } => return, }; // Pickers with covers use two-line rows: name and detail next to a thumbnail. Windows too // short for even one of them get plain rows. diff --git a/crates/cloofy-tui/src/ui/star.rs b/crates/cloofy-tui/src/ui/star.rs new file mode 100644 index 0000000..d35062b --- /dev/null +++ b/crates/cloofy-tui/src/ui/star.rs @@ -0,0 +1,70 @@ +//! Asks for a star on GitHub, once cloofy is clearly in use: a short note and two buttons. + +use ratatui::{ + buffer::Buffer, + layout::{Constraint, Rect}, + style::{Style, Stylize}, + text::Line, + widgets::{Block, BorderType, Clear, Paragraph, Widget, Wrap}, +}; +use unicode_width::UnicodeWidthStr; + +use crate::{ + app::{App, Hit}, + overlay::Overlay, + theme, +}; + +const WIDTH: u16 = 54; +const HEIGHT: u16 = 10; +/// A star that every terminal font has. +const STAR_ICON: &str = "★"; +const NOTE: &str = "cloofy is free and made in spare time. If you like it, a star on GitHub helps \ + other people find it."; +/// The two buttons, in the order the cursor goes through them. +pub const STAR: &str = "Star on GitHub"; +pub const NO_THANKS: &str = "No thanks"; + +pub fn draw(buf: &mut Buffer, app: &mut App, area: Rect) { + let p = theme::palette(); + let Some(Overlay::Star { cursor }) = app.overlay else { return }; + let popup = area.centered(Constraint::Length(WIDTH.min(area.width)), Constraint::Length(HEIGHT.min(area.height))); + Clear.render(popup, buf); + Block::bordered() + .border_type(BorderType::Rounded) + .border_style(Style::new().fg(p.faint)) + .title(Line::from(format!(" {STAR_ICON} Enjoying cloofy? ")).fg(p.text).bold()) + .style(Style::new().bg(p.raised)) + .render(popup, buf); + app.hits.push((popup, Hit::OverlayArea)); + + let inner = Rect { x: popup.x + 3, y: popup.y + 2, width: popup.width.saturating_sub(6), height: 3 }; + Paragraph::new(NOTE).wrap(Wrap { trim: true }).style(Style::new().fg(p.muted)).render(inner, buf); + + let y = popup.y + 6; + if y >= popup.bottom().saturating_sub(1) { + return; + } + let labels = [format!(" {STAR_ICON} {STAR} "), format!(" {NO_THANKS} ")]; + let widths: Vec = labels.iter().map(|label| label.width() as u16).collect(); + let total = widths.iter().sum::() + 3; + let mut x = popup.x + popup.width.saturating_sub(total) / 2; + let accent = app.accent.color(); + for (index, label) in labels.iter().enumerate() { + let button = Rect::new(x, y, widths[index], 1).intersection(popup); + let style = if index == cursor { + Style::new().fg(p.bg).bg(accent).bold() + } else { + Style::new().fg(p.text).bg(p.unfocused) + }; + buf.set_string(button.x, y, label, style); + app.hits.push((button, Hit::OverlayItem(index))); + x += widths[index] + 3; + } + let hint = "enter choose · esc close"; + let hint_x = popup.x + popup.width.saturating_sub(hint.width() as u16) / 2; + buf.set_string(hint_x, y + 2, hint, Style::new().fg(p.faint)); + if app.overlay_fx_pending { + app.animate_overlay(popup); + } +} diff --git a/crates/cloofy-tui/src/views.rs b/crates/cloofy-tui/src/views.rs index f25d01b..a1f4bb7 100644 --- a/crates/cloofy-tui/src/views.rs +++ b/crates/cloofy-tui/src/views.rs @@ -3,7 +3,7 @@ use std::{collections::HashMap, ops::Range}; use cloofy_core::{ artist::{ArtistPage, TopTrack}, catalog::{AlbumInfo, ArtistInfo, PlaylistInfo, SearchResults, Track}, - home::{Home, HomeItem}, + home::{Chip, Home, HomeItem}, }; use crate::clock::Instant; @@ -327,18 +327,27 @@ impl QueueView { } } -/// The Home feed: shelves of cards, navigated in two dimensions. +/// Songs per column of a shelf of songs, like YouTube Music's Quick picks. +pub const SONG_ROWS: usize = 4; + +/// The Home feed: chips, then shelves of cards or songs, navigated in two dimensions. pub struct HomeView { pub id: u64, pub home: Option, pub loading: bool, pub error: Option, + /// The cursor is on the chips above the shelves, at this one. + pub chip: Option, + /// The chip whose Home is shown or on its way; `None` for the whole Home. + pub filter: Option, pub shelf: usize, pub item: usize, - /// First visible card per shelf. + /// First visible card or song per shelf. pub offsets: Vec, /// Cards that fit next to each other at the last draw. pub cards: usize, + /// Columns of songs that fit next to each other at the last draw. + pub columns: usize, /// Vertical scroll in rows. pub scroll: u16, /// Scrolled with the mouse: the view stays put instead of following the selection. @@ -354,18 +363,47 @@ fn page_shelf(offset: &mut usize, len: usize, cards: usize, delta: isize, item: } } +/// Pages a shelf of `len` songs sideways by `delta` columns of `columns` visible. The offset +/// stays at the top of a column; a selected song moves along in its row. +fn page_songs(offset: &mut usize, len: usize, columns: usize, delta: isize, item: Option<&mut usize>) { + let mut column = *offset / SONG_ROWS; + let selected = item.as_ref().map(|item| (**item / SONG_ROWS, **item % SONG_ROWS)); + let mut selected_column = selected.map(|(column, _)| column); + page_shelf(&mut column, len.div_ceil(SONG_ROWS), columns, delta, selected_column.as_mut()); + *offset = column * SONG_ROWS; + if let (Some(item), Some(column), Some((_, row))) = (item, selected_column, selected) { + *item = (column * SONG_ROWS + row).min(len.saturating_sub(1)); + } +} + +/// Scrolls a shelf of songs sideways so the column of the selected song stays visible. +pub fn follow_songs(offset: &mut usize, item: usize, columns: usize) { + let mut column = *offset / SONG_ROWS; + let selected = item / SONG_ROWS; + if selected < column { + column = selected; + } else if selected >= column + columns.max(1) { + column = selected + 1 - columns.max(1); + } + *offset = column * SONG_ROWS; +} + impl HomeView { pub fn new(id: u64, cached: Option) -> Self { let offsets = cached.as_ref().map_or_else(Vec::new, |home| vec![0; home.shelves.len()]); + let filter = cached.as_ref().and_then(Home::chip).cloned(); Self { id, home: cached, loading: true, error: None, + chip: None, + filter, shelf: 0, item: 0, offsets, cards: 1, + columns: 1, scroll: 0, detached: false, } @@ -376,11 +414,33 @@ impl HomeView { self.detached = true; } + /// The chips above the shelves. + pub fn chips(&self) -> &[Chip] { + self.home.as_ref().map_or(&[], |home| &home.chips) + } + + /// Whether shelf `shelf` shows songs in columns rather than cards. + pub fn is_songs(&self, shelf: usize) -> bool { + self.home.as_ref().and_then(|h| h.shelves.get(shelf)).is_some_and(|s| s.songs) + } + + /// How far the arrows of a shelf page it: the columns of songs or the cards that fit. + pub fn visible(&self, shelf: usize) -> usize { + if self.is_songs(shelf) { self.columns } else { self.cards } + } + + /// Pages a shelf sideways by `delta` cards, or columns of songs. pub fn scroll_shelf(&mut self, shelf: usize, delta: isize) { let Some(home) = &self.home else { return }; - let Some(len) = home.shelves.get(shelf).filter(|s| !s.shortcuts).map(|s| s.items.len()) else { return }; + let Some(shelf_ref) = home.shelves.get(shelf).filter(|s| !s.shortcuts) else { return }; + let (len, songs) = (shelf_ref.items.len(), shelf_ref.songs); let Some(offset) = self.offsets.get_mut(shelf) else { return }; - page_shelf(offset, len, self.cards, delta, (self.shelf == shelf).then_some(&mut self.item)); + let item = (self.shelf == shelf && self.chip.is_none()).then_some(&mut self.item); + if songs { + page_songs(offset, len, self.columns, delta, item); + } else { + page_shelf(offset, len, self.cards, delta, item); + } } /// Shows a newer Home. Shelves and cards are found again by URI, so the selection and @@ -403,33 +463,115 @@ impl HomeView { home.shelves[shelf].items.iter().position(|i| Some(i.uri.as_str()) == card).unwrap_or(self.item); self.shelf = shelf; } + self.filter = home.chip().cloned(); self.home = Some(home); self.loading = false; self.error = None; self.clamp(); } + /// Whether `home` is the one this view waits for: the whole Home, or that of its chip. + /// One that arrives after another chip was picked is not. + pub fn wants(&self, home: &Home) -> bool { + home.chip().map(|c| &c.title) == self.filter.as_ref().map(|c| &c.title) + } + + /// Narrows Home to chip `index`, or back to the whole Home when that chip is picked + /// already. Returns the ID of the chip to load Home for, `None` for the whole Home. + pub fn pick_chip(&mut self, index: usize) -> Option> { + let home = self.home.as_mut()?; + let chip = home.chips.get(index)?.clone(); + let picked = !chip.selected; + for (i, c) in home.chips.iter_mut().enumerate() { + c.selected = picked && i == index; + } + self.filter = picked.then(|| Chip { selected: true, ..chip.clone() }); + self.chip = Some(index); + self.loading = true; + self.error = None; + Some(picked.then_some(chip.id)) + } + pub fn selected(&self) -> Option<&HomeItem> { + if self.chip.is_some() { + return None; + } self.home.as_ref()?.shelves.get(self.shelf)?.items.get(self.item) } + /// Moves up or down: within a column of songs, from shelf to shelf, and from the first + /// shelf up to the chips. pub fn move_shelf(&mut self, delta: isize) { self.detached = false; - let shelves = self.home.as_ref().map_or(0, |h| h.shelves.len()); - if shelves > 0 { - self.shelf = (self.shelf as isize + delta).clamp(0, shelves as isize - 1) as usize; - self.clamp(); + let Some(home) = &self.home else { return }; + let shelves = home.shelves.len(); + if self.chip.is_some() { + if delta > 0 && shelves > 0 { + self.chip = None; + self.shelf = 0; + self.item = self.offsets.first().copied().unwrap_or(0); + self.clamp(); + // Further down, as to the last shelf, goes on from the first. + if delta > 1 { + self.move_shelf(delta - 1); + } + } + return; + } + if shelves == 0 { + return; } + if self.is_songs(self.shelf) && delta.abs() == 1 { + let len = home.shelves[self.shelf].items.len(); + let row = self.item % SONG_ROWS; + if delta > 0 && row + 1 < SONG_ROWS && self.item + 1 < len { + self.item += 1; + return; + } + if delta < 0 && row > 0 { + self.item -= 1; + return; + } + } + if delta == -1 && self.shelf == 0 && !home.chips.is_empty() { + self.chip = Some(home.chips.iter().position(|c| c.selected).unwrap_or(0)); + return; + } + let from = self.shelf; + self.shelf = (self.shelf as isize + delta).clamp(0, shelves as isize - 1) as usize; + if self.shelf != from && (self.is_songs(from) || self.is_songs(self.shelf)) { + // Into or out of columns of songs, the cursor lands on what shows first, at the + // top of a column, or its bottom when coming from below. + let offset = self.offsets.get(self.shelf).copied().unwrap_or(0); + let bottom = if self.is_songs(self.shelf) && delta < 0 { SONG_ROWS - 1 } else { 0 }; + self.item = offset + bottom; + } + self.clamp(); } - /// Moves within the current shelf. Returns `false` at the left edge, so the caller can - /// hand focus to the sidebar. + /// Moves within the current shelf, or along the chips. Returns `false` at the left edge, + /// so the caller can hand focus to the sidebar. pub fn move_item(&mut self, delta: isize) -> bool { - if delta < 0 && self.item == 0 { + if let Some(chip) = self.chip { + if delta < 0 && chip == 0 { + return false; + } + let last = self.chips().len().saturating_sub(1); + self.chip = Some((chip as isize + delta).clamp(0, last as isize) as usize); + return true; + } + let step = if self.is_songs(self.shelf) { SONG_ROWS as isize } else { 1 }; + if delta < 0 && self.item < step as usize { return false; } self.detached = false; - self.item = (self.item as isize + delta).max(0) as usize; + let len = self.home.as_ref().and_then(|h| h.shelves.get(self.shelf)).map_or(0, |s| s.items.len()); + let target = self.item as isize + delta * step; + // Past the last full column, the last song. + if target >= len as isize && step > 1 && self.item / SONG_ROWS == len.saturating_sub(1) / SONG_ROWS { + return true; + } + self.item = target.max(0) as usize; self.clamp(); true } @@ -439,6 +581,10 @@ impl HomeView { self.shelf = self.shelf.min(home.shelves.len().saturating_sub(1)); let items = home.shelves.get(self.shelf).map_or(0, |s| s.items.len()); self.item = self.item.min(items.saturating_sub(1)); + self.chip = self.chip.filter(|_| !home.chips.is_empty()).map(|chip| chip.min(home.chips.len() - 1)); + if home.shelves.is_empty() && !home.chips.is_empty() { + self.chip.get_or_insert(0); + } } } @@ -686,14 +832,14 @@ mod tests { cloofy_core::home::Shelf { uri: uri.into(), title: uri.into(), - shortcuts: false, items: items.iter().map(item).collect(), + ..Default::default() } } #[test] fn a_newer_home_keeps_the_selected_card_and_paging() { - let home = |shelves| Home { greeting: String::new(), shelves }; + let home = |shelves| Home { shelves, ..Home::default() }; let mut view = HomeView::new(1, Some(home(vec![shelf("a", &["1", "2"]), shelf("b", &["3", "4", "5"])]))); (view.shelf, view.item, view.offsets) = (1, 2, vec![0, 1]); view.set_home(home(vec![shelf("new", &["0"]), shelf("b", &["6", "3", "4", "5"]), shelf("a", &["1"])])); @@ -701,6 +847,90 @@ mod tests { assert_eq!(view.offsets, [0, 1, 0]); } + fn songs(uri: &str, count: usize) -> cloofy_core::home::Shelf { + let names: Vec = (0..count).map(|i| format!("{uri}{i}")).collect(); + let names: Vec<&str> = names.iter().map(String::as_str).collect(); + cloofy_core::home::Shelf { songs: true, ..shelf(uri, &names) } + } + + fn chips(titles: &[&str]) -> Vec { + titles.iter().map(|t| Chip { title: t.to_string(), id: format!("id-{t}"), selected: false }).collect() + } + + #[test] + fn up_and_down_go_through_a_column_of_songs() { + let home = + Home { shelves: vec![shelf("a", &["1", "2"]), songs("q", 10), shelf("b", &["3"])], ..Home::default() }; + let mut view = HomeView::new(1, Some(home)); + view.move_shelf(1); + assert_eq!((view.shelf, view.item), (1, 0), "into the songs at the top of their first column"); + view.move_shelf(1); + view.move_shelf(1); + view.move_shelf(1); + assert_eq!((view.shelf, view.item), (1, 3)); + view.move_shelf(1); + assert_eq!(view.shelf, 2, "the bottom of the column leads on to the next shelf"); + view.move_shelf(-1); + assert_eq!((view.shelf, view.item), (1, 3), "from below, at the bottom of the column"); + } + + #[test] + fn left_and_right_go_from_column_to_column() { + let home = Home { shelves: vec![songs("q", 10)], ..Home::default() }; + let mut view = HomeView::new(1, Some(home)); + view.move_shelf(1); + assert_eq!(view.item, 1, "down the first column"); + assert!(view.move_item(1)); + assert_eq!(view.item, 5, "the same row of the next column"); + assert!(view.move_item(1)); + assert_eq!(view.item, 9, "the last column is short: its last song"); + assert!(view.move_item(1)); + assert_eq!(view.item, 9); + view.item = 2; + assert!(!view.move_item(-1), "the first column hands over to the sidebar"); + } + + #[test] + fn paging_songs_keeps_the_cursor_in_its_row() { + let home = Home { shelves: vec![songs("q", 20)], ..Home::default() }; + let mut view = HomeView::new(1, Some(home)); + (view.columns, view.item) = (2, 1); + view.scroll_shelf(0, 2); + assert_eq!(view.offsets[0], 8); + assert_eq!(view.item, 9); + view.scroll_shelf(0, 9); + assert_eq!(view.offsets[0], 12, "as far as the last columns"); + let mut offset = 0; + follow_songs(&mut offset, 13, 2); + assert_eq!(offset, 8); + } + + #[test] + fn the_chips_sit_above_the_first_shelf() { + let home = + Home { chips: chips(&["Relax", "Workout"]), shelves: vec![shelf("a", &["1", "2"])], ..Home::default() }; + let mut view = HomeView::new(1, Some(home)); + view.move_shelf(-1); + assert_eq!(view.chip, Some(0)); + assert!(view.selected().is_none()); + assert!(view.move_item(1)); + assert_eq!(view.chip, Some(1)); + assert_eq!(view.pick_chip(1), Some(Some("id-Workout".into()))); + assert!(view.loading && view.chips()[1].selected); + let workout = + Home { chips: vec![Chip { selected: true, ..chips(&["Workout"])[0].clone() }], ..Home::default() }; + assert!(view.wants(&workout)); + assert!(!view.wants(&Home::default()), "the whole Home arrives too late"); + // Picked again, back to the whole Home. + assert_eq!(view.pick_chip(1), Some(None)); + assert!(view.wants(&Home::default()) && !view.wants(&workout)); + view.move_shelf(1); + assert_eq!((view.chip, view.shelf, view.item), (None, 0, 0)); + view.move_shelf(-1); + view.move_shelf(isize::MAX / 2); + assert_eq!((view.chip, view.shelf), (None, 0), "the end, from the chips"); + } + fn next(n: u32, provider: crate::queue::Provider) -> QueueRow { let entry = Upcoming { uri: format!("spotify:track:{n}"), uid: format!("u{n}"), provider }; QueueRow::Next { track: track(n), entry } diff --git a/crates/cloofy-tui/tests/screens/star.txt b/crates/cloofy-tui/tests/screens/star.txt new file mode 100644 index 0000000..0fe40a9 --- /dev/null +++ b/crates/cloofy-tui/tests/screens/star.txt @@ -0,0 +1,36 @@ + + ▄▀▀ █ ▄▀▄ ▄▀▄ ▄▀▀ █ █ + █ █ █ █ █ █ █▀▀ ▀█ ‹ ⌂ ⌕ What do you want to play? ◉ Tester + ▀▀ ▀ ▀ ▀ ▀ ▀▀ + + + ≡ Your Library ⤢ Relax Workout ┃ + ┃ + Playlists Albums Quick picks ▶ Play all 1–8 of 9 ‹ › ┃ + ┃ + ▄▄▄▄ Liked Songs ▀▄▄▀ YouTube Music Song 1 ▀▄▄▀ YouTube Music Song 5 ┃ + ▄▀▀▄ Playlist · 3 songs ▀▀▀▀ YouTube Music Band ▀▀▀▀ YouTube Music Band ┃ + ┃ + ▀▄▄▀ YouTube Music Mix ╭ ★ Enjoying cloofy? ────────────────────────────────╮ube Music Mix Song 1 ┃ + ▀▀▀▀ Playlist · Tester │ │ube Music Band ┃ + │ cloofy is free and made in spare time. If you │ ┃ + ▀▄▄▀ YouTube Music Album │ like it, a star on GitHub helps other people │ube Music Mix Song 2 ┃ + ▀▀▀▀ Album · YouTube Music… │ find it. │ube Music Band ┃ + │ │ ┃ + │ ★ Star on GitHub No thanks │ube Music Mix Song 3 ┃ + │ │ube Music Band ┃ + │ enter choose · esc close │ ┃ + ╰────────────────────────────────────────────────────╯ ┃ + MADE FOR YOU ┃ + For you │ + │ + ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ │ + ▀ ▀ ▀▄▀ ▀ ▀ ▀ ▀ ▀▄▀ ▀ ▀ │ + ▀ ▀ ▄▄▄ ▀ ▀ ▀ ▀ ▄▄▄ ▀ ▀ │ + ▀ ▄▄▄▄▀▀ ▀ ▀ ▄▄▄▄▀▀ ▀ │ + + Nothing playing + ♪ Pick a song and press ↵ + + + enter play . actions / search ^K commands ? help diff --git a/crates/cloofy-tui/tests/screens/ytmusic_home.txt b/crates/cloofy-tui/tests/screens/ytmusic_home.txt new file mode 100644 index 0000000..dde46dd --- /dev/null +++ b/crates/cloofy-tui/tests/screens/ytmusic_home.txt @@ -0,0 +1,36 @@ + + ▄▀▀ █ ▄▀▄ ▄▀▄ ▄▀▀ █ █ + █ █ █ █ █ █ █▀▀ ▀█ ‹ ⌂ ⌕ What do you want to play? ◉ Tester + ▀▀ ▀ ▀ ▀ ▀ ▀▀ + + + ≡ Your Library ⤢ Relax Workout ┃ + ┃ + Playlists Albums Quick picks ▶ Play all 1–8 of 9 ‹ › ┃ + ┃ + ▄▄▄▄ Liked Songs ▀▄▄▀ YouTube Music Song 1 ▀▄▄▀ YouTube Music Song 5 ┃ + ▄▀▀▄ Playlist · 3 songs ▀▀▀▀ YouTube Music Band ▀▀▀▀ YouTube Music Band ┃ + ┃ + ▀▄▄▀ YouTube Music Mix ▀▄▄▀ YouTube Music Song 2 ▀▄▄▀ YouTube Music Mix Song 1 ┃ + ▀▀▀▀ Playlist · Tester ▀▀▀▀ YouTube Music Band ▀▀▀▀ YouTube Music Band ┃ + ┃ + ▀▄▄▀ YouTube Music Album ▀▄▄▀ YouTube Music Song 3 ▀▄▄▀ YouTube Music Mix Song 2 ┃ + ▀▀▀▀ Album · YouTube Music… ▀▀▀▀ YouTube Music Band ▀▀▀▀ YouTube Music Band ┃ + ┃ + ▀▄▄▀ YouTube Music Song 4 ▀▄▄▀ YouTube Music Mix Song 3 ┃ + ▀▀▀▀ YouTube Music Band ▀▀▀▀ YouTube Music Band ┃ + ┃ + ┃ + MADE FOR YOU ┃ + For you │ + │ + ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ ▀ │ + ▀ ▀ ▀▄▀ ▀ ▀ ▀ ▀ ▀▄▀ ▀ ▀ │ + ▀ ▀ ▄▄▄ ▀ ▀ ▀ ▀ ▄▄▄ ▀ ▀ │ + ▀ ▄▄▄▄▀▀ ▀ ▀ ▄▄▄▄▀▀ ▀ │ + + Nothing playing + ♪ Pick a song and press ↵ + + + enter play . actions / search ^K commands ? help diff --git a/crates/cloofy-ytmusic/examples/ytm.rs b/crates/cloofy-ytmusic/examples/ytm.rs index 4844774..49058a2 100644 --- a/crates/cloofy-ytmusic/examples/ytm.rs +++ b/crates/cloofy-ytmusic/examples/ytm.rs @@ -1,7 +1,7 @@ //! A command line for trying the YouTube Music backend without the interface: //! //! ```text -//! cargo run -p cloofy-ytmusic --example ytm -- home +//! cargo run -p cloofy-ytmusic --example ytm -- home [chip ID] //! cargo run -p cloofy-ytmusic --example ytm -- search daft punk //! cargo run -p cloofy-ytmusic --example ytm -- playlist|album|artist|radio|lyrics //! cargo run -p cloofy-ytmusic --example ytm -- suggest|tracks|saved|me|accounts|browsers|doctor … @@ -53,9 +53,16 @@ async fn main() -> Result<()> { let started = Instant::now(); match command.as_str() { "home" => { - let home = client.home().await?; + let home = client.home(rest.first().map(String::as_str)).await?; + for chip in &home.chips { + println!("chip {}{} [{}]", chip.title, if chip.selected { " (selected)" } else { "" }, chip.id); + } for shelf in &home.shelves { - println!("\n## {} ({} items)", shelf.title, shelf.items.len()); + let layout = if shelf.songs { ", songs" } else { "" }; + println!("\n## {} ({} items{layout}) {}", shelf.title, shelf.items.len(), shelf.strapline); + if let Some(all) = &shelf.play_all { + println!(" play all: {all}"); + } for item in &shelf.items { println!( " {:?} {} — {} [{}] play={}", diff --git a/crates/cloofy-ytmusic/src/doctor.rs b/crates/cloofy-ytmusic/src/doctor.rs index 2a921e4..fc80f8d 100644 --- a/crates/cloofy-ytmusic/src/doctor.rs +++ b/crates/cloofy-ytmusic/src/doctor.rs @@ -31,7 +31,7 @@ pub async fn programs() -> Section { pub async fn innertube(client: &YtMusic) -> Section { let mut checks = vec![ timed("Home", Expect::Available, async { - let home = client.home().await?; + let home = client.home(None).await?; Ok(format!("{} shelves", home.shelves.len())) }) .await, diff --git a/crates/cloofy-ytmusic/src/home.rs b/crates/cloofy-ytmusic/src/home.rs index b9ac1da..c94b3bd 100644 --- a/crates/cloofy-ytmusic/src/home.rs +++ b/crates/cloofy-ytmusic/src/home.rs @@ -1,23 +1,33 @@ //! The Home feed. music.youtube.com sends a few shelves first and more as the page scrolls; //! cloofy asks for a few more pages straight away so Home has as many shelves as Spotify's. +//! Above the shelves are chips for moods like "Relax", which show a Home of their own. use anyhow::{Context, Result}; -use cloofy_core::home::{Home, Shelf}; -use serde_json::Value; +use cloofy_core::home::{Chip, Home, Shelf}; +use serde_json::{Value, json}; use crate::{ innertube::InnerTube, - parse::{self, find, list, text}, + parse::{self, PLAYLIST, SONGS, TRACK, find, list, str_at, text}, }; /// Home asks for more pages until it has this many shelves… const MIN_SHELVES: usize = 10; /// …but no more pages than this. const MAX_PAGES: usize = 5; +/// The chip of podcasts, which cloofy can't play on YouTube Music. Titles are English, since +/// cloofy asks for English. +const PODCASTS: &str = "Podcasts"; -pub(crate) async fn home(api: &InnerTube) -> Result { - let first = api.browse("FEmusic_home").await?; +/// Home, or the Home of the chip with this ID. +pub(crate) async fn home(api: &InnerTube, chip: Option<&str>) -> Result { + let mut body = json!({ "browseId": "FEmusic_home" }); + if let Some(chip) = chip { + body["params"] = chip.into(); + } + let first = api.call("browse", body).await?; let sections = find(&first, "sectionListRenderer").context("Home: unexpected response")?; + let chips = parse_chips(sections, chip); let mut shelves = parse_shelves(sections); let mut token = parse::continuation(sections); let mut pages = 1; @@ -35,7 +45,22 @@ pub(crate) async fn home(api: &InnerTube) -> Result { shelves.extend(parse_shelves(sections)); token = parse::continuation(sections); } - Ok(Home { greeting: String::new(), shelves }) + Ok(Home { greeting: String::new(), chips, shelves }) +} + +/// The chips above Home's shelves; `asked` is the ID of the chip Home was asked for. +fn parse_chips(sections: &Value, asked: Option<&str>) -> Vec { + let chips = sections.pointer("/header/chipCloudRenderer/chips").unwrap_or(&Value::Null); + list(chips) + .iter() + .filter_map(|chip| { + let chip = chip.get("chipCloudChipRenderer")?; + let title = text(&chip["text"]); + let id = str_at(chip, "/navigationEndpoint/browseEndpoint/params")?.to_owned(); + let selected = chip["isSelected"] == true || asked == Some(id.as_str()); + (!title.is_empty() && title != PODCASTS).then_some(Chip { title, id, selected }) + }) + .collect() } /// The shelves of a section list; ones with nothing cloofy can show are left out. @@ -53,8 +78,27 @@ fn shelf(section: &Value) -> Option { if title.is_empty() { return None; } - let items = list(&carousel["contents"]).iter().filter_map(parse::home_item).collect(); - Some(Shelf { uri: format!("ytmusic:shelf:{title}"), title, shortcuts: false, items }) + let items: Vec<_> = list(&carousel["contents"]).iter().filter_map(parse::home_item).collect(); + // Quick picks and the like: songs in columns, rather than cards. + let songs = carousel.get("numItemsPerColumn").is_some() && items.iter().all(|item| item.is_song()); + let play = header.pointer("/moreContentButton/buttonRenderer/navigationEndpoint/watchEndpoint"); + let play_all = play.and_then(|play| match str_at(play, "/playlistId") { + Some(playlist) => Some(format!("{PLAYLIST}{playlist}")), + // A list made up for the shelf: its songs, in order. + None => { + let videos: Vec<_> = items.iter().filter_map(|item| item.context_uri.strip_prefix(TRACK)).collect(); + (!videos.is_empty()).then(|| format!("{SONGS}{}", videos.join(","))) + } + }); + Some(Shelf { + uri: format!("ytmusic:shelf:{title}"), + title, + strapline: text(&header["strapline"]), + shortcuts: false, + songs, + play_all, + items, + }) } #[cfg(test)] @@ -69,16 +113,25 @@ mod tests { let sections = find(&page, "sectionListRenderer").unwrap(); let shelves = parse_shelves(sections); assert_eq!(shelves[0].title, "Quick picks"); + assert!(shelves[0].songs, "Quick picks are songs in columns"); + let videos = ["xukbqwRuN5w", "kOn-HdEg6AQ"]; + assert!( + shelves[0].play_all.as_deref().is_some_and(|all| all.starts_with(&format!("{SONGS}{}", videos.join(",")))), + "Play all plays the songs in order: {:?}", + shelves[0].play_all + ); let song = &shelves[0].items[0]; assert_eq!(song.kind, ItemKind::Playlist, "a song opens as its radio"); assert_eq!(song.uri, "ytmusic:playlist:RDAMVMxukbqwRuN5w"); assert_eq!(song.context_uri, "ytmusic:track:xukbqwRuN5w"); assert_eq!(song.title, "Choosin' Texas"); - assert_eq!(song.subtitle, "Song • Ella Langley"); + assert_eq!(song.subtitle, "Ella Langley • 346M plays • Dandelion"); assert!(song.image_url.as_deref().is_some_and(|url| url.contains("=w300-h300")), "{:?}", song.image_url); let playlists = &shelves[1]; assert_eq!(playlists.title, "100% Hits"); + assert_eq!(playlists.strapline, "DIE GRÖSSTEN HITS ALLER ZEITEN"); + assert!(!playlists.songs && playlists.play_all.is_none()); let first = &playlists.items[0]; assert_eq!(first.kind, ItemKind::Playlist); assert!(first.uri.starts_with("ytmusic:playlist:RDCLAK5uy_"), "{}", first.uri); @@ -86,6 +139,19 @@ mod tests { assert!(parse::continuation(sections).is_some()); } + #[test] + fn chips_narrow_home_down_except_to_podcasts() { + let page: Value = serde_json::from_str(include_str!("../tests/fixtures/home.json")).unwrap(); + let sections = find(&page, "sectionListRenderer").unwrap(); + let chips = parse_chips(sections, None); + let titles: Vec<_> = chips.iter().map(|c| c.title.as_str()).collect(); + assert_eq!(titles, ["Workout", "Relax"], "cloofy can't play podcasts on YouTube Music"); + assert!(chips.iter().all(|c| !c.selected && c.id.starts_with("ggN"))); + + let relax = parse_chips(sections, Some(&chips[1].id)); + assert!(relax[1].selected && !relax[0].selected, "the chip asked for is the selected one"); + } + #[test] fn continuation_pages_add_shelves() { let page: Value = serde_json::from_str(include_str!("../tests/fixtures/home_continuation.json")).unwrap(); diff --git a/crates/cloofy-ytmusic/src/lib.rs b/crates/cloofy-ytmusic/src/lib.rs index 8f432b6..324e63f 100644 --- a/crates/cloofy-ytmusic/src/lib.rs +++ b/crates/cloofy-ytmusic/src/lib.rs @@ -98,9 +98,10 @@ impl YtMusic { /// The Home feed's shelves, as music.youtube.com shows them. Home items have no kind for /// songs, so a song is its radio: a playlist (`ytmusic:playlist:RDAMVM`) to open, whose - /// `context_uri` is the song itself (`ytmusic:track:`) to play. - pub async fn home(&self) -> Result { - home::home(&self.inner.api).await + /// `context_uri` is the song itself (`ytmusic:track:`) to play. With a chip's ID, the + /// Home of that chip. + pub async fn home(&self, chip: Option<&str>) -> Result { + home::home(&self.inner.api, chip).await } /// Songs, albums, artists and playlists for `query`. diff --git a/crates/cloofy-ytmusic/src/parse.rs b/crates/cloofy-ytmusic/src/parse.rs index cb21d56..8e3106d 100644 --- a/crates/cloofy-ytmusic/src/parse.rs +++ b/crates/cloofy-ytmusic/src/parse.rs @@ -17,6 +17,9 @@ pub(crate) const TRACK: &str = "ytmusic:track:"; pub(crate) const ALBUM: &str = "ytmusic:album:"; pub(crate) const PLAYLIST: &str = "ytmusic:playlist:"; pub(crate) const ARTIST: &str = "ytmusic:artist:"; +/// Songs played in a row, by video ID: `ytmusic:songs:,,…`. Home's Quick picks play as +/// this, since YouTube Music makes their list up rather than keeping it as a playlist. +pub(crate) const SONGS: &str = "ytmusic:songs:"; /// The text of a `runs` or `simpleText` object. pub(crate) fn text(value: &Value) -> String { @@ -387,18 +390,29 @@ pub(crate) fn home_item(item: &Value) -> Option { if let Some(track) = list_item_track(row) && row.get("navigationEndpoint").is_none() { - return Some(song_item(&track)); + // A row of songs only: what the row says under the title, e.g. "Artist • Album". + let mut item = song_item(&track); + let below = below_title(row); + if !below.is_empty() { + item.subtitle = below; + } + return Some(item); } let link = Link::of(row.get("navigationEndpoint")?)?; let columns = flex_columns(row); let title: String = columns.first()?.iter().filter_map(|r| r["text"].as_str()).collect(); let byline = Byline::parse(columns.iter().skip(1).copied()); - let subtitle = - columns.iter().skip(1).map(|runs| runs.iter().filter_map(|r| r["text"].as_str()).collect::()); - let subtitle = subtitle.filter(|s| !s.is_empty()).collect::>().join(" • "); + let subtitle = below_title(row); make_item(link, title, &byline, subtitle, &row["thumbnail"]) } +/// The columns of a list row after its title, as one line: "Artist • Album". +fn below_title(row: &Value) -> String { + let columns = flex_columns(row); + let texts = columns.iter().skip(1).map(|runs| runs.iter().filter_map(|r| r["text"].as_str()).collect::()); + texts.filter(|s| !s.is_empty()).collect::>().join(" • ") +} + fn make_item(link: Link, title: String, byline: &Byline, subtitle: String, thumbnail: &Value) -> Option { if title.is_empty() { return None; diff --git a/crates/cloofy-ytmusic/src/player/mod.rs b/crates/cloofy-ytmusic/src/player/mod.rs index 7b34b37..3a12d7e 100644 --- a/crates/cloofy-ytmusic/src/player/mod.rs +++ b/crates/cloofy-ytmusic/src/player/mod.rs @@ -32,11 +32,11 @@ use tokio::{ use self::{ mpv::{Events, Mpv, MpvEvent}, queue::Queue, - stream::Stream, + stream::{BotCheck, Stream}, }; use crate::{ Source, YtMusic, pages, - parse::{self, ALBUM, ARTIST, PLAYLIST, TRACK}, + parse::{self, ALBUM, ARTIST, PLAYLIST, SONGS, TRACK}, }; /// "Previous" restarts the song once it has played this long, as Spotify's apps do. @@ -245,6 +245,8 @@ struct Engine { resolving: HashSet, /// Songs yt-dlp couldn't resolve, which mpv's hook gets to try. unresolvable: HashSet, + /// YouTube's bot check stopped yt-dlp, and the interface was told. + blocked: bool, /// Failed tries to play each song, by URI. attempts: HashMap, skipped_in_a_row: u32, @@ -302,6 +304,7 @@ impl Engine { streams: HashMap::new(), resolving: HashSet::new(), unresolvable: HashSet::new(), + blocked: false, attempts: HashMap::new(), skipped_in_a_row: 0, generation: 0, @@ -851,11 +854,17 @@ impl Engine { self.resolving.remove(&video); match result { Ok(stream) => { + self.blocked = false; self.streams.insert(video.clone(), stream); } Err(err) => { tracing::warn!("yt-dlp can't resolve {video}: {err:#}"); self.unresolvable.insert(video.clone()); + // Said once: every song after it would run into the same check. + if err.downcast_ref::().is_some() && !self.blocked { + self.blocked = true; + self.emit(PlayerEvent::Blocked { reason: err.to_string() }); + } } } let current = self.queue.current().map(|t| video_id(&t.uri) == video).unwrap_or(false); @@ -975,6 +984,12 @@ fn load_context(client: YtMusic, jobs: UnboundedSender, generation: u64, co let track = track.and_then(|t| if t.is_empty() { Err(anyhow!("This song isn't available")) } else { Ok(t) }); return send(track, true); + } else if let Some(videos) = context.strip_prefix(SONGS) { + let uris: Vec<_> = videos.split(',').filter(|v| !v.is_empty()).map(|v| format!("{TRACK}{v}")).collect(); + let tracks = client.tracks_by_uri(&uris).await; + let tracks = + tracks.and_then(|t| if t.is_empty() { Err(anyhow!("These songs aren't available")) } else { Ok(t) }); + return send(tracks, true); } else if context.starts_with(ALBUM) { Source::Album(context.clone()) } else if context.starts_with(PLAYLIST) { diff --git a/crates/cloofy-ytmusic/src/player/stream.rs b/crates/cloofy-ytmusic/src/player/stream.rs index 57d12a5..aacad24 100644 --- a/crates/cloofy-ytmusic/src/player/stream.rs +++ b/crates/cloofy-ytmusic/src/player/stream.rs @@ -17,6 +17,23 @@ const MARGIN: Duration = Duration::from_secs(30 * 60); /// …or, where the URL doesn't say, this long after they were made. const LIFETIME: Duration = Duration::from_secs(5 * 60 * 60); +/// YouTube asks the connection to prove it isn't a bot. It does so for signed-out requests +/// from addresses it finds suspicious, datacenters always and homes now and then, and it +/// passes by itself. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BotCheck; + +impl std::fmt::Display for BotCheck { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str( + "YouTube asks this connection to prove it isn't a bot, so songs can't play for now. It usually \ + passes within a few hours; another network helps sooner.", + ) + } +} + +impl std::error::Error for BotCheck {} + /// The page yt-dlp resolves for a song. pub(crate) fn watch_url(video: &str) -> String { format!("https://music.youtube.com/watch?v={video}") @@ -57,12 +74,20 @@ pub(crate) async fn resolve(video: &str, cache_dir: Option) -> Result Ok(Stream { url: url.to_owned(), until: valid_until(url) }), _ => { let stderr = String::from_utf8_lossy(&output.stderr); + if is_bot_check(&stderr) { + return Err(BotCheck.into()); + } let reason = stderr.lines().rfind(|line| !line.trim().is_empty()).unwrap_or("no URL").trim(); bail!("{}", reason.strip_prefix("ERROR: ").unwrap_or(reason)) } } } +/// Whether yt-dlp failed on YouTube's "Sign in to confirm you're not a bot". +fn is_bot_check(stderr: &str) -> bool { + stderr.contains("confirm you’re not a bot") || stderr.contains("confirm you're not a bot") +} + /// When to stop using a URL, from its `expire` parameter. fn valid_until(url: &str) -> Instant { let expires = url::Url::parse(url) @@ -80,6 +105,13 @@ fn valid_until(url: &str) -> Instant { mod tests { use super::*; + #[test] + fn the_bot_check_is_told_apart() { + let stderr = "ERROR: [youtube] plnfIj7dkJE: Sign in to confirm you’re not a bot. Use --cookies-from-browser"; + assert!(is_bot_check(stderr)); + assert!(!is_bot_check("ERROR: [youtube] plnfIj7dkJE: Video unavailable")); + } + #[test] fn urls_are_good_until_shortly_before_they_expire() { let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs(); diff --git a/crates/cloofy-ytmusic/tests/live.rs b/crates/cloofy-ytmusic/tests/live.rs index e819e68..c96c865 100644 --- a/crates/cloofy-ytmusic/tests/live.rs +++ b/crates/cloofy-ytmusic/tests/live.rs @@ -72,7 +72,7 @@ async fn a_song_has_a_radio_and_lyrics() { #[ignore = "online"] async fn home_and_suggestions_answer_signed_out() { let client = client("home"); - let home = client.home().await.unwrap(); + let home = client.home(None).await.unwrap(); assert!(home.shelves.iter().any(|shelf| !shelf.items.is_empty()), "{home:?}"); let suggestions = client.suggestions("daft p").await.unwrap(); assert!(!suggestions.is_empty()); diff --git a/crates/cloofy/examples/demo_fixture.rs b/crates/cloofy/examples/demo_fixture.rs index beca03b..a08211e 100644 --- a/crates/cloofy/examples/demo_fixture.rs +++ b/crates/cloofy/examples/demo_fixture.rs @@ -329,13 +329,14 @@ async fn main() -> Result<()> { title: String::new(), shortcuts: true, items: plan.home.shortcuts.iter().map(|r| item(r)).collect::>()?, + ..Shelf::default() }]; for (index, shelf) in plan.home.shelves.iter().enumerate() { shelves.push(Shelf { uri: format!("spotify:section:demo{index}"), title: shelf.title.clone(), - shortcuts: false, items: shelf.items.iter().map(|r| item(r)).collect::>()?, + ..Shelf::default() }); } @@ -346,7 +347,7 @@ async fn main() -> Result<()> { artists, shows: Vec::new(), liked, - home: Home { greeting: plan.home.greeting.clone(), shelves }, + home: Home { greeting: plan.home.greeting.clone(), shelves, ..Home::default() }, tracks, artist_pages, searches, diff --git a/crates/cloofy/src/ytmusic/playback.rs b/crates/cloofy/src/ytmusic/playback.rs index b8c138f..616b10e 100644 --- a/crates/cloofy/src/ytmusic/playback.rs +++ b/crates/cloofy/src/ytmusic/playback.rs @@ -61,6 +61,7 @@ pub async fn play(paths: &Paths, input: &str, shuffle: bool) -> Result<()> { clock.resume(position_ms); } // Nothing left to play, or nothing would. + PlayerEvent::Blocked { reason } => println!("\r\x1b[2K ✕ {reason}"), PlayerEvent::Stopped if played => break Ok(()), PlayerEvent::Stopped => break Err(anyhow!("YouTube Music can't play {input}")), _ => {} diff --git a/website/src/content/docs/docs/troubleshooting.md b/website/src/content/docs/docs/troubleshooting.md index ef5dae7..d567a19 100644 --- a/website/src/content/docs/docs/troubleshooting.md +++ b/website/src/content/docs/docs/troubleshooting.md @@ -21,7 +21,8 @@ It checks what each service can reach, one line per check: for Spotify your app, - **Songs don't start.** YouTube changes its challenges now and then, and an older yt-dlp gets no streams at all. Update yt-dlp (2025.11.12 or newer) and make sure deno is installed; `cloofy doctor` checks both. - **The wrong account.** Run `cloofy login ytmusic --force` and pick the right one. See [Signing in](/docs/youtube-music/#signing-in). -- **The sign-in has expired.** When YouTube no longer takes the sign-in, for example after you signed out of Google in the browser, cloofy says so. Run `cloofy login ytmusic` again. +- **YouTube asks to prove you're not a bot.** Now and then YouTube wants a connection to prove it isn't a bot before it hands out streams, and no song plays. cloofy says so at the bottom until music plays again. It usually passes within a few hours; another network, like your phone's hotspot, helps sooner. +- **The sign-in has expired.** When YouTube no longer takes the sign-in, for example after you signed out of Google in the browser, cloofy says so at the bottom until you close it. A click copies `cloofy login ytmusic`; run it in a terminal. - **yt-dlp can't decrypt the browser's cookies.** On Linux, yt-dlp needs Python's secretstorage to read the keyring of Chromium-based browsers: install `python-secretstorage` (Arch) or `python3-secretstorage` (Debian, Ubuntu, Fedora). ## No sound diff --git a/website/src/content/docs/docs/youtube-music.md b/website/src/content/docs/docs/youtube-music.md index d9a2e73..a75412c 100644 --- a/website/src/content/docs/docs/youtube-music.md +++ b/website/src/content/docs/docs/youtube-music.md @@ -7,6 +7,14 @@ YouTube Music needs no account. cloofy plays it with [mpv](https://mpv.io) and f Signed out, Home, search, artist, album and playlist pages, lyrics and song radios work. Signing in adds your library: your playlists, albums, subscribed artists and liked songs, and liking, saving and adding to playlists. +## Home + +Home is YouTube Music's own: Quick picks, mixes, new releases and playlists on shelves, with chips for moods like Relax, Workout or Focus above them. A chip shows the Home of that mood, and picked again the whole Home. ↑ from the first shelf reaches the chips, and ← → move along them. + +Quick picks show as songs in columns of four, as on music.youtube.com: ↑ ↓ move within a column, ← → from column to column. A song plays at once, with its radio after it, and **Play all** plays the shelf in order. + +## Playing + Songs follow each other without a gap, and when a playlist or album ends, the radio of its last song follows, as on YouTube Music. The queue, shuffle, repeat, seeking, the volume and the system's media controls work as with Spotify. ## Signing in diff --git a/website/src/pages/index.astro b/website/src/pages/index.astro index d39fa67..910234f 100644 --- a/website/src/pages/index.astro +++ b/website/src/pages/index.astro @@ -23,6 +23,7 @@ const features = [ { title: 'Plays on its own', text: 'Spotify plays through librespot, and cloofy is a Spotify Connect device. It controls your other devices too, and follows them live. YouTube Music plays through mpv, with no gap between songs.' }, { title: 'Spotify, YouTube Music or both', text: 'Install one, or both side by side: S or the switch in the top bar shows the other\'s Home, library and pages, as you left them.' }, { title: 'YouTube Music without an account', text: 'Home, search, every page, lyrics and song radios work signed out. Sign in with your browser for your library and likes.' }, + { title: 'YouTube Music\'s Home, as in its apps', text: 'Moods like Relax or Workout narrow it down, and Quick picks show as songs that play at once, or all in a row.' }, { title: 'Home and the DJ', text: 'Your shelves and mixes, and on Spotify Made For You and the DJ with its voice between tracks. Ask the DJ for something, as in Spotify\'s apps.' }, { title: 'The queue', text: 'See what plays next: the songs you queued, then the rest of the playlist or album. Skip ahead to any of them, or take a queued song out again.' }, { title: 'Cover art', text: 'Real images in terminals that show pictures through the Kitty, Sixel or iTerm2 protocol, and block art everywhere else.' }, @@ -87,7 +88,7 @@ const initial = commands(builds.ytmusic);
- What's new in 0.5: YouTube Music + What's new in 0.5.2: YouTube Music's Home

cloofy

Spotify and YouTube Music in your terminal.

Plays on its own, with Home, Spotify's DJ, synced lyrics, real cover art and a mouse that works everywhere.

@@ -187,6 +188,7 @@ const initial = commands(builds.ytmusic);
  • Plays through mpv, with the streams from yt-dlp, and no gap between songs
  • +
  • Home as in YouTube Music's apps, with moods like Relax or Workout and Quick picks as songs
  • Home, search, every page, lyrics and song radios work without an account
  • Signed in with your browser, your playlists, albums, artists and liked songs
  • With several Google accounts in the browser, you pick one by its address
  • From 25274e978b321f6ca6f7e89888729499d8e160cb Mon Sep 17 00:00:00 2001 From: Paul Otto Date: Tue, 10 Nov 2026 12:31:56 +0100 Subject: [PATCH 2/4] chore: version 0.5.2 Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 14 +++++++------- Cargo.toml | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e990fc7..eec6678 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -436,7 +436,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" [[package]] name = "cloofy" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "clap", @@ -461,7 +461,7 @@ dependencies = [ [[package]] name = "cloofy-core" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "cloofy-os", @@ -480,7 +480,7 @@ dependencies = [ [[package]] name = "cloofy-os" -version = "0.5.1" +version = "0.5.2" dependencies = [ "block2", "dispatch2", @@ -501,7 +501,7 @@ dependencies = [ [[package]] name = "cloofy-player" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "cloofy-core", @@ -515,7 +515,7 @@ dependencies = [ [[package]] name = "cloofy-spotify" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "base64 0.23.1", @@ -538,7 +538,7 @@ dependencies = [ [[package]] name = "cloofy-tui" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "base64 0.23.1", @@ -572,7 +572,7 @@ dependencies = [ [[package]] name = "cloofy-ytmusic" -version = "0.5.1" +version = "0.5.2" dependencies = [ "anyhow", "cloofy-core", diff --git a/Cargo.toml b/Cargo.toml index d10d4d4..142f8de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ members = ["crates/*"] exclude = ["vendor"] [workspace.package] -version = "0.5.1" +version = "0.5.2" edition = "2024" rust-version = "1.90" license = "MIT" From d59b3985d36d04bc6dd0c5f0823c9318e3587bc4 Mon Sep 17 00:00:00 2001 From: Paul Otto Date: Tue, 10 Nov 2026 12:31:56 +0100 Subject: [PATCH 3/4] chore(release): 0.5.2 Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ff588ba..52ec47b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,10 @@ All notable changes to cloofy. The format follows [Keep a Changelog](https://kee ## [Unreleased] +## [0.5.2] - 2026-11-10 + +YouTube Music's Home looks and works as in its own apps, and cloofy asks once for a star. + ### Added - **Moods on YouTube Music's Home.** Chips like Relax, Workout or Focus above the shelves show the Home of that mood, as on music.youtube.com, and picked again the whole Home. ↑ from the first shelf reaches them. @@ -162,7 +166,8 @@ The first release. - **Session restore.** The page, the selection and the last track come back after a restart. - **Installer.** It sets everything up step by step. -[Unreleased]: https://github.com/parda21/cloofy/compare/v0.5.1...HEAD +[Unreleased]: https://github.com/parda21/cloofy/compare/v0.5.2...HEAD +[0.5.2]: https://github.com/parda21/cloofy/compare/v0.5.1...v0.5.2 [0.5.1]: https://github.com/parda21/cloofy/compare/v0.5.0...v0.5.1 [0.5.0]: https://github.com/parda21/cloofy/compare/v0.4.0...v0.5.0 [0.4.0]: https://github.com/parda21/cloofy/compare/v0.3.0...v0.4.0 From 344d0d11dacbd8ade5bac4086382b123eb8a67ac Mon Sep 17 00:00:00 2001 From: Paul Otto Date: Tue, 10 Nov 2026 12:48:56 +0100 Subject: [PATCH 4/4] fix: from the review on #28 - A chip whose Home fails to load went unnoticed: the old Home stayed with the chip picked. The chips go back to the Home shown now, and the bottom says why. A Home result carries the chip it was asked for, so a late one for another chip, or its error, is left out, and a chip's Home that marks no chip selected still arrives. - The star's popup keeps its note, buttons and hint inside its border on a short terminal. - The bot check is said once per start, so it's said again after its notice was closed. - Troubleshooting: the sign-in notice also goes when the sign-in works. Co-Authored-By: Claude Opus 5.5 --- crates/cloofy-tui/src/app/mod.rs | 18 +++--- crates/cloofy-tui/src/backend/fake.rs | 10 ++++ crates/cloofy-tui/src/loader.rs | 6 +- crates/cloofy-tui/src/scenarios/playback.rs | 30 +++++++++- crates/cloofy-tui/src/ui/star.rs | 16 ++++-- crates/cloofy-tui/src/views.rs | 56 +++++++++++++++---- crates/cloofy-ytmusic/src/player/mod.rs | 24 +++++++- .../src/content/docs/docs/troubleshooting.md | 2 +- 8 files changed, 133 insertions(+), 29 deletions(-) diff --git a/crates/cloofy-tui/src/app/mod.rs b/crates/cloofy-tui/src/app/mod.rs index e5322cf..a36286b 100644 --- a/crates/cloofy-tui/src/app/mod.rs +++ b/crates/cloofy-tui/src/app/mod.rs @@ -1468,23 +1468,27 @@ impl App { self.saved.insert(uri, followed); self.loader.check_saved(uris); } - DataEvent::Home { view, result } => { + DataEvent::Home { view, chip, result } => { // A chip's Home is only for its view; the whole Home is what Home opens with. - if let Some(home) = result.as_ref().ok().filter(|home| home.chip().is_none()) { + if let Some(home) = result.as_ref().ok().filter(|_| chip.is_none()) { self.home_cache = Some(home.clone()); self.home_fetched_at = Some(Instant::now()); self.data_dirty = true; } let Some(View::Home(v)) = self.view_mut(view) else { return false }; - if result.as_ref().is_ok_and(|home| !v.wants(home)) { + if !v.wants(chip.as_deref()) { return false; } match result { Ok(home) => v.set_home(home), - Err(err) => { - v.loading = false; - v.error = Some(err); - } + // The Home before the chip stays, so the failure is said at the bottom. + Err(err) => match v.chip_failed() { + Some(failed) => self.error(format!("Couldn't load {failed}: {err}")), + None => { + v.loading = false; + v.error = Some(err); + } + }, } } // Loads still under way when cover art was turned off. diff --git a/crates/cloofy-tui/src/backend/fake.rs b/crates/cloofy-tui/src/backend/fake.rs index 27043ec..0f31193 100644 --- a/crates/cloofy-tui/src/backend/fake.rs +++ b/crates/cloofy-tui/src/backend/fake.rs @@ -38,6 +38,8 @@ struct State { commands: Vec, liked: HashSet, playing: Option, + /// Home fails to load from now on. + home_down: bool, } struct Playing { @@ -88,6 +90,11 @@ impl Fake { let _ = self.0.tx.send(AppEvent::PlayerLost(self.0.service)); } + /// Home fails to load from now on, as when the service doesn't answer. + pub fn take_home_down(&self) { + self.state().home_down = true; + } + /// Sends what a real player would report. pub fn send(&self, event: PlayerEvent) { let _ = self.0.tx.send(AppEvent::Player(self.0.service, event)); @@ -307,6 +314,9 @@ impl Fake { /// A shelf of cards, and on YouTube Music chips and Quick picks too. A chip's Home has a /// shelf named after it. pub async fn home(&self, chip: Option<&str>) -> Result { + if self.state().home_down { + bail!("The fake's Home is down"); + } let service = self.0.service; let (album, playlist) = (album(service), playlist(service)); let item = |uri: &str, kind, title: &str| HomeItem { diff --git a/crates/cloofy-tui/src/loader.rs b/crates/cloofy-tui/src/loader.rs index b5540bf..c3af520 100644 --- a/crates/cloofy-tui/src/loader.rs +++ b/crates/cloofy-tui/src/loader.rs @@ -92,6 +92,8 @@ pub enum DataEvent { Me(Result), Home { view: u64, + /// The chip it was asked for with, `None` for the whole Home. + chip: Option, result: Result, }, Artist { @@ -467,11 +469,11 @@ impl Loader { /// Home, or the Home of the chip with this ID. pub fn home(&self, view: u64, chip: Option) { if let Some(demo) = self.demo() { - return self.send_for(DataEvent::Home { view, result: Ok(demo.home.clone()) }); + return self.send_for(DataEvent::Home { view, chip, result: Ok(demo.home.clone()) }); } self.spawn(move |this| async move { let result = async { this.shown()?.home(chip.as_deref()).await }.await; - this.send_for(DataEvent::Home { view, result: result.map_err(|e| format!("{e:#}")) }); + this.send_for(DataEvent::Home { view, chip, result: result.map_err(|e| format!("{e:#}")) }); }); } diff --git a/crates/cloofy-tui/src/scenarios/playback.rs b/crates/cloofy-tui/src/scenarios/playback.rs index 550de05..cb09d77 100644 --- a/crates/cloofy-tui/src/scenarios/playback.rs +++ b/crates/cloofy-tui/src/scenarios/playback.rs @@ -6,7 +6,7 @@ use std::time::Duration; use cloofy_core::{player::PlayerEvent, service::Service}; use crossterm::event::KeyCode::{Char, Down, Enter}; -use crate::{backend::fake::SONG, harness::Harness}; +use crate::{backend::fake::SONG, harness::Harness, views::View}; const SPOTIFY: Service = Service::Spotify; const YOUTUBE: Service = Service::YouTubeMusic; @@ -171,6 +171,18 @@ async fn a_chip_narrows_youtube_music_home_down_and_back() { assert!(!h.shows("Workout mixes") && h.shows("Quick picks"), "{}", h.screen()); } +/// A chip whose Home doesn't load left the old Home with the chip picked, and nothing said. +/// The Home shown stays, its chip too, and the bottom says why. +#[tokio::test] +async fn a_chip_that_fails_to_load_says_so() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + h.fake(YOUTUBE).take_home_down(); + h.click_on("Workout").await; + assert!(h.shows("Couldn't load Workout: The fake's Home is down") && h.shows("Quick picks"), "{}", h.screen()); + let View::Home(v) = &h.app.view else { panic!("{}", h.screen()) }; + assert!(v.filter.is_none() && !v.loading && v.chips().iter().all(|c| !c.selected)); +} + /// On the second day of use cloofy asks for a star on GitHub, once, a few seconds in. #[tokio::test] async fn the_star_on_github_is_asked_for_once() { @@ -198,6 +210,22 @@ async fn no_thanks_closes_the_star_for_good() { assert!(h.app.usage.star_asked); } +/// On a short terminal the star's popup leaves out what doesn't fit inside its border, instead +/// of drawing over the border and the page under it. +#[tokio::test] +async fn the_star_keeps_inside_its_border_on_a_short_terminal() { + let mut h = Harness::fakes(&[YOUTUBE]).await; + h.app.ask_for_star_after(Duration::ZERO); + h.wait(Duration::from_millis(100)).await; + for height in [9, 7, 5] { + h.resize(80, height).await; + let screen = h.screen(); + let bottom = screen.lines().find(|line| line.contains('╰')).unwrap_or_else(|| panic!("{screen}")); + let border: String = bottom.chars().skip_while(|&c| c != '╰').take_while(|&c| c != '╯').collect(); + assert!(border.chars().all(|c| c == '╰' || c == '─'), "{height} rows:\n{screen}"); + } +} + /// Issue #27: the expired sign-in went away after a few seconds, before anyone read it or /// could copy the command. It stays now, under other messages, until closed. #[tokio::test] diff --git a/crates/cloofy-tui/src/ui/star.rs b/crates/cloofy-tui/src/ui/star.rs index d35062b..0a8495b 100644 --- a/crates/cloofy-tui/src/ui/star.rs +++ b/crates/cloofy-tui/src/ui/star.rs @@ -2,7 +2,7 @@ use ratatui::{ buffer::Buffer, - layout::{Constraint, Rect}, + layout::{Constraint, Margin, Rect}, style::{Style, Stylize}, text::Line, widgets::{Block, BorderType, Clear, Paragraph, Widget, Wrap}, @@ -38,11 +38,13 @@ pub fn draw(buf: &mut Buffer, app: &mut App, area: Rect) { .render(popup, buf); app.hits.push((popup, Hit::OverlayArea)); - let inner = Rect { x: popup.x + 3, y: popup.y + 2, width: popup.width.saturating_sub(6), height: 3 }; - Paragraph::new(NOTE).wrap(Wrap { trim: true }).style(Style::new().fg(p.muted)).render(inner, buf); + // Inside the border, and on a short terminal only what fits there. + let inside = popup.inner(Margin::new(3, 1)); + let note = Rect { y: popup.y + 2, height: 3, ..inside }.intersection(inside); + Paragraph::new(NOTE).wrap(Wrap { trim: true }).style(Style::new().fg(p.muted)).render(note, buf); let y = popup.y + 6; - if y >= popup.bottom().saturating_sub(1) { + if y >= inside.bottom() { return; } let labels = [format!(" {STAR_ICON} {STAR} "), format!(" {NO_THANKS} ")]; @@ -57,13 +59,15 @@ pub fn draw(buf: &mut Buffer, app: &mut App, area: Rect) { } else { Style::new().fg(p.text).bg(p.unfocused) }; - buf.set_string(button.x, y, label, style); + buf.set_stringn(button.x, y, label, button.width.into(), style); app.hits.push((button, Hit::OverlayItem(index))); x += widths[index] + 3; } let hint = "enter choose · esc close"; let hint_x = popup.x + popup.width.saturating_sub(hint.width() as u16) / 2; - buf.set_string(hint_x, y + 2, hint, Style::new().fg(p.faint)); + if y + 2 < inside.bottom() { + buf.set_stringn(hint_x, y + 2, hint, inside.right().saturating_sub(hint_x).into(), Style::new().fg(p.faint)); + } if app.overlay_fx_pending { app.animate_overlay(popup); } diff --git a/crates/cloofy-tui/src/views.rs b/crates/cloofy-tui/src/views.rs index a1f4bb7..e2924a9 100644 --- a/crates/cloofy-tui/src/views.rs +++ b/crates/cloofy-tui/src/views.rs @@ -340,6 +340,9 @@ pub struct HomeView { pub chip: Option, /// The chip whose Home is shown or on its way; `None` for the whole Home. pub filter: Option, + /// While a picked chip's Home is on its way, the chip of the Home shown, to go back to + /// when it fails. + fallback: Option>, pub shelf: usize, pub item: usize, /// First visible card or song per shelf. @@ -399,6 +402,7 @@ impl HomeView { error: None, chip: None, filter, + fallback: None, shelf: 0, item: 0, offsets, @@ -463,17 +467,33 @@ impl HomeView { home.shelves[shelf].items.iter().position(|i| Some(i.uri.as_str()) == card).unwrap_or(self.item); self.shelf = shelf; } - self.filter = home.chip().cloned(); + self.fallback = None; self.home = Some(home); self.loading = false; self.error = None; self.clamp(); } - /// Whether `home` is the one this view waits for: the whole Home, or that of its chip. - /// One that arrives after another chip was picked is not. - pub fn wants(&self, home: &Home) -> bool { - home.chip().map(|c| &c.title) == self.filter.as_ref().map(|c| &c.title) + /// Whether a Home asked for with chip `chip` is the one this view waits for: the whole + /// Home, or that of its chip. One asked for before another chip was picked is not, nor + /// is its error. + pub fn wants(&self, chip: Option<&str>) -> bool { + chip == self.filter.as_ref().map(|c| c.id.as_str()) + } + + /// The picked chip's Home failed to load: the chips go back to the Home still shown. + /// Returns the title of the one that failed, "Home" for the whole Home, or `None` when + /// no chip was picked. + pub fn chip_failed(&mut self) -> Option { + let fallback = self.fallback.take()?; + let failed = std::mem::replace(&mut self.filter, fallback); + if let Some(home) = &mut self.home { + for chip in &mut home.chips { + chip.selected = self.filter.as_ref().is_some_and(|f| f.id == chip.id); + } + } + self.loading = false; + Some(failed.map_or_else(|| "Home".to_owned(), |chip| chip.title)) } /// Narrows Home to chip `index`, or back to the whole Home when that chip is picked @@ -485,7 +505,9 @@ impl HomeView { for (i, c) in home.chips.iter_mut().enumerate() { c.selected = picked && i == index; } - self.filter = picked.then(|| Chip { selected: true, ..chip.clone() }); + let filter = picked.then(|| Chip { selected: true, ..chip.clone() }); + let shown = std::mem::replace(&mut self.filter, filter); + self.fallback.get_or_insert(shown); self.chip = Some(index); self.loading = true; self.error = None; @@ -917,13 +939,11 @@ mod tests { assert_eq!(view.chip, Some(1)); assert_eq!(view.pick_chip(1), Some(Some("id-Workout".into()))); assert!(view.loading && view.chips()[1].selected); - let workout = - Home { chips: vec![Chip { selected: true, ..chips(&["Workout"])[0].clone() }], ..Home::default() }; - assert!(view.wants(&workout)); - assert!(!view.wants(&Home::default()), "the whole Home arrives too late"); + assert!(view.wants(Some("id-Workout"))); + assert!(!view.wants(None), "the whole Home arrives too late"); // Picked again, back to the whole Home. assert_eq!(view.pick_chip(1), Some(None)); - assert!(view.wants(&Home::default()) && !view.wants(&workout)); + assert!(view.wants(None) && !view.wants(Some("id-Workout"))); view.move_shelf(1); assert_eq!((view.chip, view.shelf, view.item), (None, 0, 0)); view.move_shelf(-1); @@ -931,6 +951,20 @@ mod tests { assert_eq!((view.chip, view.shelf), (None, 0), "the end, from the chips"); } + #[test] + fn a_chip_that_fails_goes_back_to_the_home_shown() { + let home = + Home { chips: chips(&["Relax", "Workout"]), shelves: vec![shelf("a", &["1", "2"])], ..Home::default() }; + let mut view = HomeView::new(1, Some(home.clone())); + view.set_home(home); + assert_eq!(view.chip_failed(), None, "no chip was picked"); + view.pick_chip(0); + view.pick_chip(1); + assert_eq!(view.chip_failed().as_deref(), Some("Workout")); + assert!(!view.loading && view.filter.is_none() && view.chips().iter().all(|c| !c.selected)); + assert!(view.wants(None)); + } + fn next(n: u32, provider: crate::queue::Provider) -> QueueRow { let entry = Upcoming { uri: format!("spotify:track:{n}"), uid: format!("u{n}"), provider }; QueueRow::Next { track: track(n), entry } diff --git a/crates/cloofy-ytmusic/src/player/mod.rs b/crates/cloofy-ytmusic/src/player/mod.rs index 3a12d7e..2d33dfd 100644 --- a/crates/cloofy-ytmusic/src/player/mod.rs +++ b/crates/cloofy-ytmusic/src/player/mod.rs @@ -245,7 +245,7 @@ struct Engine { resolving: HashSet, /// Songs yt-dlp couldn't resolve, which mpv's hook gets to try. unresolvable: HashSet, - /// YouTube's bot check stopped yt-dlp, and the interface was told. + /// YouTube's bot check stopped yt-dlp since the last start, and the interface was told. blocked: bool, /// Failed tries to play each song, by URI. attempts: HashMap, @@ -470,6 +470,9 @@ impl Engine { // The interface may have shown another player's queue since, so this one's is reported // again, even unchanged. self.reported = None; + // Each start says once that YouTube's bot check stops it, also after the last one's + // notice was closed. + self.blocked = false; } /// Silences mpv; what was loaded is gone. @@ -1067,6 +1070,25 @@ mod tests { assert_eq!(current.cover_url_large.as_deref(), Some("https://lh3.googleusercontent.com/a=w800-h800-l90-rj")); } + /// YouTube's bot check is said once per start: not for every song after it, but again when + /// the next start runs into it, after its notice may have been closed. + #[tokio::test] + async fn the_bot_check_is_said_once_per_start() { + let (mut engine, (mut events, _)) = idle_engine("bot-check"); + let mut blocked = async |engine: &mut Engine, video: &str| { + engine.job(Job::Resolved { video: video.into(), result: Err(BotCheck.into()) }).await.unwrap(); + let mut said = false; + while let Ok(event) = events.try_recv() { + said |= matches!(event, PlayerEvent::Blocked { .. }); + } + said + }; + assert!(blocked(&mut engine, "a").await); + assert!(!blocked(&mut engine, "b").await, "not again for the next song"); + engine.activate(); + assert!(blocked(&mut engine, "c").await, "again after another start"); + } + type Reports = (UnboundedReceiver, UnboundedReceiver<(u64, MpvEvent)>); /// An engine that never loads a context, with what it reports and mpv's events, which the diff --git a/website/src/content/docs/docs/troubleshooting.md b/website/src/content/docs/docs/troubleshooting.md index d567a19..7cc896c 100644 --- a/website/src/content/docs/docs/troubleshooting.md +++ b/website/src/content/docs/docs/troubleshooting.md @@ -22,7 +22,7 @@ It checks what each service can reach, one line per check: for Spotify your app, - **Songs don't start.** YouTube changes its challenges now and then, and an older yt-dlp gets no streams at all. Update yt-dlp (2025.11.12 or newer) and make sure deno is installed; `cloofy doctor` checks both. - **The wrong account.** Run `cloofy login ytmusic --force` and pick the right one. See [Signing in](/docs/youtube-music/#signing-in). - **YouTube asks to prove you're not a bot.** Now and then YouTube wants a connection to prove it isn't a bot before it hands out streams, and no song plays. cloofy says so at the bottom until music plays again. It usually passes within a few hours; another network, like your phone's hotspot, helps sooner. -- **The sign-in has expired.** When YouTube no longer takes the sign-in, for example after you signed out of Google in the browser, cloofy says so at the bottom until you close it. A click copies `cloofy login ytmusic`; run it in a terminal. +- **The sign-in has expired.** When YouTube no longer takes the sign-in, for example after you signed out of Google in the browser, cloofy says so at the bottom until you close it or the sign-in works again. A click copies `cloofy login ytmusic`; run it in a terminal. - **yt-dlp can't decrypt the browser's cookies.** On Linux, yt-dlp needs Python's secretstorage to read the keyring of Chromium-based browsers: install `python-secretstorage` (Arch) or `python3-secretstorage` (Debian, Ubuntu, Fedora). ## No sound