From e082e00e6f4e6bc2d80f22a243bb7e1e07c153b7 Mon Sep 17 00:00:00 2001 From: Dan Lock Date: Tue, 17 Nov 2026 21:45:58 +0000 Subject: [PATCH] feat(ui): add stats page --- CHANGELOG.md | 1 + Cargo.lock | 1 + assets/i18n/en-US/main.ftl | 143 ++ assets/icons/lucide/briefcase.svg | 14 + assets/icons/lucide/calendar-days.svg | 22 + assets/icons/lucide/compass.svg | 14 + assets/icons/lucide/flame.svg | 13 + assets/icons/lucide/gem.svg | 15 + assets/icons/lucide/rocket.svg | 16 + assets/icons/lucide/snail.svg | 17 + assets/icons/lucide/sparkles.svg | 16 + assets/icons/lucide/star.svg | 13 + assets/icons/lucide/sun.svg | 21 + assets/icons/lucide/sunrise.svg | 20 + assets/icons/lucide/sunset.svg | 20 + assets/icons/lucide/trending-up.svg | 14 + assets/icons/lucide/zap.svg | 13 + crates/music/src/lib.rs | 30 +- crates/music/src/models.rs | 14 + crates/music/src/scrobble/audioscrobbler.rs | 491 ++++++- crates/music/src/scrobble/mod.rs | 24 + crates/music/src/spotify/client.rs | 21 +- crates/music/src/spotify/collection.rs | 2 +- crates/music/src/spotify/descriptors.rs | 158 +++ crates/music/src/spotify/mod.rs | 1 + crates/music/src/spotify/pathfinder.rs | 2 + crates/music/src/spotify/pathfinder/hashes.rs | 30 +- crates/music/src/spotify/pathfinder/stats.rs | 429 ++++++ crates/music/src/spotify/pb.rs | 10 + crates/music/src/stats.rs | 451 +++++++ crates/router/src/lib.rs | 18 +- crates/sonora/src/actions.rs | 4 + crates/state/Cargo.toml | 1 + crates/state/src/history.rs | 17 +- crates/state/src/lib.rs | 13 + crates/state/src/stats.rs | 1155 +++++++++++++++++ crates/ui/src/card.rs | 87 ++ crates/ui/src/filters.rs | 31 +- crates/ui/src/info_card.rs | 22 +- crates/ui/src/lib.rs | 2 +- crates/views/src/chrome/sidebar_left.rs | 3 +- crates/views/src/chrome/title_bar.rs | 5 + crates/views/src/root.rs | 19 + crates/views/src/screens/artist.rs | 1 + crates/views/src/screens/detail.rs | 1 + crates/views/src/screens/mod.rs | 1 + crates/views/src/screens/stats/charts.rs | 224 ++++ crates/views/src/screens/stats/insights.rs | 326 +++++ crates/views/src/screens/stats/mod.rs | 380 ++++++ crates/views/src/screens/stats/rankings.rs | 482 +++++++ crates/views/src/screens/stats/timeline.rs | 511 ++++++++ crates/views/src/shared/cells.rs | 20 + crates/views/src/shared/shelves.rs | 56 +- 53 files changed, 5384 insertions(+), 31 deletions(-) create mode 100644 assets/icons/lucide/briefcase.svg create mode 100644 assets/icons/lucide/calendar-days.svg create mode 100644 assets/icons/lucide/compass.svg create mode 100644 assets/icons/lucide/flame.svg create mode 100644 assets/icons/lucide/gem.svg create mode 100644 assets/icons/lucide/rocket.svg create mode 100644 assets/icons/lucide/snail.svg create mode 100644 assets/icons/lucide/sparkles.svg create mode 100644 assets/icons/lucide/star.svg create mode 100644 assets/icons/lucide/sun.svg create mode 100644 assets/icons/lucide/sunrise.svg create mode 100644 assets/icons/lucide/sunset.svg create mode 100644 assets/icons/lucide/trending-up.svg create mode 100644 assets/icons/lucide/zap.svg create mode 100644 crates/music/src/spotify/descriptors.rs create mode 100644 crates/music/src/spotify/pathfinder/stats.rs create mode 100644 crates/music/src/stats.rs create mode 100644 crates/state/src/stats.rs create mode 100644 crates/views/src/screens/stats/charts.rs create mode 100644 crates/views/src/screens/stats/insights.rs create mode 100644 crates/views/src/screens/stats/mod.rs create mode 100644 crates/views/src/screens/stats/rankings.rs create mode 100644 crates/views/src/screens/stats/timeline.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index 8fd78368a..a5c0568a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - Click the tray icon on Linux to show Sonora's window, or to hide it into the tray when it is open. - Choose Wide under Settings, Appearance, Page width to let pages fill a large window again instead of staying centred. +- Stats page for Spotify, Last.fm or your recorded plays, with your top artists, songs and albums, genres, moods, release years, a listening clock, milestones and a summary of your listening style, over a window or any dates you pick. ### Fixed diff --git a/Cargo.lock b/Cargo.lock index f09f6db3f..46a0c2212 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7687,6 +7687,7 @@ dependencies = [ "i18n", "icons", "image", + "jiff", "libc", "log", "moka", diff --git a/assets/i18n/en-US/main.ftl b/assets/i18n/en-US/main.ftl index f1a1cb082..5bb4ae4b7 100644 --- a/assets/i18n/en-US/main.ftl +++ b/assets/i18n/en-US/main.ftl @@ -24,6 +24,8 @@ range-to = To rail-back = Scroll back rail-forward = Scroll forward number-group = { "," } +number-thousand = { $value }k +number-million = { $value }M # navigation nav-history = Recents @@ -614,6 +616,22 @@ count-songs = [one] { $count } song *[other] { $count } songs } +count-artists = { $count -> + [one] { $count } artist + *[other] { $count } artists + } +count-albums = { $count -> + [one] { $count } album + *[other] { $count } albums + } +count-plays = { $count -> + [one] { $count } play + *[other] { $count } plays + } +count-days = { $count -> + [one] { $count } day + *[other] { $count } days + } count-tracks = { $count -> [one] { $count } track @@ -1656,3 +1674,128 @@ response-graph-readout = { $frequency } · { $direction -> [down] -{ $gain } *[flat] { $gain } } dB + +# Listening statistics +nav-stats = Stats +stats-source = Statistics source +stats-recorded = Local +stats-period-title = Listening window +stats-window-fixed = This source only offers one window. +stats-four-weeks = Last 4 weeks +stats-six-months = Last 6 months +stats-year = Last year +stats-week = Last week +stats-month = Last month +stats-quarter = Last 3 months +stats-all-time = All time +stats-selected-dates = { $from } – { $to } +stats-now = Now +stats-date-hint = YYYY-MM-DD +stats-failed = Could not load listening stats. Try again, or choose Local for recorded plays. +stats-empty = No listening data for this period yet. +stats-top-artists = Top artists +stats-top-songs = Top songs +stats-top-albums = Top albums +stats-top-genres = Top genres +stats-top-moods = Top moods +stats-top-tags = Top tags +stats-top-songwriters = Top songwriters +stats-top-producers = Top producers +stats-badge-new = { $count } new +stats-badge-plays = { $count -> + [one] { $value } play + *[other] { $value } plays + } +stats-badge-hours = { $count -> + [one] { $count } hour listened + *[other] { $count } hours listened + } +stats-badge-minutes = { $count -> + [one] { $count } minute listened + *[other] { $count } minutes listened + } +stats-badge-replays = { $share }% replays +stats-badge-change = { $change }% vs before +stats-badge-per-day = { $count -> + [one] { $count } play per day + *[other] { $count } plays per day + } +stats-badge-length = Average { $length } +stats-badge-mainstream = Mainstream { $score } +stats-badge-collabs = { $share }% collaborations +stats-badge-era = Peak era { $from }–{ $to } +stats-badge-recent = { $share }% recent +stats-badge-peak = Peak { $hour } +stats-mark-busiest = Busiest day · { $day } · { count-plays } +stats-mark-streak = Longest streak · { count-days } +stats-style-title = Your listening style +stats-milestones-title = Milestones +stats-milestone-first = First play +stats-milestone-nth = Play #{ $count } +stats-years-title = Release years +stats-years-label = Songs by release year, { $from } to { $to } +stats-mood-energetic = Energetic +stats-mood-danceable = Danceable +stats-mood-positive = Positive +stats-mood-negative = Negative +stats-mood-sad = Sad +stats-mood-calming = Calming +stats-mood-instrumental = Instrumental +stats-mood-acoustic = Acoustic +stats-tempo-title = Tempo +stats-tempo-label = Songs by tempo, { $from } to { $to } beats per minute +stats-tempo-bpm = { $bpm } BPM +stats-tempo-songs = { $from }–{ $to } BPM · { count-songs } +stats-badge-bpm = Average { $bpm } BPM +stats-year-songs = { $year } · { count-songs } +stats-trait-early-bird = Early bird +stats-trait-early-bird-note = You listen most in the morning. +stats-trait-daytime = Daytime listener +stats-trait-daytime-note = Your listening peaks in the afternoon. +stats-trait-evening = Evening listener +stats-trait-evening-note = You wind down with music in the evening. +stats-trait-night-owl = Night owl +stats-trait-night-owl-note = Your listening peaks late at night. +stats-trait-weekender = Weekend listener +stats-trait-weekender-note = Most of your music is played on weekends. +stats-trait-weekday = Weekday listener +stats-trait-weekday-note = You mostly listen on weekdays. +stats-trait-explorer = Explorer +stats-trait-explorer-note = You keep finding new songs. +stats-trait-loyalist = Loyalist +stats-trait-loyalist-note = You stay with the songs you love. +stats-trait-mainstream = Mainstream +stats-trait-mainstream-note = Your songs are popular with everyone. +stats-trait-deep-diver = Deep diver +stats-trait-deep-diver-note = You dig into songs few others play. +stats-trait-throwback = Throwback +stats-trait-throwback-note = Your songs come from another era. +stats-trait-fresh-ears = Fresh ears +stats-trait-fresh-ears-note = Most of what you play is brand new. +stats-trait-collaborator = Collab lover +stats-trait-collaborator-note = You love songs with more than one artist. +stats-trait-superfan = Superfan +stats-trait-superfan-note = One artist makes up a quarter of your plays. +stats-trait-daily = Daily listener +stats-trait-daily-note = You listened every day for a week or more. +stats-trait-rising = On the rise +stats-trait-rising-note = You are listening much more than before. +stats-trait-fast-lane = Fast lane +stats-trait-fast-lane-note = Your songs are quick and high in energy. +stats-trait-slow-burner = Slow burner +stats-trait-slow-burner-note = Your songs take their time. +stats-genre-share = { $genre } · { $percent }% +stats-clock-title = Listening clock +stats-clock-day = { $day }: { count-plays } +stats-weekday = { $day -> + [0] Mon + [1] Tue + [2] Wed + [3] Thu + [4] Fri + [5] Sat + *[other] Sun + } +stats-rank = #{ $rank } +stats-rank-new = New +stats-rank-popularity = { $score } popularity diff --git a/assets/icons/lucide/briefcase.svg b/assets/icons/lucide/briefcase.svg new file mode 100644 index 000000000..ef4dbd857 --- /dev/null +++ b/assets/icons/lucide/briefcase.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/lucide/calendar-days.svg b/assets/icons/lucide/calendar-days.svg new file mode 100644 index 000000000..78c5420d4 --- /dev/null +++ b/assets/icons/lucide/calendar-days.svg @@ -0,0 +1,22 @@ + + + + + + + + + + + + diff --git a/assets/icons/lucide/compass.svg b/assets/icons/lucide/compass.svg new file mode 100644 index 000000000..1a4e8c7dc --- /dev/null +++ b/assets/icons/lucide/compass.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/lucide/flame.svg b/assets/icons/lucide/flame.svg new file mode 100644 index 000000000..9a7749168 --- /dev/null +++ b/assets/icons/lucide/flame.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/lucide/gem.svg b/assets/icons/lucide/gem.svg new file mode 100644 index 000000000..1b142584c --- /dev/null +++ b/assets/icons/lucide/gem.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/assets/icons/lucide/rocket.svg b/assets/icons/lucide/rocket.svg new file mode 100644 index 000000000..6c006f11b --- /dev/null +++ b/assets/icons/lucide/rocket.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/lucide/snail.svg b/assets/icons/lucide/snail.svg new file mode 100644 index 000000000..35d5dd2fc --- /dev/null +++ b/assets/icons/lucide/snail.svg @@ -0,0 +1,17 @@ + + + + + + + diff --git a/assets/icons/lucide/sparkles.svg b/assets/icons/lucide/sparkles.svg new file mode 100644 index 000000000..2d749398b --- /dev/null +++ b/assets/icons/lucide/sparkles.svg @@ -0,0 +1,16 @@ + + + + + + diff --git a/assets/icons/lucide/star.svg b/assets/icons/lucide/star.svg new file mode 100644 index 000000000..b35bedd29 --- /dev/null +++ b/assets/icons/lucide/star.svg @@ -0,0 +1,13 @@ + + + diff --git a/assets/icons/lucide/sun.svg b/assets/icons/lucide/sun.svg new file mode 100644 index 000000000..3ecadd68c --- /dev/null +++ b/assets/icons/lucide/sun.svg @@ -0,0 +1,21 @@ + + + + + + + + + + + diff --git a/assets/icons/lucide/sunrise.svg b/assets/icons/lucide/sunrise.svg new file mode 100644 index 000000000..11c3f5b8b --- /dev/null +++ b/assets/icons/lucide/sunrise.svg @@ -0,0 +1,20 @@ + + + + + + + + + + diff --git a/assets/icons/lucide/sunset.svg b/assets/icons/lucide/sunset.svg new file mode 100644 index 000000000..5e899c5ea --- /dev/null +++ b/assets/icons/lucide/sunset.svg @@ -0,0 +1,20 @@ + + + + + + + + + + diff --git a/assets/icons/lucide/trending-up.svg b/assets/icons/lucide/trending-up.svg new file mode 100644 index 000000000..2ff1fb202 --- /dev/null +++ b/assets/icons/lucide/trending-up.svg @@ -0,0 +1,14 @@ + + + + diff --git a/assets/icons/lucide/zap.svg b/assets/icons/lucide/zap.svg new file mode 100644 index 000000000..6dde2a649 --- /dev/null +++ b/assets/icons/lucide/zap.svg @@ -0,0 +1,13 @@ + + + diff --git a/crates/music/src/lib.rs b/crates/music/src/lib.rs index 0ebc97276..a64cac0be 100644 --- a/crates/music/src/lib.rs +++ b/crates/music/src/lib.rs @@ -36,6 +36,7 @@ pub mod soloist; mod spectrum; mod sponsorblock; pub mod spotify; +mod stats; mod stream; pub mod subsonic; pub mod tidal; @@ -57,10 +58,11 @@ pub use audio::Meter; pub use equalizer::Equalizer; pub use models::{ Album, AlbumCatalogue, AlbumDetail, Arrival, Artist, ArtistCatalogue, ArtistProfile, ArtistRef, - Contributor, CoverSize, Credit, Found, Genre, GenreDetail, GenreItem, GenreSection, HomeFeed, - ImportedPlaylist, Lyrics, LyricsHit, LyricsLane, LyricsLine, LyricsQuery, LyricsWord, - PinOutcome, PinTarget, PinTargetKind, Playlist, PlaylistDetail, ReleaseType, RomanizedText, - SavedArtist, Track, TrackKey, TrackTags, UserDetail, UserProfile, Voice, WritingSystem, + Contributor, CoverSize, Credit, Descriptors, Found, Genre, GenreDetail, GenreItem, + GenreSection, HomeFeed, ImportedPlaylist, Lyrics, LyricsHit, LyricsLane, LyricsLine, + LyricsQuery, LyricsWord, PinOutcome, PinTarget, PinTargetKind, Playlist, PlaylistDetail, + ReleaseType, RomanizedText, SavedArtist, Track, TrackKey, TrackTags, UserDetail, UserProfile, + Voice, WritingSystem, }; pub use output::{Server as SoundServer, missing_bridge}; pub use redact::redact; @@ -70,6 +72,10 @@ pub use smart::{ }; pub use spectrum::{Analyzer, Level, Listening, Spectrum, Watch}; pub use sponsorblock::{SkipSegment, SponsorBlock}; +pub use stats::{ + Board, ListeningStats, Milestone, Overview, Ranked, StatsPeriod, Trait, album_key, album_of, + compare, credits, milestone_numbers, tag_key, +}; pub const LOCAL_TRACK_PREFIX: &str = "local:"; pub const LOCAL_ALBUM_PREFIX: &str = "local-album:"; @@ -176,6 +182,12 @@ pub trait MusicApi: Send + Sync { async fn artist_profile(&self, artist_id: &str) -> Result; async fn artist_images(&self, ids: Vec) -> Result>; + /// Genres, moods, tags and tempo for tracks by id. A track the provider does not describe is + /// left out, and a provider that describes none returns an empty map. + async fn descriptors(&self, _track_ids: &[String]) -> Result> { + Ok(HashMap::new()) + } + /// The tracks the user starred. On a `Shape::Saved` provider this is the whole songs /// library; on a `Shape::Catalog` one it only feeds the hearts and the favorites filter. async fn saved_tracks(&self) -> Result>; @@ -239,6 +251,16 @@ pub trait MusicApi: Send + Sync { Ok(Vec::new()) } + /// The periods this provider can rank from its own listening data. Empty means unsupported. + fn stats_periods(&self) -> &'static [StatsPeriod] { + &[] + } + + /// Personal rankings across devices, in the provider's order; counts may be unavailable. + async fn stats(&self, _period: StatsPeriod) -> Result { + anyhow::bail!("this provider does not expose listening stats") + } + async fn playlists(&self) -> Result>; /// Changes the provider's own pin for `uri`, one of the uris `pin_targets` lists or /// `pin_uri` builds. diff --git a/crates/music/src/models.rs b/crates/music/src/models.rs index 070881c08..94fcb4f52 100644 --- a/crates/music/src/models.rs +++ b/crates/music/src/models.rs @@ -70,6 +70,20 @@ pub struct Credit { pub id: Option, } +/// What a provider says a track is about and how it sounds, for filtering a list by it. Every +/// part may be empty, and a track the provider does not describe has none. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct Descriptors { + /// Genres and other descriptive words, lowercase, as the provider words them. + pub genres: Vec, + pub tags: Vec, + /// The Fluent keys of the feelings the audio carries, such as `stats-mood-energetic`. + pub moods: Vec, + /// Beats per minute, where the provider analysed the audio. + pub bpm: Option, +} + /// A song or episode as a provider lists it. The default is an unplayable track with no id, so a /// caller that builds one from `..Default::default()` sets `playable` itself. #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] diff --git a/crates/music/src/scrobble/audioscrobbler.rs b/crates/music/src/scrobble/audioscrobbler.rs index b9d9909d1..f0bf822f8 100644 --- a/crates/music/src/scrobble/audioscrobbler.rs +++ b/crates/music/src/scrobble/audioscrobbler.rs @@ -1,7 +1,8 @@ use std::time::Duration; -use anyhow::{Context as _, Result, bail}; +use anyhow::{Context as _, Result, bail, ensure}; use async_trait::async_trait; +use futures::StreamExt as _; use md5::{Digest, Md5}; use percent_encoding::percent_decode_str; use serde::Deserialize; @@ -9,7 +10,12 @@ use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; use tokio::net::TcpListener; use super::{Account, Link, Play, Secret, Service}; -use crate::escape; +use crate::{ + Album, ListeningStats, Milestone, Overview, Ranked, SavedArtist, Track, compare, + milestone_numbers, +}; +use crate::{escape, tag_key}; +use serde_json::Value; /// The loopback address the browser hands the token back on. const PORT: u16 = 8990; @@ -18,6 +24,16 @@ const PATH: &str = "/scrobble"; const WAIT: Duration = Duration::from_secs(300); /// How many listens last.fm's `track.scrobble` takes in one call. const LASTFM_BATCH: usize = 50; +/// How many plays one page of recent tracks holds, and how many pages are read for the hours someone listens at. +const ACTIVITY_PAGE: &str = "200"; +const ACTIVITY_PAGES: usize = 4; +/// How many slices of the account's history are asked about at once. +const DENSITY_AT_ONCE: usize = 8; +/// How many slices the account's history is cut into to show when it was played. +const SLICES: usize = 24; +/// How many ranked artists, songs and albums are kept, and how many rows a weekly chart can hold. +const RANKED: usize = 50; +const CHART_ROWS: usize = 1000; const PAGE: &str = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\ Sonora is connected. You can close this window."; @@ -37,6 +53,8 @@ pub struct AudioScrobbler { /// How many listens one `track.scrobble` carries. One means the server only implements the /// single unindexed form, which is what GNU FM does. batch: usize, + /// Whether the service reads personal rankings between any two dates. + dated: bool, } pub const LASTFM: AudioScrobbler = AudioScrobbler { @@ -46,6 +64,7 @@ pub const LASTFM: AudioScrobbler = AudioScrobbler { signup: Some("https://www.last.fm/api/account/create"), link: Link::Keys, batch: LASTFM_BATCH, + dated: true, }; pub const LIBREFM: AudioScrobbler = AudioScrobbler { @@ -55,6 +74,7 @@ pub const LIBREFM: AudioScrobbler = AudioScrobbler { signup: None, link: Link::Browser, batch: 1, + dated: false, }; #[async_trait] @@ -139,6 +159,473 @@ impl Service for AudioScrobbler { } Ok(()) } + + fn stats_dated(&self) -> bool { + self.dated + } + + async fn history(&self, account: &Account) -> Result { + ensure!(self.stats_dated(), "{} does not expose history", self.id); + let info = self + .read("user.getInfo", &[("user", account.name.as_str())], account) + .await?; + let user = info.get("user").unwrap_or(&info); + let (milestones, density) = tokio::join!( + async { + match number(user, "playcount") { + Some(total) => self.milestones(account, total).await, + None => Vec::new(), + } + }, + async { + match registered(user) { + Some(since) => self.density(account, since).await, + None => Vec::new(), + } + }, + ); + Ok(ListeningStats { + milestones, + density, + ..Default::default() + }) + } + + async fn stats(&self, account: &Account, dates: Option<(i64, i64)>) -> Result { + ensure!(self.stats_dated(), "{} does not expose stats", self.id); + let user = account.name.as_str(); + let profile = [("user", user)]; + let tags = [("user", user), ("limit", "30")]; + // A range is also read for the equal stretch before it, to see how the listening moved. + let earlier = dates.map(|(from, to)| (2 * from - to - 1, from - 1)); + let (charts, info, tags, activity, before) = tokio::join!( + self.charts(account, dates), + self.read("user.getInfo", &profile, account), + self.read("user.getTopTags", &tags, account), + self.activity(account, dates), + async { + match earlier { + Some(range) => Some(tokio::join!( + self.charts(account, Some(range)), + self.plays_between(account, range) + )), + None => None, + } + }, + ); + let mut charts = charts?; + let mut overview = Overview { + artists: charts.distinct[0], + tracks: charts.distinct[1], + albums: charts.distinct[2], + ..Default::default() + }; + if let Some((plays, times)) = activity { + overview.plays = Some(plays); + // Only the latest plays are read, so their days and streaks say nothing of the rest. + let complete = times.len() >= plays; + overview = overview.timed(×); + if !complete { + overview = overview.partial(); + } + } + if let Some((Ok(before), plays_before @ Some(1..))) = before { + let key = |name: &str, artist: &str| format!("{name}\u{1}{artist}"); + compare( + &mut charts.artists, + before.artists.iter().map(|row| row.item.name.clone()), + |artist| artist.name.clone(), + ); + compare( + &mut charts.tracks, + before + .tracks + .iter() + .map(|row| key(&row.item.name, &row.item.artists)), + |track| key(&track.name, &track.artists), + ); + compare( + &mut charts.albums, + before + .albums + .iter() + .map(|row| key(&row.item.name, &row.item.artists)), + |album| key(&album.name, &album.artists), + ); + overview.change = overview + .plays + .zip(plays_before) + .map(|(now, was)| ((now as i64 - was as i64) * 100 / was as i64) as i32); + } + let user = info + .as_ref() + .ok() + .map(|info| info.get("user").unwrap_or(info)); + overview.since = user.and_then(registered); + if let (None, Some(user)) = (dates, user) { + // The window is the whole account, so its totals are the account's. + let plays = number(user, "playcount"); + let per_day = plays.zip(overview.since).and_then(|(plays, since)| { + let days = (jiff::Timestamp::now().as_second() - since) as f32 / 86_400.; + (days >= 1.).then(|| plays as f32 / days) + }); + overview = Overview { + plays, + artists: number(user, "artist_count"), + tracks: number(user, "track_count"), + albums: number(user, "album_count"), + plays_per_day: per_day, + ..overview + }; + } + let genres = tags + .map(|tags| { + rows(&tags, "toptags", "tag") + .into_iter() + .filter(|tag| tag_key(&string(tag, "name")).is_some()) + .map(|tag| Ranked::new(string(tag, "name"), number(tag, "count"))) + .collect() + }) + .unwrap_or_default(); + Ok(ListeningStats { + artists: charts.artists, + tracks: charts.tracks, + albums: charts.albums, + genres, + overview, + ..Default::default() + }) + } +} + +/// The top artists, songs and albums of a stretch of time, and how many distinct ones the +/// stretch holds where that is known. +struct Charts { + artists: Vec>, + tracks: Vec>, + albums: Vec>, + distinct: [Option; 3], +} + +impl AudioScrobbler { + /// Reads one unsigned read method, which is open to the account's public profile. + async fn read(&self, method: &str, query: &[(&str, &str)], account: &Account) -> Result { + let key = match account.key.is_empty() { + true => ANONYMOUS, + false => &account.key, + }; + let answer = super::http() + .get(self.endpoint) + .query(&[("method", method), ("api_key", key), ("format", "json")]) + .query(query) + .send() + .await + .with_context(|| format!("cannot reach {} {method}", self.id))?; + let status = answer.status(); + let value: Value = answer + .json() + .await + .with_context(|| format!("cannot decode {} {method} (HTTP {status})", self.id))?; + if !status.is_success() || value.get("error").is_some() { + bail!( + "{} {method} refused the request (HTTP {status}): {value}", + self.id + ); + } + Ok(value) + } + + /// Plays in each equal slice of the account's history, one count request for each slice. An + /// account that cannot be read at all has none. + async fn density(&self, account: &Account, since: i64) -> Vec { + let now = jiff::Timestamp::now().as_second(); + let width = ((now - since) / SLICES as i64).max(1); + // A few at a time keeps Last.fm from refusing the burst, and a slice it refused is asked + // for once more. + let counts: Vec> = futures::stream::iter(0..SLICES as i64) + .map(|slice| async move { + let range = (since + slice * width, since + slice * width + width - 1); + match self.plays_between(account, range).await { + None => self.plays_between(account, range).await, + found => found, + } + }) + .buffered(DENSITY_AT_ONCE) + .collect() + .await; + match counts.iter().any(Option::is_some) { + true => counts.into_iter().map(Option::unwrap_or_default).collect(), + false => Vec::new(), + } + } + + /// The plays of the whole history that reached a round number. Reading them newest first one + /// to a page, the nth play is on page `total - n + 1`. + async fn milestones(&self, account: &Account, total: usize) -> Vec { + let reads = milestone_numbers(total) + .into_iter() + .map(|number| async move { + let recent = self.recent(account, "1", total - number + 1, None).await?; + // A song playing right now leads every page and has no date, so it is skipped. + let track = rows(&recent, "recenttracks", "track") + .into_iter() + .find(|track| track.get("date").is_some())?; + let at = number_of(track.get("date")?, "uts")?; + Some(Milestone { + number, + title: string(track, "name"), + artist: credited(track), + at, + }) + }); + let mut found: Vec<_> = futures::future::join_all(reads) + .await + .into_iter() + .flatten() + .collect(); + found.sort_by_key(|milestone| milestone.number); + found + } + + /// The top artists, songs and albums between two dates, or of all time. The weekly chart + /// methods take any two dates, and Last.fm says as much of the range as it holds up to 1000. + async fn charts(&self, account: &Account, dates: Option<(i64, i64)>) -> Result { + let user = account.name.as_str(); + let (from, to) = dates + .map(|(from, to)| (from.to_string(), to.to_string())) + .unzip(); + let ranged = [ + ("user", user), + ("from", from.as_deref().unwrap_or_default()), + ("to", to.as_deref().unwrap_or_default()), + ]; + let overall = [("user", user), ("period", "overall"), ("limit", "50")]; + let (query, methods, parents) = match dates { + Some(_) => ( + &ranged[..], + [ + "user.getWeeklyArtistChart", + "user.getWeeklyTrackChart", + "user.getWeeklyAlbumChart", + ], + ["weeklyartistchart", "weeklytrackchart", "weeklyalbumchart"], + ), + None => ( + &overall[..], + [ + "user.getTopArtists", + "user.getTopTracks", + "user.getTopAlbums", + ], + ["topartists", "toptracks", "topalbums"], + ), + }; + let (artists, tracks, albums) = tokio::try_join!( + self.read(methods[0], query, account), + self.read(methods[1], query, account), + self.read(methods[2], query, account), + )?; + let ranged = dates.is_some(); + let (artist_rows, artist_total) = kept(&artists, parents[0], "artist", ranged); + let (track_rows, track_total) = kept(&tracks, parents[1], "track", ranged); + let (album_rows, album_total) = kept(&albums, parents[2], "album", ranged); + Ok(Charts { + artists: artist_rows + .into_iter() + .map(|row| { + let artist = SavedArtist { + name: string(row, "name"), + cover: image(row), + ..Default::default() + }; + chart_row(row, artist) + }) + .collect(), + tracks: track_rows + .into_iter() + .map(|row| { + let track = Track { + name: string(row, "name"), + artists: credited(row), + album: row + .get("album") + .map(|album| string(album, "#text")) + .unwrap_or_default(), + cover: image(row).or_else(|| row.get("album").and_then(image)), + ..Default::default() + }; + chart_row(row, track) + }) + .collect(), + albums: album_rows + .into_iter() + .map(|row| { + let album = Album { + name: string(row, "name"), + artists: credited(row), + cover: image(row), + ..Default::default() + }; + chart_row(row, album) + }) + .collect(), + distinct: [artist_total, track_total, album_total], + }) + } + + /// One page of the recent tracks, newest first, optionally within a range of dates. + async fn recent( + &self, + account: &Account, + limit: &str, + page: usize, + dates: Option<(i64, i64)>, + ) -> Option { + let page = page.to_string(); + let (from, to) = dates + .map(|(from, to)| (from.to_string(), to.to_string())) + .unzip(); + let mut query = vec![ + ("user", account.name.as_str()), + ("limit", limit), + ("page", page.as_str()), + ]; + query.extend(from.as_deref().map(|from| ("from", from))); + query.extend(to.as_deref().map(|to| ("to", to))); + self.read("user.getRecentTracks", &query, account) + .await + .ok() + } + + /// How many plays there are between two dates, which the first page of a range says. + async fn plays_between(&self, account: &Account, range: (i64, i64)) -> Option { + attr_total( + &self.recent(account, "1", 1, Some(range)).await?, + "recenttracks", + ) + } + + /// How many plays there are between two dates (or ever), and the start times of the latest + /// of them, newest first. Every page is asked for at once, since the first only says how + /// many there are, and a page past the end comes back empty. + async fn activity( + &self, + account: &Account, + dates: Option<(i64, i64)>, + ) -> Option<(usize, Vec)> { + let pages = + (1..=ACTIVITY_PAGES).map(|page| self.recent(account, ACTIVITY_PAGE, page, dates)); + let mut chunks = futures::future::join_all(pages).await.into_iter(); + let first = chunks.next()??; + let plays = attr_total(&first, "recenttracks")?; + let times = std::iter::once(first) + .chain(chunks.flatten()) + .flat_map(|chunk| { + rows(&chunk, "recenttracks", "track") + .into_iter() + .filter_map(|play| number_of(play.get("date")?, "uts")) + .collect::>() + }) + .collect(); + Some((plays, times)) + } +} + +/// The top rows of a chart and how many distinct rows it holds. A ranged chart is cut off at +/// `CHART_ROWS`, past which its size is unknown. +fn kept<'a>( + chart: &'a Value, + parent: &str, + child: &str, + ranged: bool, +) -> (Vec<&'a Value>, Option) { + let all = rows(chart, parent, child); + let distinct = match ranged { + true => (all.len() < CHART_ROWS).then_some(all.len()), + false => attr_total(chart, parent), + }; + (all.into_iter().take(RANKED).collect(), distinct) +} + +/// The total a Last.fm list reports for itself, under the list's `@attr`. +fn attr_total(value: &Value, parent: &str) -> Option { + number(value.get(parent)?.get("@attr")?, "total") +} + +/// A chart row's item with its play count and Last.fm page. +fn chart_row(row: &Value, item: T) -> Ranked { + Ranked::new(item, number(row, "playcount")).linked(lastfm_url(row)) +} + +/// An allow-listed Last.fm page, used as the identity of a chart entry with no catalogue match. +fn lastfm_url(value: &Value) -> Option { + let url = string(value, "url"); + (url.starts_with("https://www.last.fm/") || url.starts_with("https://last.fm/")).then_some(url) +} + +/// The largest real artwork entry, skipping Last.fm's generic placeholder. +fn image(value: &Value) -> Option { + value + .get("image") + .and_then(Value::as_array)? + .iter() + .rev() + .filter_map(|image| image.get("#text")?.as_str()) + .map(str::trim) + .find(|url| !url.is_empty() && !url.contains("2a96cbd8b46e442fc41c2b86b821562f")) + .map(str::to_owned) +} + +/// The chart rows under `parent.child`, which Last.fm sends as a lone object for a single row. +fn rows<'a>(value: &'a Value, parent: &str, child: &str) -> Vec<&'a Value> { + match value.get(parent).and_then(|value| value.get(child)) { + Some(Value::Array(items)) => items.iter().collect(), + Some(item @ Value::Object(_)) => vec![item], + _ => Vec::new(), + } +} + +/// The artist of a track or album row, which is either a name or an object holding one. +fn credited(row: &Value) -> String { + row.get("artist") + .map(|artist| match artist.is_string() { + true => artist.as_str().unwrap_or_default().to_owned(), + false => Some(string(artist, "name")) + .filter(|name| !name.is_empty()) + .unwrap_or_else(|| string(artist, "#text")), + }) + .unwrap_or_default() +} + +fn string(value: &Value, key: &str) -> String { + value + .get(key) + .and_then(Value::as_str) + .unwrap_or_default() + .to_owned() +} + +/// When the account registered, in Unix seconds. +fn registered(user: &Value) -> Option { + number_of(user.get("registered")?, "unixtime") +} + +/// A time in Unix seconds that Last.fm sends as a string. +fn number_of(value: &Value, key: &str) -> Option { + number(value, key).and_then(|seconds| i64::try_from(seconds).ok()) +} + +/// A count Last.fm sends as a string. +fn number(value: &Value, key: &str) -> Option { + let number = value.get(key)?; + number + .as_str() + .and_then(|text| text.parse().ok()) + .or_else(|| { + number + .as_u64() + .and_then(|count| usize::try_from(count).ok()) + }) } impl AudioScrobbler { diff --git a/crates/music/src/scrobble/mod.rs b/crates/music/src/scrobble/mod.rs index f7a4491de..ee7be79db 100644 --- a/crates/music/src/scrobble/mod.rs +++ b/crates/music/src/scrobble/mod.rs @@ -5,6 +5,8 @@ use anyhow::Result; use async_trait::async_trait; use serde::{Deserialize, Serialize}; +use crate::ListeningStats; + mod audioscrobbler; mod listenbrainz; mod maloja; @@ -146,6 +148,28 @@ pub trait Service: Send + Sync { /// The account is one `connect` returned, since a row only submits while its account is /// linked and switched on. async fn scrobble(&self, account: &Account, plays: &[Play]) -> Result<()>; + + /// Whether the linked account can read personal rankings between any two dates. + fn stats_dated(&self) -> bool { + false + } + + /// Reads what only the whole account can say, which a range never changes: the round-number + /// plays and the plays across the account's history. It is read once, apart from the rankings, + /// so that they are not kept waiting for it. + async fn history(&self, _account: &Account) -> Result { + anyhow::bail!("{} does not expose listening history", self.id()) + } + + /// Reads personal rankings between two dates in Unix seconds, or of all time, without + /// changing the service's scrobble state. + async fn stats( + &self, + _account: &Account, + _dates: Option<(i64, i64)>, + ) -> Result { + anyhow::bail!("{} does not expose listening stats", self.id()) + } } /// The one http client every service shares, so they pool connections and reuse TLS sessions diff --git a/crates/music/src/spotify/client.rs b/crates/music/src/spotify/client.rs index 325f1c98b..0e408277e 100644 --- a/crates/music/src/spotify/client.rs +++ b/crates/music/src/spotify/client.rs @@ -10,12 +10,13 @@ use librespot_protocol::playlist4_external::SelectedListContent as RootList; use protobuf::Message as _; use crate::spotify::{ - albums, artists, collection, collection2, pathfinder, playlists, profiles, radio, search, wire, + albums, artists, collection, collection2, descriptors, pathfinder, playlists, profiles, radio, + search, wire, }; use crate::{ - Album, AlbumCatalogue, AlbumDetail, Artist, ArtistCatalogue, ArtistProfile, CoverSize, Genre, - GenreDetail, GenreItem, GenreSection, HomeFeed, Playlist, PlaylistDetail, SUGGESTIONS, - SavedArtist, Track, UserDetail, UserProfile, + Album, AlbumCatalogue, AlbumDetail, Artist, ArtistCatalogue, ArtistProfile, CoverSize, + Descriptors, Genre, GenreDetail, GenreItem, GenreSection, HomeFeed, ListeningStats, Playlist, + PlaylistDetail, SUGGESTIONS, SavedArtist, StatsPeriod, Track, UserDetail, UserProfile, }; const MADE_FOR_YOU: &str = "0JQ5DAt0tbjZptfcdMSKl3"; @@ -63,6 +64,18 @@ impl MusicApi for LibrespotClient { )) } + async fn descriptors(&self, ids: &[String]) -> Result> { + descriptors::read(&self.session, ids).await + } + + fn stats_periods(&self) -> &'static [StatsPeriod] { + &[StatsPeriod::Weeks, StatsPeriod::Months, StatsPeriod::Year] + } + + async fn stats(&self, period: StatsPeriod) -> Result { + pathfinder::stats(&self.session, period).await + } + async fn profile(&self) -> Result { Ok(profiles::own(&self.session).await) } diff --git a/crates/music/src/spotify/collection.rs b/crates/music/src/spotify/collection.rs index d34e57612..4876a9c87 100644 --- a/crates/music/src/spotify/collection.rs +++ b/crates/music/src/spotify/collection.rs @@ -116,7 +116,7 @@ pub(crate) async fn batched( Ok(()) } -fn track_from(uri: &str, track: &TrackMessage) -> Track { +pub(crate) fn track_from(uri: &str, track: &TrackMessage) -> Track { let (artists, artist_refs) = artists_from(&track.artist); Track { diff --git a/crates/music/src/spotify/descriptors.rs b/crates/music/src/spotify/descriptors.rs new file mode 100644 index 000000000..db37fcd28 --- /dev/null +++ b/crates/music/src/spotify/descriptors.rs @@ -0,0 +1,158 @@ +use std::collections::HashMap; + +use anyhow::{Context as _, Result}; +use librespot_core::Session; +use librespot_protocol::extension_kind::ExtensionKind; +use serde::Deserialize; + +use crate::Descriptors; +use crate::spotify::{collection, pb}; + +const TRACK_PREFIX: &str = "spotify:track:"; +/// How many tracks one audio features request names. +const FEATURES_AT_ONCE: usize = 100; + +/// Reads the genres, moods, descriptive words and tempo of tracks by id, over librespot's own +/// metadata transport and spclient, never the Web API. Either source can fail alone and the other +/// still describes the tracks; only both failing is an error. +pub(crate) async fn read( + session: &Session, + ids: &[String], +) -> Result> { + let uris: Vec<_> = ids.iter().map(|id| format!("{TRACK_PREFIX}{id}")).collect(); + let (words, sound) = tokio::join!(words(session, &uris), features(session, ids)); + if let (Err(error), Err(_)) = (&words, &sound) { + anyhow::bail!("cannot read track descriptors: {error:#}"); + } + let mut words = words.unwrap_or_default(); + let sound = sound.unwrap_or_default(); + Ok(ids + .iter() + .map(|id| { + let mut found = words + .remove(&format!("{TRACK_PREFIX}{id}")) + .unwrap_or_default(); + if let Some(features) = sound.get(id) { + found.moods = features.moods().into_iter().map(str::to_owned).collect(); + found.bpm = Some(features.tempo).filter(|bpm| *bpm > 0.); + } + (id.clone(), found) + }) + .collect()) +} + +/// Reads the typed descriptor words of each track, by uri. A track with none is left untagged. +async fn words(session: &Session, uris: &[String]) -> Result> { + let entities = collection::extended(session, uris, ExtensionKind::TRACK_DESCRIPTOR).await?; + entities + .into_iter() + .map(|entity| Ok((entity.entity_uri, concepts(&entity.extension_data.value)?))) + .collect() +} + +/// Reads descriptor text and its repeated type enums: type 1 is a genre, and any other word is a +/// tag. +fn concepts(bytes: &[u8]) -> Result { + let mut reader = pb::Reader::new(bytes); + let mut found = Descriptors::default(); + while let Some((field, value)) = reader.field()? { + let (1, pb::Value::Bytes(descriptor)) = (field, value) else { + continue; + }; + let mut descriptor = pb::Reader::new(descriptor); + let mut text = None; + let mut kinds = Vec::new(); + while let Some((field, value)) = descriptor.field()? { + match (field, value) { + (1, pb::Value::Bytes(value)) => text = Some(pb::text(value)?), + (3, pb::Value::Varint(value)) => kinds.push(value), + (3, pb::Value::Bytes(values)) => kinds.extend(pb::varints(values)?), + _ => {} + } + } + let Some(text) = text else { continue }; + let text = text.trim().to_lowercase(); + let text = text + .strip_prefix("spotify:concept:") + .unwrap_or(&text) + .replace('_', " "); + if text.is_empty() || text == "track" { + continue; + } + let list = match kinds.contains(&1) { + true => &mut found.genres, + false => &mut found.tags, + }; + if !list.contains(&text) { + list.push(text); + } + } + Ok(found) +} + +/// How a song sounds, as Spotify's audio analysis measures it. Each measure runs from none to all, +/// and the tempo is in beats per minute. +#[derive(Deserialize, Default)] +#[serde(default)] +struct Features { + id: String, + danceability: f32, + energy: f32, + valence: f32, + acousticness: f32, + instrumentalness: f32, + tempo: f32, +} + +impl Features { + /// The feelings the song carries, by the Fluent key that names each. A song can carry several, + /// and a middling one none. + fn moods(&self) -> Vec<&'static str> { + let mut moods = Vec::new(); + let mut when = |condition: bool, mood| { + if condition { + moods.push(mood); + } + }; + when(self.energy >= 0.7, "stats-mood-energetic"); + when(self.danceability >= 0.7, "stats-mood-danceable"); + when(self.valence >= 0.6, "stats-mood-positive"); + when( + self.valence <= 0.3 && self.energy >= 0.5, + "stats-mood-negative", + ); + when(self.valence <= 0.3 && self.energy < 0.5, "stats-mood-sad"); + when(self.energy <= 0.35, "stats-mood-calming"); + when(self.instrumentalness >= 0.5, "stats-mood-instrumental"); + when(self.acousticness >= 0.6, "stats-mood-acoustic"); + moods + } +} + +/// Reads how each of the tracks sounds by id, a hundred to a request, which is what Spotify's own +/// audio analysis answers for. A track it does not know is left out. +async fn features(session: &Session, ids: &[String]) -> Result> { + #[derive(Deserialize)] + struct Answer { + audio_features: Vec>, + } + let mut found = HashMap::new(); + for ids in ids.chunks(FEATURES_AT_ONCE) { + let path = format!("/audio-attributes/v1/audio-features?ids={}", ids.join(",")); + let body = session + .spclient() + .request_as_json(&http::Method::GET, &path, None, None) + .await + .context("cannot request audio features")?; + let answer: Answer = + serde_json::from_slice(&body).context("cannot decode audio features")?; + found.extend( + answer + .audio_features + .into_iter() + .flatten() + .map(|features| (features.id.clone(), features)), + ); + } + Ok(found) +} diff --git a/crates/music/src/spotify/mod.rs b/crates/music/src/spotify/mod.rs index 7e9945a84..4fae1a33a 100644 --- a/crates/music/src/spotify/mod.rs +++ b/crates/music/src/spotify/mod.rs @@ -6,6 +6,7 @@ mod client; mod collection; mod collection2; mod connect; +mod descriptors; mod links; mod lyrics; mod offline; diff --git a/crates/music/src/spotify/pathfinder.rs b/crates/music/src/spotify/pathfinder.rs index ce95681db..1d75560c9 100644 --- a/crates/music/src/spotify/pathfinder.rs +++ b/crates/music/src/spotify/pathfinder.rs @@ -14,6 +14,7 @@ mod hashes; mod library; mod plays; mod search; +mod stats; pub(crate) use album::album; pub(crate) use artist::{Overview, artist}; @@ -23,6 +24,7 @@ pub(crate) use plays::track; pub(crate) use search::{ albums as search_albums, artists as search_artists, playlists as search_playlists, }; +pub(crate) use stats::stats; const ENDPOINT: &str = "https://api-partner.spotify.com/pathfinder/v2/query"; const APP_PLATFORM: &str = "WebPlayer"; diff --git a/crates/music/src/spotify/pathfinder/hashes.rs b/crates/music/src/spotify/pathfinder/hashes.rs index c1dd6dc21..4bc4a0e0c 100644 --- a/crates/music/src/spotify/pathfinder/hashes.rs +++ b/crates/music/src/spotify/pathfinder/hashes.rs @@ -18,8 +18,9 @@ const MAX_AGE: Duration = Duration::from_secs(24 * 60 * 60); const FILE: &str = "pathfinder.json"; /// Operations the shared hash service does not list, read from the web player bundle instead. -const DESKTOP_OPERATIONS: [(&str, &str); 4] = [ +const DESKTOP_OPERATIONS: [(&str, &str); 5] = [ ("home", "query"), + ("userTopContent", "query"), ("libraryV3", "query"), ("pinLibraryItem", "mutation"), ("unpinLibraryItem", "mutation"), @@ -230,6 +231,15 @@ async fn desktop_hash(operation: &str) -> Result { let html = public_text(&public, "https://open.spotify.com").await?; let bundle = desktop_bundle(&html).context("Spotify page has no desktop player bundle")?; let javascript = public_text(&public, bundle).await?; + let javascript = match operation { + "userTopContent" => { + let chunk = + profile_bundle(&javascript).context("Spotify bundle has no profile chunk")?; + let url = format!("https://open.spotifycdn.com/cdn/build/web-player/{chunk}"); + public_text(&public, &url).await? + } + _ => javascript, + }; let mut operations = registry() .map(|registry| registry.operations) .unwrap_or_default(); @@ -275,6 +285,24 @@ fn desktop_bundle(html: &str) -> Option<&str> { }) } +/// Resolves the profile chunk from the client's own JavaScript filename map. +fn profile_bundle(javascript: &str) -> Option { + let name = "xpui-routes-profile"; + let before = javascript.split_once(&format!(":\"{name}\""))?.0; + let id = before.rsplit([',', '{']).next()?; + // An entry of the map follows a comma or the opening brace, so a longer id that merely ends + // in these digits is not taken for it. + let hash = [',', '{'].into_iter().find_map(|before| { + let marker = format!("{before}{id}:\""); + javascript + .split(&marker) + .skip(1) + .filter_map(|tail| tail.split_once('"').map(|p| p.0)) + .find(|value| value.len() == 8 && value.bytes().all(|b| b.is_ascii_hexdigit())) + })?; + Some(format!("{name}.{hash}.js")) +} + fn operation_hash<'a>(javascript: &'a str, operation: &str, kind: &str) -> Option<&'a str> { let marker = format!("\"{operation}\",\"{kind}\",\""); let (_, after) = javascript.split_once(&marker)?; diff --git a/crates/music/src/spotify/pathfinder/stats.rs b/crates/music/src/spotify/pathfinder/stats.rs new file mode 100644 index 000000000..4b6835a20 --- /dev/null +++ b/crates/music/src/spotify/pathfinder/stats.rs @@ -0,0 +1,429 @@ +use std::collections::HashMap; + +use anyhow::{Context as _, Result, ensure}; +use librespot_core::Session; +use librespot_protocol::extension_kind::ExtensionKind; +use librespot_protocol::metadata::Track as TrackMessage; +use protobuf::Message as _; +use serde::Deserialize; + +use crate::spotify::{collection, descriptors, pb}; +use crate::{ + Board, ListeningStats, Overview, Ranked, SavedArtist, StatsPeriod, Track, album_of, compare, +}; + +/// Reads the same personal rankings as Spotify's profile, without the Web API. Each is compared +/// with the next broader window, which shows who is rising and who is fading. +pub(crate) async fn stats(session: &Session, period: StatsPeriod) -> Result { + let (range, broader) = match period { + StatsPeriod::Weeks => ("SHORT_TERM", Some("MID_TERM")), + StatsPeriod::Months => ("MID_TERM", Some("LONG_TERM")), + StatsPeriod::Year => ("LONG_TERM", None), + }; + let (profile, broader) = tokio::join!(top(session, range), async { + match broader { + Some(range) => top(session, range).await.ok(), + None => None, + } + }); + let profile = profile?; + let earlier = |page: &Page, prefix: &str| -> Vec { + page.items + .iter() + .filter_map(|hit| hit.data.as_ref()?.uri.strip_prefix(prefix)) + .map(str::to_owned) + .collect() + }; + let before = broader.map(|broader| { + ( + earlier(&broader.tracks, "spotify:track:"), + earlier(&broader.artists, "spotify:artist:"), + ) + }); + let totals = (profile.tracks.total, profile.artists.total); + let uris: Vec<_> = profile + .tracks + .items + .into_iter() + .filter_map(|hit| hit.data) + .filter(|item| item.kind == "Track") + .map(|item| item.uri) + .collect(); + let ids: Vec<_> = uris + .iter() + .filter_map(|uri| uri.strip_prefix("spotify:track:")) + .map(str::to_owned) + .collect(); + let (metadata, described, credited) = tokio::join!( + released(session, &uris), + descriptors::read(session, &ids), + credits(session, &uris) + ); + let mut metadata = metadata?; + let mut years = Vec::new(); + let mut described = optional("descriptors", described); + let credited = optional("credits", credited); + let (mut songwriters, mut producers) = (Board::default(), Board::default()); + let (mut genres, mut moods, mut tags) = (Board::default(), Board::default(), Board::default()); + let mut tempos = Vec::new(); + let mut albums = Board::default(); + let mut tracks = Vec::new(); + for uri in uris { + let Some((mut track, year)) = metadata.remove(&uri) else { + continue; + }; + years.extend(year); + for (writes, produces, artist) in credited.get(&uri).into_iter().flatten() { + let make = || artist.clone(); + if *writes { + songwriters.add(artist.id.clone(), 1, make); + } + if *produces { + producers.add(artist.id.clone(), 1, make); + } + } + let found = track + .id + .as_ref() + .and_then(|id| described.remove(id)) + .unwrap_or_default(); + tempos.extend(found.bpm); + track.tags = [&found.genres, &found.tags] + .into_iter() + .flatten() + .cloned() + .collect(); + for (board, names) in [ + (&mut genres, found.genres), + (&mut moods, found.moods), + (&mut tags, found.tags), + ] { + for name in names { + board.add(name.clone(), 1, || name); + } + } + if let Some((key, album)) = album_of(&track) { + albums.add(key, 1, || album); + } + tracks.push(Ranked::new(track, None)); + } + let mut artists: Vec> = profile + .artists + .items + .into_iter() + .filter_map(|hit| hit.data) + .filter(|item| item.kind == "Artist") + .filter_map(|item| { + let id = item.uri.strip_prefix("spotify:artist:")?.to_owned(); + let name = item.profile?.name; + let cover = item + .visuals + .and_then(|visuals| visuals.avatar_image) + .and_then(|image| image.sources.into_iter().max_by_key(|source| source.height)) + .map(|source| source.url); + let artist = SavedArtist { + id, + name, + cover, + ..Default::default() + }; + Some(Ranked::new(artist, None)) + }) + .collect(); + let mut overview = about(&tracks); + overview.avg_year = average(&years); + overview.avg_bpm = mean_tempo(&tempos); + // Spotify counts every song and artist it ranks for the window, not just the fifty it lists. + overview.tracks = Some(totals.0).filter(|total| *total > 0); + overview.artists = Some(totals.1).filter(|total| *total > 0); + overview.recent_share = recent(&years); + if let Some((tracks_before, artists_before)) = &before { + compare(&mut tracks, tracks_before.clone(), |track| { + track.id.clone().unwrap_or_default() + }); + compare(&mut artists, artists_before.clone(), |artist| { + artist.id.clone() + }); + // What is new against the broader window is what the listener has newly taken to. + overview.new_tracks = Some(tracks.iter().filter(|row| row.fresh).count()); + overview.new_artists = Some(artists.iter().filter(|row| row.fresh).count()); + } + // Moods read from the audio say more than a song's descriptor words. Those words stay as tags + // beside them, and stand in as the moods when the analysis is missing. + let (moods, tags) = match moods.is_empty() { + false => (moods.ranked(), tags.ranked()), + true => (tags.ranked(), Vec::new()), + }; + // Spotify ranks by affinity without counts, so albums and tags rank by how many of the + // top tracks they cover. + Ok(ListeningStats { + tracks, + artists, + albums: unranked(albums, usize::MAX), + genres: genres.ranked(), + moods, + tags, + songwriters: unranked(songwriters, 12), + producers: unranked(producers, 12), + years: tally(&years), + tempos: bands(&tempos), + overview, + ..Default::default() + }) +} + +/// What a read that only adds detail gives: its answer, or an empty one with a warning when it +/// failed, so that the rankings still show. +fn optional(what: &str, result: Result) -> T { + result.unwrap_or_else(|error| { + log::warn!("stats: cannot read Spotify {what}: {error:#}"); + T::default() + }) +} + +/// Reads the songs with the release year, where it is known, that the same metadata carries. +async fn released( + session: &Session, + uris: &[String], +) -> Result)>> { + let entities = collection::extended(session, uris, ExtensionKind::TRACK_V4) + .await + .context("cannot read track metadata")?; + Ok(entities + .into_iter() + .filter_map(|entity| { + let message = TrackMessage::parse_from_bytes(&entity.extension_data.value).ok()?; + let year = Some(message.album.date.year()).filter(|year| *year > 0); + let track = collection::track_from(&entity.entity_uri, &message); + Some((entity.entity_uri, (track, year))) + }) + .collect()) +} + +/// Who is credited with writing and producing each song: the artist, and whether as a writer and +/// as a producer. A song's credits name an artist once for each role. +async fn credits( + session: &Session, + uris: &[String], +) -> Result>> { + let entities = + collection::extended(session, uris, ExtensionKind::TRACK_EXTENDED_CREDITS).await?; + entities + .into_iter() + .map(|entity| { + let mut found: Vec<(bool, bool, SavedArtist)> = Vec::new(); + let mut reader = pb::Reader::new(&entity.extension_data.value); + while let Some((field, value)) = reader.field()? { + let (1, pb::Value::Bytes(credit)) = (field, value) else { + continue; + }; + let (mut id, mut name, mut role) = (String::new(), String::new(), String::new()); + let mut credit = pb::Reader::new(credit); + while let Some((field, value)) = credit.field()? { + match (field, value) { + (1, pb::Value::Bytes(value)) => id = pb::text(value)?, + (2, pb::Value::Bytes(value)) => name = pb::text(value)?, + (3, pb::Value::Bytes(value)) => role = pb::text(value)?.to_lowercase(), + _ => {} + } + } + let Some(id) = id.strip_prefix("spotify:artist:") else { + continue; + }; + let writes = ["composer", "lyricist", "writer"] + .iter() + .any(|word| role.contains(word)); + let produces = role.contains("producer"); + if !(writes || produces) { + continue; + } + match found.iter_mut().find(|(_, _, artist)| artist.id == id) { + Some(known) => { + known.0 |= writes; + known.1 |= produces; + } + None => found.push(( + writes, + produces, + SavedArtist { + id: id.to_owned(), + name: name.clone(), + ..Default::default() + }, + )), + } + } + Ok((entity.entity_uri, found)) + }) + .collect() +} + +/// The `most` highest ranked rows of a board, without the counts that only ordered them. +fn unranked(board: Board, most: usize) -> Vec> { + board + .ranked() + .into_iter() + .take(most) + .map(|row| Ranked::new(row.item, None)) + .collect() +} + +/// The mean tempo, rounded. +fn mean_tempo(tempos: &[f32]) -> Option { + (!tempos.is_empty()).then(|| (tempos.iter().sum::() / tempos.len() as f32).round() as u16) +} + +/// How many songs fall in each band of ten beats per minute, slowest first. +fn bands(tempos: &[f32]) -> Vec<(u16, usize)> { + let mut counts = std::collections::BTreeMap::new(); + for bpm in tempos { + *counts.entry((*bpm as u16) / 10 * 10).or_default() += 1; + } + counts.into_iter().collect() +} + +/// How many of the years there are of each, oldest first. +fn tally(years: &[i32]) -> Vec<(i32, usize)> { + let mut counts = std::collections::BTreeMap::new(); + for year in years { + *counts.entry(*year).or_default() += 1; + } + counts.into_iter().collect() +} + +/// The mean of the years, rounded. +fn average(years: &[i32]) -> Option { + let total: i64 = years.iter().map(|year| i64::from(*year)).sum(); + total + .checked_div(years.len() as i64) + .map(|year| year as i32) +} + +/// The share of the years that are this year or the one before, in percent. +fn recent(years: &[i32]) -> Option { + let now = jiff::Zoned::now().year(); + (!years.is_empty()).then(|| { + (years + .iter() + .filter(|year| **year >= i32::from(now) - 1) + .count() + * 100 + / years.len()) as u8 + }) +} + +/// The popularity under which a song counts as a deep cut. +const DEEP_CUT: u32 = 40; + +/// Requests the profile's top tracks and artists over one of Spotify's three windows. +async fn top(session: &Session, range: &str) -> Result { + let input = + serde_json::json!({"offset": 0, "limit": 50, "sortBy": "AFFINITY", "timeRange": range}); + let data: Data = super::query( + session, + "userTopContent", + serde_json::json!({ + "includeTopArtists": true, "topArtistsInput": input, + "includeTopTracks": true, "topTracksInput": input, + }), + ) + .await?; + let profile = data + .me + .context("stats response has no account")? + .profile + .context("stats response has no profile")?; + ensure!( + profile.tracks.kind == "TrackPageV2" && profile.artists.kind == "ArtistPageV2", + "Spotify did not return personal rankings" + ); + Ok(profile) +} + +/// What the top songs say about the listener's taste: how popular, how rare and how long. +fn about(tracks: &[Ranked]) -> Overview { + let songs = tracks.iter().map(|ranked| &ranked.item); + let popular: Vec<_> = songs + .clone() + .map(|track| track.popularity) + .filter(|score| *score > 0) + .collect(); + let share = |count: usize, of: usize| (count * 100).checked_div(of).map(|share| share as u8); + Overview { + mainstream: (popular.iter().sum::() as usize) + .checked_div(popular.len()) + .map(|score| score as u8), + deep_cuts: share( + popular.iter().filter(|score| **score < DEEP_CUT).count(), + popular.len(), + ), + collab_share: share( + songs + .clone() + .filter(|track| track.artist_refs.len() > 1) + .count(), + tracks.len(), + ), + avg_length: songs + .map(|track| track.duration.as_secs()) + .sum::() + .checked_div(tracks.len() as u64), + ..Default::default() + } +} + +#[derive(Deserialize)] +struct Data { + me: Option, +} +#[derive(Deserialize)] +struct Account { + profile: Option, +} +#[derive(Deserialize)] +struct Profile { + #[serde(rename = "topTracks")] + tracks: Page, + #[serde(rename = "topArtists")] + artists: Page, +} +#[derive(Deserialize)] +struct Page { + #[serde(rename = "__typename")] + kind: String, + #[serde(default)] + items: Vec, + #[serde(default, rename = "totalCount")] + total: usize, +} +#[derive(Deserialize)] +struct Hit { + data: Option, +} +#[derive(Deserialize)] +struct Item { + #[serde(rename = "__typename")] + kind: String, + #[serde(default)] + uri: String, + profile: Option, + visuals: Option, +} +#[derive(Deserialize)] +struct Name { + name: String, +} +#[derive(Deserialize)] +#[serde(rename_all = "camelCase")] +struct Visuals { + avatar_image: Option, +} +#[derive(Deserialize)] +struct Image { + sources: Vec, +} +#[derive(Deserialize)] +struct Source { + url: String, + height: Option, +} diff --git a/crates/music/src/spotify/pb.rs b/crates/music/src/spotify/pb.rs index f45fd6f4f..dd5f6d7f6 100644 --- a/crates/music/src/spotify/pb.rs +++ b/crates/music/src/spotify/pb.rs @@ -124,6 +124,16 @@ impl<'a> Reader<'a> { } } +/// Reads packed protobuf varints from a length-delimited field. +pub(crate) fn varints(bytes: &[u8]) -> Result> { + let mut reader = Reader::new(bytes); + let mut values = Vec::new(); + while reader.at < reader.bytes.len() { + values.push(reader.varint()?); + } + Ok(values) +} + pub(crate) fn text(bytes: &[u8]) -> Result { Ok(std::str::from_utf8(bytes) .context("field is not utf-8")? diff --git a/crates/music/src/stats.rs b/crates/music/src/stats.rs new file mode 100644 index 000000000..06ec6bf5e --- /dev/null +++ b/crates/music/src/stats.rs @@ -0,0 +1,451 @@ +use std::collections::{BTreeMap, HashMap, HashSet}; + +use jiff::civil::Date; +use jiff::tz::TimeZone; + +use crate::{Album, SavedArtist, Track}; + +/// The windows a source can rank personal listening over. A source lists the ones it supports. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum StatsPeriod { + Weeks, + Months, + Year, +} + +/// One ranked item. A missing count means the source supplies affinity order alone. +#[derive(Clone, Debug)] +pub struct Ranked { + pub item: T, + pub count: Option, + /// The source's own page for the item, when it has no matching catalogue id. + pub external_url: Option, + /// Whether the item is absent from the list the source compares it to, where it compares. + pub fresh: bool, +} + +impl Ranked { + pub fn new(item: T, count: Option) -> Self { + Self { + item, + count, + external_url: None, + fresh: false, + } + } + + pub fn linked(mut self, url: Option) -> Self { + self.external_url = url; + self + } +} + +/// The figures of a listening period. A source fills in what it knows and leaves the rest empty, +/// so a view shows exactly the figures that exist. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Overview { + pub plays: Option, + pub tracks: Option, + pub artists: Option, + pub albums: Option, + /// Artists, and songs, whose first play in Sonora's retained log falls inside the period. + pub new_artists: Option, + pub new_tracks: Option, + /// The share of plays, in percent, that were of a song already played in the period. + pub replay_share: Option, + /// The average song length in seconds, and how mainstream the songs are from 0 to 100. + pub avg_length: Option, + pub mainstream: Option, + /// The average year the songs were released, and the share released in the past year. + pub avg_year: Option, + pub recent_share: Option, + /// The average tempo of the songs, in beats per minute. + pub avg_bpm: Option, + /// The share of songs, in percent, that few listeners play, and that credit several artists. + pub deep_cuts: Option, + pub collab_share: Option, + /// Plays against the period before, in percent. + pub change: Option, + /// The first and last day of the longest run of consecutive days with plays. + pub streak: Option<(Date, Date)>, + pub plays_per_day: Option, + pub busiest_day: Option<(Date, usize)>, + /// Seconds of music played, where the source knows track lengths. + pub time: Option, + /// When the account began, in Unix seconds. + pub since: Option, + /// The local hour with the most starts. + pub peak_hour: Option, + /// Starts in each local hour of each weekday, Monday first, or empty without play times. + pub clock: Vec, +} + +impl Overview { + /// Fills in what the start times of plays say about when the listener listens: the clock, + /// the days and the busiest hour and day. + pub fn timed(mut self, times: &[i64]) -> Self { + let zone = TimeZone::system(); + let mut clock = vec![0; 7 * 24]; + let mut days: BTreeMap = BTreeMap::new(); + for at in times { + if let Ok(stamp) = jiff::Timestamp::from_second(*at) { + let local = stamp.to_zoned(zone.clone()); + let weekday = local.weekday().to_monday_zero_offset() as usize; + clock[weekday * 24 + local.hour() as usize] += 1; + *days.entry(local.date()).or_default() += 1; + } + } + self.clock = clock; + self.peak_hour = self + .hourly() + .iter() + .enumerate() + .max_by_key(|(_, count)| **count) + .filter(|(_, count)| **count > 0) + .map(|(hour, _)| hour as u8); + self.streak = longest_streak(days.keys().copied()); + self.plays_per_day = (!days.is_empty()).then(|| times.len() as f32 / days.len() as f32); + self.busiest_day = days + .iter() + .max_by_key(|(_, count)| **count) + .map(|(day, count)| (*day, *count)); + self + } + + /// Drops the figures that only make sense for every play, for times that are just the latest. + /// A streak found among the latest plays is still a streak, so it stays as a lower bound. + pub fn partial(mut self) -> Self { + self.plays_per_day = None; + self.busiest_day = None; + self + } + + /// Starts in each local hour, over every weekday. + pub fn hourly(&self) -> Vec { + let mut hours = vec![0; 24]; + for (at, count) in self.clock.iter().enumerate() { + hours[at % 24] += count; + } + hours + } +} + +/// Personal listening for one period: the ranked items and the figures that describe them. +#[derive(Clone, Debug, Default)] +pub struct ListeningStats { + pub tracks: Vec>, + pub artists: Vec>, + pub albums: Vec>, + /// Catalogue genres, when the source has a genre taxonomy. + pub genres: Vec>, + /// How the songs feel, where the source can say. Either read from the audio, or the words a + /// source describes songs with that are not genres. + pub moods: Vec>, + /// The words a source describes songs with, such as slow, soft or chill, where the moods + /// above are read from the audio instead. + pub tags: Vec>, + /// The artists credited with writing and with producing the most songs, ranked by how many + /// songs, without counts. + pub songwriters: Vec>, + pub producers: Vec>, + /// How many songs came out in each year, oldest first. + pub years: Vec<(i32, usize)>, + /// How many songs play at each tempo, in bands of ten beats per minute named by their + /// slowest, slowest first. + pub tempos: Vec<(u16, usize)>, + /// Plays of the whole history that reached a round number, oldest first. + pub milestones: Vec, + /// Plays in each equal slice of the account's history, for a source that can read them. + pub density: Vec, + /// The figures of the selected period. + pub overview: Overview, +} + +/// A play that reached a round number in the listener's whole history. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Milestone { + pub number: usize, + pub title: String, + pub artist: String, + /// When the play started, in Unix seconds. + pub at: i64, +} + +/// The round play numbers a history can have reached. +const LADDER: [usize; 11] = [ + 100, 500, 1_000, 5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, +]; +/// How many of the round numbers, the latest ones, are marked beside the first play. +const MARKED: usize = 4; + +/// The play numbers of a history of `total` plays that are worth marking: the first, and the +/// latest few round numbers it has passed. +pub fn milestone_numbers(total: usize) -> Vec { + let passed: Vec<_> = LADDER + .into_iter() + .filter(|number| *number < total) + .collect(); + let skip = passed.len().saturating_sub(MARKED); + (total > 1) + .then_some(1) + .into_iter() + .chain(passed.into_iter().skip(skip)) + .collect() +} + +/// How many traits at most are shown, the first that the figures support. +const MOST_TRAITS: usize = 6; + +/// What a listener's figures say about how they listen, each a short label to wear. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Trait { + EarlyBird, + Daytime, + Evening, + NightOwl, + Weekender, + Weekday, + Explorer, + Loyalist, + Mainstream, + DeepDiver, + Throwback, + FreshEars, + Collaborator, + Superfan, + Daily, + Rising, + FastLane, + SlowBurner, +} + +impl ListeningStats { + /// The traits the figures support. A source with few figures has few traits, and a trait + /// needs the figures it rests on. + pub fn traits(&self) -> Vec { + let o = &self.overview; + let hour = o.peak_hour.map(|hour| match hour { + 5..=11 => Trait::EarlyBird, + 12..=17 => Trait::Daytime, + 18..=22 => Trait::Evening, + _ => Trait::NightOwl, + }); + let total: usize = o.clock.iter().sum(); + let weekend: usize = o.clock.iter().skip(5 * 24).sum(); + let days = match (total > 0).then(|| weekend * 100 / total) { + Some(40..) => Some(Trait::Weekender), + Some(..=15) => Some(Trait::Weekday), + _ => None, + }; + // Without a record of plays or a window to compare with, how many different artists the + // top songs spread over says as much: many suggest exploring, a few suggest devotion. + let mut leads: HashMap = HashMap::new(); + for track in self.tracks.iter().map(|ranked| &ranked.item) { + let lead = track + .artist_refs + .first() + .and_then(|artist| artist.id.clone()) + .unwrap_or_else(|| track.artists.clone()); + *leads.entry(lead).or_default() += 1; + } + let listed = self.tracks.len(); + let explorer = match (o.replay_share, o.new_tracks) { + (Some(share), _) => Some(share < 40), + (None, Some(fresh)) if listed > 0 => Some(fresh * 100 / listed >= 20), + (None, None) if listed >= 10 => Some(leads.len() * 100 / listed >= 50), + _ => None, + }; + let novelty = explorer.map(|explorer| match explorer { + true => Trait::Explorer, + false => Trait::Loyalist, + }); + let taste = match (o.mainstream, o.deep_cuts) { + (Some(60..), _) => Some(Trait::Mainstream), + (Some(..=50), _) | (_, Some(30..)) => Some(Trait::DeepDiver), + _ => None, + }; + let era = match (o.recent_share, o.avg_year) { + (Some(40..), _) => Some(Trait::FreshEars), + (_, Some(..=2012)) => Some(Trait::Throwback), + _ => None, + }; + let collaborator = (o.collab_share >= Some(40)).then_some(Trait::Collaborator); + // One artist taking a quarter of the plays, or of the top songs where there are no plays. + let by_plays = self + .artists + .first() + .and_then(|artist| artist.count) + .zip(o.plays.filter(|plays| *plays > 0)) + .map(|(top, plays)| top * 100 / plays); + let by_songs = + (listed > 0).then(|| leads.values().max().copied().unwrap_or_default() * 100 / listed); + let superfan = (by_plays.or(by_songs) >= Some(25)).then_some(Trait::Superfan); + let week = o.streak.is_some_and(|(from, to)| { + to.since((jiff::Unit::Day, from)) + .is_ok_and(|span| span.get_days() >= 6) + }); + let daily = week.then_some(Trait::Daily); + let rising = (o.change >= Some(15)).then_some(Trait::Rising); + let tempo = o.avg_bpm.and_then(|bpm| match bpm { + 125.. => Some(Trait::FastLane), + ..=100 => Some(Trait::SlowBurner), + _ => None, + }); + [ + hour, + days, + novelty, + taste, + era, + tempo, + collaborator, + superfan, + daily, + rising, + ] + .into_iter() + .flatten() + .take(MOST_TRAITS) + .collect() + } +} + +/// Counts weighted hits per key and ranks them, keeping first-seen order between equal counts. +pub struct Board { + slots: HashMap, + rows: Vec>, +} + +impl Default for Board { + fn default() -> Self { + Self { + slots: HashMap::new(), + rows: Vec::new(), + } + } +} + +impl Board { + /// Adds `weight` to `key`, building its item on the first hit. + pub fn add(&mut self, key: String, weight: usize, make: impl FnOnce() -> T) { + let at = *self.slots.entry(key).or_insert_with(|| { + self.rows.push(Ranked::new(make(), Some(0))); + self.rows.len() - 1 + }); + let count = &mut self.rows[at].count; + *count = count.map(|count| count.saturating_add(weight)); + } + + /// How many distinct keys were hit. + pub fn len(&self) -> usize { + self.rows.len() + } + + pub fn is_empty(&self) -> bool { + self.rows.is_empty() + } + + /// The rows from most to least hit. + pub fn ranked(mut self) -> Vec> { + self.rows.sort_by_key(|row| std::cmp::Reverse(row.count)); + self.rows + } +} + +/// Marks each row that is absent from `before`, the keys of the list it is compared with. +pub fn compare( + rows: &mut [Ranked], + before: impl IntoIterator, + key: impl Fn(&T) -> String, +) { + let known: HashSet = before.into_iter().collect(); + for row in rows { + row.fresh = !known.contains(&key(&row.item)); + } +} + +/// The artists credited on a track, each once and keyed by catalogue id when there is one. +pub fn credits(track: &Track) -> Vec<(String, SavedArtist)> { + let mut seen = HashSet::new(); + let mut artists: Vec<_> = track + .artist_refs + .iter() + .filter_map(|artist| { + let key = artist.id.clone().unwrap_or_else(|| artist.name.clone()); + seen.insert(key.clone()).then(|| { + let id = artist.id.clone().unwrap_or_default(); + let name = artist.name.clone(); + ( + key, + SavedArtist { + id, + name, + ..Default::default() + }, + ) + }) + }) + .collect(); + if artists.is_empty() && !track.artists.is_empty() { + let name = track.artists.clone(); + artists.push(( + name.clone(), + SavedArtist { + name, + ..Default::default() + }, + )); + } + artists +} + +/// The key an album is tallied under: its catalogue id, else its name, or nothing without a name. +pub fn album_key(track: &Track) -> Option { + (!track.album.is_empty()).then(|| { + track + .album_id + .clone() + .unwrap_or_else(|| track.album.clone()) + }) +} + +/// The album a track belongs to, keyed by [`album_key`]. +pub fn album_of(track: &Track) -> Option<(String, Album)> { + let key = album_key(track)?; + let album = Album { + id: key.clone(), + name: track.album.clone(), + artists: track.artists.clone(), + artist_refs: track.artist_refs.clone(), + cover: track.cover.clone(), + ..Default::default() + }; + Some((key, album)) +} + +/// A tag in its tallying form, or nothing for a blank tag or the catch-all "music". +pub fn tag_key(tag: &str) -> Option { + let key = tag.trim().to_lowercase(); + (!key.is_empty() && key != "music").then_some(key) +} + +/// The first and last day of the longest run of consecutive calendar days, from the days in order. +fn longest_streak(days: impl Iterator) -> Option<(Date, Date)> { + let mut best: Option<(Date, Date, usize)> = None; + let mut run: Option<(Date, usize)> = None; + let mut previous = None::; + for day in days { + let continues = previous.and_then(|previous| previous.tomorrow().ok()) == Some(day); + run = match (continues, run) { + (true, Some((start, length))) => Some((start, length + 1)), + _ => Some((day, 1)), + }; + if let Some((start, length)) = run + && best.is_none_or(|(_, _, longest)| length > longest) + { + best = Some((start, day, length)); + } + previous = Some(day); + } + best.map(|(start, end, _)| (start, end)) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 2ef39f38b..e76b01a44 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -28,7 +28,7 @@ impl LibraryTab { /// A row the sidebar can hide from Settings. The four library pages are rows of their own, /// each opening its page of the merged streaming and local library. History and Settings always -/// sit in the account menu, so their rows are optional and stay out of the sidebar until asked for. +/// sit in the account menu, and so does Stats, so their rows are optional and stay out of the sidebar until asked for. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum NavEntry { Home, @@ -39,15 +39,17 @@ pub enum NavEntry { Playlists, History, Settings, + Stats, Pins, } impl NavEntry { - pub const ALL: [Self; 9] = [ + pub const ALL: [Self; 10] = [ Self::Home, Self::Search, Self::History, Self::Settings, + Self::Stats, Self::Songs, Self::Albums, Self::Artists, @@ -65,6 +67,7 @@ impl NavEntry { Self::Playlists => "playlists", Self::History => "history", Self::Settings => "settings", + Self::Stats => "stats", Self::Pins => "sidebar-pins", } } @@ -79,6 +82,7 @@ impl NavEntry { Self::Playlists => "nav-playlists", Self::History => "nav-history", Self::Settings => "nav-settings", + Self::Stats => "nav-stats", Self::Pins => "nav-pinned", } } @@ -86,7 +90,7 @@ impl NavEntry { /// Whether the row stays out of the sidebar until the listener adds it, rather than showing /// until hidden. pub fn optional(self) -> bool { - matches!(self, Self::Settings) + matches!(self, Self::Settings | Self::Stats) } } @@ -95,6 +99,7 @@ pub enum Screen { Home, Search, History, + Stats, Songs, Albums, Playlists, @@ -102,7 +107,7 @@ pub enum Screen { } impl Screen { - pub const ALL: [Self; 7] = [ + pub const ALL: [Self; 8] = [ Self::Home, Self::Search, Self::Songs, @@ -110,6 +115,7 @@ impl Screen { Self::Artists, Self::Playlists, Self::History, + Self::Stats, ]; pub fn id(self) -> &'static str { @@ -117,6 +123,7 @@ impl Screen { Self::Home => "home", Self::Search => "search", Self::History => "history", + Self::Stats => "stats", Self::Songs => "songs", Self::Albums => "albums", Self::Playlists => "playlists", @@ -129,6 +136,7 @@ impl Screen { Self::Home => "nav-home", Self::Search => "nav-search", Self::History => "nav-history", + Self::Stats => "nav-stats", Self::Songs => "nav-songs", Self::Albums => "nav-albums", Self::Playlists => "nav-playlists", @@ -149,6 +157,7 @@ impl Screen { Self::Home => Destination::Home, Self::Search => Destination::Search, Self::History => Destination::History, + Self::Stats => Destination::Stats, Self::Songs => Destination::Library(LibraryTab::Songs), Self::Albums => Destination::Library(LibraryTab::Albums), Self::Playlists => Destination::Library(LibraryTab::Playlists), @@ -360,6 +369,7 @@ impl SettingsTab { pub enum Destination { Home, History, + Stats, Library(LibraryTab), Album(SharedString), Song(SharedString), diff --git a/crates/sonora/src/actions.rs b/crates/sonora/src/actions.rs index 3b58538d9..aca77d33a 100644 --- a/crates/sonora/src/actions.rs +++ b/crates/sonora/src/actions.rs @@ -69,6 +69,10 @@ pub fn register(lingers: bool, cx: &mut App) { let history = Sonora::global(cx).history.clone(); history.update(cx, |history, cx| history.refresh(cx)); } + Destination::Stats => { + let stats = Sonora::global(cx).stats.clone(); + stats.update(cx, |stats, cx| stats.refresh(cx)); + } at if !at.refreshes() => {} at => { let library = Sonora::global(cx).library.clone(); diff --git a/crates/state/Cargo.toml b/crates/state/Cargo.toml index c1476eecf..e2864a827 100644 --- a/crates/state/Cargo.toml +++ b/crates/state/Cargo.toml @@ -17,6 +17,7 @@ gpui.workspace = true i18n.workspace = true icons.workspace = true image.workspace = true +jiff.workspace = true log.workspace = true moka.workspace = true music.workspace = true diff --git a/crates/state/src/history.rs b/crates/state/src/history.rs index 4672ab907..461f3709e 100644 --- a/crates/state/src/history.rs +++ b/crates/state/src/history.rs @@ -29,12 +29,12 @@ pub enum HistoryState { } #[derive(Clone)] -struct Store { +pub(crate) struct Store { database: Database, } impl Store { - fn new(database: Database) -> Self { + pub(crate) fn new(database: Database) -> Self { Self { database } } @@ -172,6 +172,15 @@ impl Store { } fn load(&self, scope: &str) -> Result> { + self.read(scope, LOCAL_LIMIT as i64) + } + + /// Reads the retained play log without the history page's display limit. + pub(crate) fn recorded(&self, scope: &str) -> Result> { + self.read(scope, i64::MAX) + } + + fn read(&self, scope: &str, limit: i64) -> Result> { let connection = self.open()?; let mut query = connection .prepare( @@ -184,7 +193,7 @@ impl Store { ) .context("cannot prepare listening history read")?; let rows = query - .query_map(params![scope, LOCAL_LIMIT as i64], |row| { + .query_map(params![scope, limit], |row| { let refs = row.get_ref(5)?.as_str()?; let artist_refs: Vec = serde_json::from_str(refs).unwrap_or_default(); let played_at: i64 = row.get(1)?; @@ -616,7 +625,7 @@ impl History { }); } - fn scope(&self, cx: &Context) -> Option { + pub(crate) fn scope(&self, cx: &gpui::App) -> Option { let session = self.session.read(cx); let SessionState::SignedIn(profile) = session.state() else { return None; diff --git a/crates/state/src/lib.rs b/crates/state/src/lib.rs index 106b09ab8..3eafe3ef4 100644 --- a/crates/state/src/lib.rs +++ b/crates/state/src/lib.rs @@ -38,6 +38,7 @@ mod snapshot; mod soloist; mod song; mod sponsorblock; +mod stats; mod tags; mod toast; mod updates; @@ -96,6 +97,7 @@ pub use signal::{Change, Equalizing, FLOAT_BITS, Following, Signal, SignalPath}; pub use soloist::{Soloist, SoloistProblem, SoloistState, SoloistStep, SoloistSwitched}; pub use song::SongDetail; pub use sponsorblock::SponsorBlock; +pub use stats::{Entry, Found, Stats, StatsSource}; pub use tags::{TagState, Tags}; pub use toast::{Outcome, Target, Toast, ToastAction, Toasts}; pub use updates::{Channel, Release, UpdateState, Updates, commit, updates_itself, version}; @@ -236,6 +238,7 @@ pub struct Sonora { pub links: Entity, pub listening: Entity, pub history: Entity, + pub stats: Entity, pub lyrics: Entity, pub network: Entity, pub outputs: Entity, @@ -351,6 +354,15 @@ pub fn init( cx, ) }); + let stats = cx.new(|cx| { + Stats::new( + session.clone(), + history.clone(), + settings.clone(), + database.clone(), + cx, + ) + }); let scan = cx.new(|cx| Scan::new(session.clone(), cx)); let scrobbling = cx.new(|cx| { Scrobbling::new( @@ -448,6 +460,7 @@ pub fn init( links, listening, history, + stats, lyrics, network, outputs, diff --git a/crates/state/src/stats.rs b/crates/state/src/stats.rs new file mode 100644 index 000000000..dcb00f383 --- /dev/null +++ b/crates/state/src/stats.rs @@ -0,0 +1,1155 @@ +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use futures::StreamExt as _; +use gpui::{App, Context, Entity, Task}; +use music::scrobble::{self, Service}; +use music::{ + Album, Board, CoverSize, Descriptors, ListeningStats, Milestone, MusicApi, Overview, + SavedArtist, StatsPeriod, Track, album_key, album_of, compare, credits, milestone_numbers, + tag_key, +}; +use storage::Database; + +use crate::history::Store; +use crate::{AppSettings, History, Io, Session, SessionEvent, join}; + +/// How many ranked artists, songs and albums of a scrobbler chart are matched to the catalogue up +/// front. Further entries are matched when opened. +const MATCHED: usize = 10; +/// How many recorded artists get a portrait, and how many are requested at once. +const PORTRAITS: usize = 100; +const PORTRAIT_BATCH: usize = 25; +/// How many catalogue requests run at once. +const CONCURRENT: usize = 6; +/// How long the dates sit still before a scrobbler is asked about them. +const DEBOUNCE: Duration = Duration::from_millis(400); +/// How long recorded plays wait for the dates to settle, which is only a pass over the log. +const SETTLE: Duration = Duration::from_millis(120); +/// How long a load counts as current when the page is opened again. +const FRESH: Duration = Duration::from_secs(300); +/// How many of the most played recorded tracks are asked for genres and moods, and how many at once. +const DESCRIBED: usize = 300; +/// How many slices the recorded history is cut into for the timeline's activity shape. +const DENSITY_BUCKETS: usize = 64; + +/// Where the rankings come from. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum StatsSource { + /// The signed-in provider's own rankings, over its fixed windows. + Provider, + /// The timestamped plays Sonora recorded, over any range of dates. + Recorded, + /// A linked scrobbling service, by its id. + Scrobbler(&'static str), +} + +/// A scrobbler chart entry that names something in the active catalogue without an id of its own. +#[derive(Clone, Debug)] +pub enum Entry { + Artist { name: String }, + Track { title: String, artist: String }, + Album { title: String, artist: String }, +} + +/// The catalogue item an [`Entry`] matched. +#[derive(Clone, Debug)] +pub enum Found { + Artist(SavedArtist), + Track(Track), + Album(Album), +} + +impl Entry { + /// What names the entry, for remembering what the catalogue made of it. + fn key(&self) -> String { + match self { + Self::Artist { name } => format!("artist\u{1}{name}"), + Self::Track { title, artist } => format!("track\u{1}{title}\u{1}{artist}"), + Self::Album { title, artist } => format!("album\u{1}{title}\u{1}{artist}"), + } + } + + /// Searches the catalogue and keeps a result only when its names match exactly. + async fn find(&self, client: &dyn MusicApi) -> Result> { + Ok(match self { + Self::Artist { name } => client + .search_artists(name) + .await? + .into_iter() + .find(|found| !found.id.is_empty() && same(&found.name, name)) + .map(Found::Artist), + Self::Track { title, artist } => client + .search(&format!("{title} {artist}")) + .await? + .into_iter() + .find(|found| { + found.id.is_some() && named(&found.name, &found.artists, title, artist) + }) + .map(Found::Track), + Self::Album { title, artist } => client + .search_albums(&format!("{title} {artist}")) + .await? + .into_iter() + .find(|found| { + !found.id.is_empty() && named(&found.name, &found.artists, title, artist) + }) + .map(Found::Album), + }) + } + + /// Swaps every unmatched ranking row this entry names for the catalogue item, keeping the + /// chart's artwork when the catalogue has none. + fn adopt(&self, found: &Found, data: &mut ListeningStats) { + match (self, found) { + (Self::Artist { name }, Found::Artist(found)) => { + for row in &mut data.artists { + if row.item.id.is_empty() && same(&row.item.name, name) { + let cover = found.cover.clone().or_else(|| row.item.cover.take()); + row.item = SavedArtist { + cover, + ..found.clone() + }; + } + } + } + (Self::Track { title, artist }, Found::Track(found)) => { + for row in &mut data.tracks { + let item = &mut row.item; + if item.id.is_none() && named(&item.name, &item.artists, title, artist) { + let cover = found.cover.clone().or_else(|| item.cover.take()); + *item = Track { + cover, + ..found.clone() + }; + } + } + } + (Self::Album { title, artist }, Found::Album(found)) => { + for row in &mut data.albums { + let item = &mut row.item; + if item.id.is_empty() && named(&item.name, &item.artists, title, artist) { + let chart = item.cover.take(); + *item = Album { + cover: found.cover.clone().or_else(|| chart.clone()), + cover_large: found.cover_large.clone().or(chart), + ..found.clone() + }; + } + } + } + _ => {} + } + } +} + +/// The retained play log with everything derived from it, which changing the dates leaves be. +#[derive(Default)] +struct Log { + /// The retained play log, kept so that changing the dates needs no new read. + recorded: Vec, + /// Genres and moods the provider gave the most played recorded tracks. + descriptors: HashMap, + portraits: HashMap, + /// When each artist was first played in the retained log, which a date range never changes. + first_play: Firsts, + /// The figures of every recorded play, which a date range never changes. + history: Overview, + /// Plays per slice of the scrobbler account's history, which a date range never changes. + scrobbled_density: Vec, + /// The scrobbler account's round-number plays, read once with the all-time view. + scrobbled_milestones: Vec, + /// The recorded plays that reached a round number, which a date range never changes. + milestones: Vec, + /// The first and last recorded play, in Unix seconds. + bounds: Option<(i64, i64)>, + /// The selected range of recorded plays, in Unix seconds, or all of them. + dates: Option<(i64, i64)>, + /// Recorded plays per slice of `bounds`. + density: Vec, +} + +/// Owns stats requests, the retained play log and date filtering, independently of any view. +pub struct Stats { + session: Entity, + history: Entity, + settings: Entity, + store: Store, + source: StatsSource, + period: StatsPeriod, + log: Log, + /// What was last loaded and when, so that opening the page again need not load it again. + loaded: Option<(StatsSource, StatsPeriod, Instant)>, + /// When the scrobbler account began, in Unix seconds. + since: Option, + data: ListeningStats, + loading: bool, + failed: bool, + task: Option>, + /// The wait for dragged dates to settle, kept apart from `task` so that it never cancels a load. + settling: Option>, + matching: Option>, + opening: Option>, + /// The read of what only a whole scrobbler account says, which runs beside the page. + history_task: Option>, + /// What searching the catalogue found for chart entries, misses included, so that a new range + /// asks only about the entries it has not met. It belongs to the provider named beside it. + matched: HashMap>, + matched_for: Option, + /// The latest answer for each window of a source, so that coming back to one is instant. + windows: HashMap<(StatsSource, StatsPeriod), (Instant, ListeningStats)>, +} + +impl Stats { + pub fn new( + session: Entity, + history: Entity, + settings: Entity, + database: Database, + cx: &mut Context, + ) -> Self { + cx.subscribe(&session, |this, _, event, cx| { + if matches!(event, SessionEvent::SignedOut | SessionEvent::SignedIn) { + (this.source, this.period) = defaults(&this.session, cx); + this.log = Log::default(); + this.since = None; + this.windows.clear(); + this.matched.clear(); + this.history_task = None; + this.refresh(cx); + } + }) + .detach(); + cx.observe(&history, |this, _, cx| { + // The history notifies whenever the window comes back to the front, so a change in + // the log is checked for quietly rather than reloading a page that is being read. + if this.source == StatsSource::Recorded && this.loaded.is_some() && this.task.is_none() + { + this.load_recorded(true, cx); + } + }) + .detach(); + cx.observe(&settings, |this, _, cx| { + if matches!(this.source, StatsSource::Scrobbler(_)) { + this.ensure(cx); + } + }) + .detach(); + let (source, period) = defaults(&session, cx); + Self { + session, + history, + settings, + store: Store::new(database), + source, + period, + log: Log::default(), + loaded: None, + since: None, + data: ListeningStats::default(), + loading: false, + failed: false, + task: None, + settling: None, + matching: None, + opening: None, + history_task: None, + matched: HashMap::new(), + matched_for: None, + windows: HashMap::new(), + } + } + + pub fn source(&self) -> StatsSource { + self.source + } + + /// The sources that can be shown right now, in tab order. + pub fn sources(&self, cx: &App) -> Vec { + let mut sources = vec![StatsSource::Recorded]; + if !self.periods_of(StatsSource::Provider, cx).is_empty() { + sources.push(StatsSource::Provider); + } + let accounts = self.settings.read(cx).scrobbling(); + sources.extend( + scrobble::services() + .into_iter() + .filter(|service| { + service.stats_dated() + && accounts + .get(service.id()) + .is_some_and(|account| account.linked()) + }) + .map(|service| StatsSource::Scrobbler(service.id())), + ); + sources + } + + /// The fixed windows of the selected source. Sources that read any dates have none. + pub fn periods(&self, cx: &App) -> Vec { + self.periods_of(self.source, cx) + } + + pub fn period(&self) -> StatsPeriod { + self.period + } + + pub fn data(&self) -> &ListeningStats { + &self.data + } + + pub fn is_loading(&self) -> bool { + self.loading + } + + pub fn failed(&self) -> bool { + self.failed + } + + /// The stretch the dates can be picked from: the first to the last recorded play, or the + /// scrobbler account's first day to now. + pub fn bounds(&self) -> Option<(i64, i64)> { + match self.source { + StatsSource::Scrobbler(_) => self + .since + .map(|since| (since, jiff::Timestamp::now().as_second())), + _ => self.log.bounds, + } + } + + /// The selected range of dates, or none for all time. + pub fn dates(&self) -> Option<(i64, i64)> { + self.log.dates + } + + /// The figures of the whole recorded history, whatever dates are selected, where the source + /// has every play. Only recorded plays do. + pub fn history(&self) -> Option<&Overview> { + (self.source == StatsSource::Recorded).then_some(&self.log.history) + } + + /// How many plays fall in each equal slice of [`Self::bounds`]. + pub fn density(&self) -> &[usize] { + match self.source { + StatsSource::Recorded => &self.log.density, + StatsSource::Scrobbler(_) => &self.log.scrobbled_density, + StatsSource::Provider => &[], + } + } + + /// Switches source, moving to the new source's first window when it lacks `period`. + pub fn select(&mut self, source: StatsSource, period: StatsPeriod, cx: &mut Context) { + let periods = self.periods_of(source, cx); + if source != self.source { + self.log.dates = None; + } + self.settling = None; + self.source = source; + self.period = match periods.contains(&period) { + true => period, + false => periods.last().copied().unwrap_or(period), + }; + let kept = self + .windows + .get(&(self.source, self.period)) + .filter(|(at, _)| at.elapsed() < FRESH && self.log.dates.is_none()); + if let (Some((at, data)), true) = (kept, self.source != StatsSource::Recorded) { + self.task = None; + self.matching = None; + self.failed = false; + self.loading = false; + self.data = data.clone(); + // The account history can land after the window was kept, so its milestones come + // from the log, not from the cached copy. + if matches!(self.source, StatsSource::Scrobbler(_)) + && !self.log.scrobbled_milestones.is_empty() + { + self.data.milestones = self.log.scrobbled_milestones.clone(); + } + self.loaded = Some((self.source, self.period, *at)); + cx.notify(); + return; + } + self.refresh(cx); + } + + /// Restricts the rankings to an inclusive range of Unix seconds, or to none for all time. + /// Recorded plays are regrouped at once, and a scrobbler is asked again once the range has + /// stopped moving. + pub fn set_dates(&mut self, dates: Option<(i64, i64)>, cx: &mut Context) { + self.log.dates = dates; + // A drag sends many dates, and each answer is a pass over the whole log or a request, so + // the work waits for the dates to settle. + let (wait, scrobbled) = match self.source { + StatsSource::Scrobbler(_) => (DEBOUNCE, true), + _ => (SETTLE, false), + }; + self.settling = Some(cx.spawn(async move |this, cx| { + cx.background_executor().timer(wait).await; + this.update(cx, |this, cx| { + match scrobbled { + true => this.refresh(cx), + false => this.data = this.aggregated(), + } + cx.notify(); + }) + .ok(); + })); + cx.notify(); + } + + /// Loads what the selected source shows, unless that is loading or was loaded recently. + pub fn ensure(&mut self, cx: &mut Context) { + let current = self.loaded.is_some_and(|(source, period, at)| { + source == self.source && period == self.period && at.elapsed() < FRESH + }); + if !(self.loading || current && !self.failed) { + self.refresh(cx); + } + } + + /// Reloads whatever the selected source shows. + pub fn refresh(&mut self, cx: &mut Context) { + self.windows.remove(&(self.source, self.period)); + self.loaded = None; + self.task = None; + self.matching = None; + self.opening = None; + self.failed = false; + self.loading = false; + self.data = ListeningStats::default(); + let client = self.session.read(cx).client(); + let ranks = client + .as_ref() + .is_some_and(|client| client.stats_periods().contains(&self.period)); + if self.source == StatsSource::Provider && !ranks { + self.source = StatsSource::Recorded; + } + match (self.source, client) { + (StatsSource::Provider, Some(client)) => self.load_provider(client, cx), + (StatsSource::Scrobbler(id), client) => self.load_scrobbler(id, client, cx), + _ => self.load_recorded(false, cx), + } + cx.notify(); + } + + /// Matches a scrobbler chart entry to the active catalogue, and tells `resolved` the result. + pub fn resolve( + &mut self, + entry: Entry, + resolved: impl FnOnce(Option, &mut App) + 'static, + cx: &mut Context, + ) { + let Some(client) = self.session.read(cx).client() else { + return resolved(None, cx); + }; + let io = Io::global(cx); + self.opening = Some(cx.spawn(async move |this, cx| { + let worker = entry.clone(); + let found = join(io.spawn(async move { worker.find(client.as_ref()).await })); + let found = found.await.unwrap_or_else(|error| { + log::debug!("stats: cannot match {entry:?} to the catalogue: {error:#}"); + None + }); + this.update(cx, |this, cx| { + this.opening = None; + if let Some(found) = &found { + entry.adopt(found, &mut this.data); + cx.notify(); + } + resolved(found, cx); + }) + .ok(); + })); + } + + fn periods_of(&self, source: StatsSource, cx: &App) -> Vec { + match source { + StatsSource::Provider => self + .session + .read(cx) + .client() + .map(|client| client.stats_periods().to_vec()) + .unwrap_or_default(), + StatsSource::Recorded | StatsSource::Scrobbler(_) => Vec::new(), + } + } + + /// Stores a finished load, or the reason it failed. + fn finish(&mut self, result: Result, what: &str, cx: &mut Context) { + self.loading = false; + self.task = None; + match result { + Ok(data) => { + self.data = data; + self.loaded = Some((self.source, self.period, Instant::now())); + } + Err(error) => { + log::warn!("stats: cannot load {what}: {error:#}"); + self.failed = true; + } + } + cx.notify(); + } + + /// Shows the rankings as soon as the provider answers. The portraits of credited artists, which + /// it does not send, are looked up after, in batches that run together, and each card takes + /// its picture as the batch holding it arrives. + fn load_provider(&mut self, client: Arc, cx: &mut Context) { + let period = self.period; + let io = Io::global(cx); + self.loading = true; + let looked_up = client.clone(); + self.task = Some(io.clone().load( + async move { + let mut data = client.stats(period).await?; + enlarge_ranked(&mut data, client.as_ref()); + Ok(data) + }, + move |this, result, cx| { + // Each artist is asked for once, in rank order, so the top cards fill first. + let mut seen = HashSet::new(); + let missing: Vec<_> = result + .as_ref() + .map(|data| { + data.songwriters + .iter() + .chain(&data.producers) + .map(|ranked| ranked.item.id.clone()) + .filter(|id| { + !this.log.portraits.contains_key(id) && seen.insert(id.clone()) + }) + .collect() + }) + .unwrap_or_default(); + let result = result.map(|mut data| { + this.dress_credits(&mut data); + this.windows.insert( + (StatsSource::Provider, period), + (Instant::now(), data.clone()), + ); + data + }); + this.finish(result, "provider rankings", cx); + if missing.is_empty() { + return; + } + let batches: Vec<_> = missing + .chunks(PORTRAIT_BATCH) + .map(|batch| { + let (client, ids) = (looked_up.clone(), batch.to_vec()); + join(io.spawn(async move { client.artist_images(ids).await })) + }) + .collect(); + this.matching = Some(cx.spawn(async move |this, cx| { + // Each batch is a request of its own, and the cards take what each brings as + // it arrives. + let mut pending: futures::stream::FuturesUnordered<_> = + batches.into_iter().collect(); + while let Some(found) = pending.next().await { + let Ok(found) = found else { continue }; + this.update(cx, |this, cx| { + this.log.portraits.extend(found); + let mut data = std::mem::take(&mut this.data); + this.dress_credits(&mut data); + this.data = data; + let key = (StatsSource::Provider, period); + if let Some((at, mut kept)) = this.windows.remove(&key) { + this.dress_credits(&mut kept); + this.windows.insert(key, (at, kept)); + } + cx.notify(); + }) + .ok(); + } + })); + }, + cx, + )); + } + + /// Gives the credited artists the portraits that are known. + fn dress_credits(&self, data: &mut ListeningStats) { + for ranked in data.songwriters.iter_mut().chain(&mut data.producers) { + if let Some(cover) = self.log.portraits.get(&ranked.item.id) { + ranked.item.cover = Some(cover.clone()); + } + } + } + + /// Shows the chart as soon as the service answers, then matches its top entries to the active + /// catalogue in the background so they open in Sonora. + fn load_scrobbler( + &mut self, + id: &'static str, + client: Option>, + cx: &mut Context, + ) { + let account = self.settings.read(cx).account(id); + let Some(service) = service(id).filter(|service| account.linked() && service.stats_dated()) + else { + self.failed = true; + return; + }; + let dates = self.log.dates; + let io = Io::global(cx); + // The matches belong to one catalogue, so another provider starts them afresh. + let provider = self.session.read(cx).provider_slug().map(str::to_owned); + if provider != self.matched_for { + self.matched.clear(); + self.matched_for = provider; + } + let known = self.matched.clone(); + let period = self.period; + let history = (self.log.scrobbled_density.is_empty() + && self.log.scrobbled_milestones.is_empty()) + .then(|| (service.clone(), account.clone())); + // The history of the whole account is read alongside the rankings. + if let Some((service, account)) = history { + self.history_task = Some(io.load( + async move { service.history(&account).await }, + |this, result, cx| { + this.history_task = None; + match result { + Ok(history) => { + this.log.scrobbled_density = history.density; + this.log.scrobbled_milestones = history.milestones.clone(); + // Another source may have been picked while this was read. + if matches!(this.source, StatsSource::Scrobbler(_)) { + this.data.milestones = history.milestones; + } + } + Err(error) => log::debug!("stats: cannot load history: {error:#}"), + } + cx.notify(); + }, + cx, + )); + } + self.loading = true; + self.task = Some(io.clone().load( + async move { service.stats(&account, dates).await }, + move |this, mut result, cx| { + if let Ok(data) = &mut result { + // The milestones and the history belong to the whole account, so a range + // keeps the ones read before it. + data.milestones = this.log.scrobbled_milestones.clone(); + this.since = data.overview.since.or(this.since); + } + if let (Ok(data), Some(client)) = (&result, client) { + let data = data.clone(); + this.matching = Some(io.clone().load( + async move { Ok(match_catalogue(data, client.as_ref(), known).await) }, + |this, result, cx| { + this.matching = None; + match result { + Ok((mut data, found)) => { + this.matched.extend(found); + data.milestones = this.log.scrobbled_milestones.clone(); + this.data = data; + } + Err(error) => log::debug!("stats: cannot match chart: {error:#}"), + } + cx.notify(); + }, + cx, + )); + } + if let (Ok(data), None) = (&result, dates) { + this.windows.insert( + (StatsSource::Scrobbler(id), period), + (Instant::now(), data.clone()), + ); + } + this.finish(result, "scrobbler rankings", cx); + }, + cx, + )); + } + + /// Reads the play log and shows it at once. Portraits and genres follow. A + /// quiet read leaves the page alone, and changes it only when the log has changed. + fn load_recorded(&mut self, quiet: bool, cx: &mut Context) { + let Some(scope) = self.history.read(cx).scope(cx) else { + return; + }; + let store = self.store.clone(); + let io = Io::global(cx); + let client = self.session.read(cx).client(); + // What the log held when last read, so that a quiet read of an unchanged log stops short. + let known = ( + self.log.recorded.len(), + self.log.recorded.first().map(|track| track.added_at), + ); + self.loading = !quiet; + self.task = Some(io.clone().load( + async move { + io.spawn_blocking(move || { + let mut tracks = store.recorded(&scope)?; + if quiet && (tracks.len(), tracks.first().map(|track| track.added_at)) == known + { + return Ok(None); + } + prepare_covers(&mut tracks, client.as_deref()); + let first_play = first_plays(&tracks); + let milestones = milestones_of(&tracks); + let times: Vec<_> = tracks.iter().filter_map(|track| track.added_at).collect(); + let history = Overview::default().timed(×); + Ok(Some((tracks, first_play, milestones, history))) + }) + .await? + }, + move |this, result, cx| match result { + Ok(None) => this.task = None, + Ok(Some((tracks, first_play, milestones, history))) => { + let times = tracks.iter().filter_map(|track| track.added_at); + this.log.bounds = times.clone().min().zip(times.max()); + this.log.density = this + .log + .bounds + .map(|bounds| slice_plays(&tracks, bounds)) + .unwrap_or_default(); + this.log.recorded = tracks; + this.log.first_play = first_play; + this.log.milestones = milestones; + this.log.history = history; + // Built from the dates selected at this point, with the descriptors and + // portraits already known. + let data = this.aggregated(); + this.finish(Ok(data), "recorded plays", cx); + this.enrich(cx); + } + Err(error) => this.finish(Err(error), "recorded plays", cx), + }, + cx, + )); + } + + /// Fetches, all at once, the genres and moods of the most played recorded songs and the + /// artists' portraits. The page is already on screen, and the answers are applied together. + fn enrich(&mut self, cx: &mut Context) { + let Some(client) = self.session.read(cx).client() else { + return; + }; + let described: Vec<_> = self + .data + .tracks + .iter() + .map(|ranked| &ranked.item) + .filter(|track| track.tags.is_empty()) + .filter_map(|track| track.id.clone()) + .filter(|id| !self.log.descriptors.contains_key(id)) + .take(DESCRIBED) + .collect(); + let portraits: Vec<_> = self + .data + .artists + .iter() + .map(|ranked| &ranked.item.id) + .filter(|id| !id.is_empty() && !self.log.portraits.contains_key(*id)) + .take(PORTRAITS) + .cloned() + .collect(); + if described.is_empty() && portraits.is_empty() { + return; + } + self.matching = Some(Io::global(cx).load( + async move { + let client = client.as_ref(); + Ok(tokio::join!( + fetch_descriptors(client, described), + fetch_portraits(client, portraits), + )) + }, + |this, result, cx| { + this.matching = None; + if let Ok((descriptors, portraits)) = result { + this.log.descriptors.extend(descriptors); + this.log.portraits.extend(portraits); + this.data = this.aggregated(); + cx.notify(); + } + }, + cx, + )); + } + + /// The recorded plays inside the selected dates, with portraits applied. + fn aggregated(&self) -> ListeningStats { + let mut data = aggregate( + &self.log.recorded, + &self.log.first_play, + self.log.dates, + &self.log.descriptors, + ); + if let Some((from, to)) = self.log.dates { + let length = to - from + 1; + let range = Some((from - length, from - 1)); + let before = aggregate( + &self.log.recorded, + &self.log.first_play, + range, + &self.log.descriptors, + ); + compare_with(&mut data, &before); + } + data.milestones = self.log.milestones.clone(); + for artist in &mut data.artists { + if let Some(cover) = self.log.portraits.get(&artist.item.id) { + artist.item.cover = Some(cover.clone()); + } + } + data + } +} + +/// The source and window a fresh account starts on: its provider's broadest window, else recorded +/// plays. +fn defaults(session: &Entity, cx: &App) -> (StatsSource, StatsPeriod) { + let first = session + .read(cx) + .client() + .and_then(|client| client.stats_periods().last().copied()); + match first { + Some(period) => (StatsSource::Provider, period), + None => (StatsSource::Recorded, StatsPeriod::Weeks), + } +} + +fn service(id: &str) -> Option> { + scrobble::services() + .into_iter() + .find(|service| service.id() == id) +} + +/// Folds punctuation and case, so that a chart's spelling can match the catalogue's. +fn comparable(value: &str) -> String { + value + .chars() + .filter(|character| character.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect() +} + +/// Whether two names are the same once folded, which a blank never is. +fn same(a: &str, b: &str) -> bool { + let a = comparable(a); + !a.is_empty() && a == comparable(b) +} + +/// Whether a title and its artist are the ones a chart entry names. +fn named(title: &str, artist: &str, wanted_title: &str, wanted_artist: &str) -> bool { + same(title, wanted_title) && same(artist, wanted_artist) +} + +/// Matches the top entries of a scrobbler chart to the catalogue, a few searches at a time, then +/// gives the matches large covers. Entries already met come from `known`, and what the searches +/// found is handed back to be kept. +async fn match_catalogue( + mut data: ListeningStats, + client: &dyn MusicApi, + known: HashMap>, +) -> (ListeningStats, HashMap>) { + let top = |len: usize| len.min(MATCHED); + let entries: Vec = data.artists[..top(data.artists.len())] + .iter() + .filter(|row| row.item.id.is_empty()) + .map(|row| Entry::Artist { + name: row.item.name.clone(), + }) + .chain( + data.tracks[..top(data.tracks.len())] + .iter() + .filter(|row| row.item.id.is_none()) + .map(|row| Entry::Track { + title: row.item.name.clone(), + artist: row.item.artists.clone(), + }), + ) + .chain( + data.albums[..top(data.albums.len())] + .iter() + .filter(|row| row.item.id.is_empty()) + .map(|row| Entry::Album { + title: row.item.name.clone(), + artist: row.item.artists.clone(), + }), + ) + .collect(); + let known = &known; + let found: Vec<_> = futures::stream::iter(entries) + .map(|entry| async move { + let key = entry.key(); + match known.get(&key) { + Some(found) => (entry, key, Ok(found.clone()), false), + None => { + let found = entry.find(client).await; + (entry, key, found, true) + } + } + }) + .buffer_unordered(CONCURRENT) + .collect() + .await; + let mut fresh = HashMap::new(); + for (entry, key, found, searched) in found { + match found { + Ok(found) => { + if let Some(found) = &found { + entry.adopt(found, &mut data); + } + if searched { + fresh.insert(key, found); + } + } + Err(error) => log::debug!("stats: cannot match {entry:?} to the catalogue: {error:#}"), + } + } + enlarge_ranked(&mut data, client); + (data, fresh) +} + +/// Gives the ranked songs and albums large covers. +fn enlarge_ranked(data: &mut ListeningStats, client: &dyn MusicApi) { + let covers = data + .tracks + .iter_mut() + .map(|row| &mut row.item.cover) + .chain(data.albums.iter_mut().map(|row| &mut row.item.cover)); + for cover in covers { + if let Some(large) = cover + .as_deref() + .and_then(|url| client.cover_at(url, CoverSize::Large)) + { + *cover = Some(large); + } + } +} + +/// Asks the provider for the genres and moods of songs, which it may not describe. +async fn fetch_descriptors( + client: &dyn MusicApi, + ids: Vec, +) -> HashMap { + if ids.is_empty() { + return HashMap::new(); + } + client.descriptors(&ids).await.unwrap_or_else(|error| { + log::debug!("stats: cannot load descriptors: {error:#}"); + HashMap::new() + }) +} + +/// Fetches artist portraits in batches, all at once. +async fn fetch_portraits(client: &dyn MusicApi, ids: Vec) -> HashMap { + let batches = ids + .chunks(PORTRAIT_BATCH) + .map(|batch| client.artist_images(batch.to_vec())); + futures::future::join_all(batches) + .await + .into_iter() + .filter_map(|found| { + found + .map_err(|error| log::debug!("stats: cannot load portraits: {error:#}")) + .ok() + }) + .flatten() + .collect() +} + +/// Gives a song with no cover the cover of another play of its album, and asks the provider for +/// large covers once, so that every later regrouping of the plays has them. +fn prepare_covers(tracks: &mut [Track], client: Option<&dyn MusicApi>) { + let covers: HashMap<_, _> = tracks + .iter() + .filter_map(|track| Some((album_key(track)?, track.cover.clone()?))) + .collect(); + let mut large: HashMap = HashMap::new(); + for track in tracks.iter_mut() { + track.cover = track + .cover + .take() + .or_else(|| covers.get(&album_key(track)?).cloned()); + if let (Some(cover), Some(client)) = (track.cover.as_mut(), client) { + let url = large.entry(cover.clone()).or_insert_with(|| { + client + .cover_at(cover, CoverSize::Large) + .unwrap_or_else(|| cover.clone()) + }); + *cover = url.clone(); + } + } +} + +/// Counts the plays that started within `dates`. Every credited artist, genre and mood of a play +/// gets one hit. A track the provider described takes its genres and moods from that, and any +/// other from the tags it was recorded with. +fn aggregate( + tracks: &[Track], + first_play: &Firsts, + dates: Option<(i64, i64)>, + descriptors: &HashMap, +) -> ListeningStats { + let (mut songs, mut artists, mut albums) = + (Board::default(), Board::default(), Board::default()); + let (mut genres, mut moods, mut tags) = (Board::default(), Board::default(), Board::default()); + let none = Descriptors::default(); + let (mut time, mut times) = (0u64, Vec::new()); + let mut new_artists = HashSet::new(); + let (mut plays, mut new_tracks) = (0, 0); + for track in tracks { + let (Some(at), Some(id)) = (track.added_at, track.id.as_ref()) else { + continue; + }; + if dates.is_some_and(|(from, to)| at < from || at > to) { + continue; + } + plays += 1; + new_tracks += usize::from(first_play.tracks.get(id) == Some(&at)); + time += track.duration.as_secs(); + times.push(at); + songs.add(id.clone(), 1, || track.clone()); + if let Some((key, album)) = album_of(track) { + albums.add(key, 1, || album); + } + for (key, artist) in credits(track) { + if first_play.artists.get(&key) == Some(&at) { + new_artists.insert(key.clone()); + } + artists.add(key, 1, || artist); + } + let (own_genres, own_moods, own_tags) = descriptors + .get(id) + .map_or((&track.tags, &none.moods, &none.tags), |found| { + (&found.genres, &found.moods, &found.tags) + }); + for (board, names) in [ + (&mut genres, own_genres), + (&mut moods, own_moods), + (&mut tags, own_tags), + ] { + let mut seen = HashSet::new(); + for name in names { + if let Some(key) = tag_key(name).filter(|key| seen.insert(key.clone())) { + board.add(key, 1, || name.trim().to_owned()); + } + } + } + } + + let overview = match plays { + 0 => Overview::default(), + _ => Overview { + plays: Some(plays), + time: Some(time), + tracks: Some(songs.len()), + artists: Some(artists.len()), + albums: Some(albums.len()), + new_artists: Some(new_artists.len()), + new_tracks: Some(new_tracks), + replay_share: Some((plays.saturating_sub(songs.len()) * 100 / plays) as u8), + avg_length: Some(time / plays as u64), + ..Default::default() + } + .timed(×), + }; + ListeningStats { + tracks: songs.ranked(), + artists: artists.ranked(), + albums: albums.ranked(), + genres: genres.ranked(), + moods: moods.ranked(), + tags: tags.ranked(), + overview, + ..Default::default() + } +} + +/// When each artist and each song was first played in the log. +#[derive(Default)] +struct Firsts { + artists: HashMap, + tracks: HashMap, +} + +/// The recorded plays that reached a round number, oldest first. +fn milestones_of(tracks: &[Track]) -> Vec { + let mut plays: Vec<_> = tracks + .iter() + .filter_map(|track| Some((track.added_at?, track))) + .collect(); + plays.sort_by_key(|(at, _)| *at); + milestone_numbers(plays.len()) + .into_iter() + .filter_map(|number| { + let (at, track) = plays.get(number - 1)?; + Some(Milestone { + number, + title: track.name.clone(), + artist: track.artists.clone(), + at: *at, + }) + }) + .collect() +} + +fn first_plays(tracks: &[Track]) -> Firsts { + let mut firsts = Firsts::default(); + let earliest = |map: &mut HashMap, key: String, at: i64| { + map.entry(key) + .and_modify(|first| *first = (*first).min(at)) + .or_insert(at); + }; + for track in tracks { + let Some(at) = track.added_at else { continue }; + for (key, _) in credits(track) { + earliest(&mut firsts.artists, key, at); + } + if let Some(id) = &track.id { + earliest(&mut firsts.tracks, id.clone(), at); + } + } + firsts +} + +/// Marks each ranked item as new, up or down against the period before, and sets how plays +/// changed. Nothing is marked when there was no period before to compare with. +fn compare_with(data: &mut ListeningStats, before: &ListeningStats) { + let Some(was) = before.overview.plays.filter(|was| *was > 0) else { + return; + }; + let named = |id: &str, name: &str| if id.is_empty() { name } else { id }.to_owned(); + let artist = |artist: &SavedArtist| named(&artist.id, &artist.name); + let song = |track: &Track| track.id.clone().unwrap_or_default(); + let album = |album: &Album| named(&album.id, &album.name); + compare( + &mut data.artists, + before.artists.iter().map(|row| artist(&row.item)), + artist, + ); + compare( + &mut data.tracks, + before.tracks.iter().map(|row| song(&row.item)), + song, + ); + compare( + &mut data.albums, + before.albums.iter().map(|row| album(&row.item)), + album, + ); + let now = data.overview.plays.unwrap_or_default(); + data.overview.change = Some(((now as i64 - was as i64) * 100 / was as i64) as i32); +} + +/// Counts plays in equal slices of `bounds`. +fn slice_plays(tracks: &[Track], (first, last): (i64, i64)) -> Vec { + let span = (last - first).max(1) as f64; + let mut slices = vec![0; DENSITY_BUCKETS]; + for at in tracks.iter().filter_map(|track| track.added_at) { + let share = (at - first) as f64 / span; + slices[((share * DENSITY_BUCKETS as f64) as usize).min(DENSITY_BUCKETS - 1)] += 1; + } + slices +} diff --git a/crates/ui/src/card.rs b/crates/ui/src/card.rs index b94c8f69d..c36863251 100644 --- a/crates/ui/src/card.rs +++ b/crates/ui/src/card.rs @@ -31,6 +31,10 @@ const PLAY_FILL: f32 = 0.55; const SCRIM_RATIO: f32 = 0.45; const SCRIM_MIN: Pixels = px(14.); const TIGHT: Pixels = px(2.); +const BADGE_INSET: Pixels = px(6.); +const BADGE_PAD: Pixels = px(7.); +const BADGE_HEIGHT: Pixels = px(20.); +const BADGE_GAP: Pixels = px(3.); pub const CARD_GROUP: &str = "card"; @@ -39,6 +43,14 @@ type Summon = Box; type DragStart = Rc; type Warm = Rc; +/// A corner of a card's artwork that a badge can sit in. +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum Corner { + TopLeft, + BottomLeft, + BottomRight, +} + #[derive(IntoElement)] pub struct Card { id: ElementId, @@ -82,6 +94,7 @@ pub struct Card { collapsed: bool, drag_start: Option, menu: Option, + badges: Vec<(Corner, Option, SharedString)>, } impl Card { @@ -126,6 +139,7 @@ impl Card { collapsed: false, drag_start: None, menu: None, + badges: Vec::new(), } } @@ -250,6 +264,24 @@ impl Card { self } + /// Lays a small frosted label over a corner of the artwork. A badge in the bottom right + /// steps aside while the play button shows there. + pub fn badge(mut self, corner: Corner, label: impl Into) -> Self { + self.badges.push((corner, None, label.into())); + self + } + + /// A badge with an icon before its label. + pub fn icon_badge( + mut self, + corner: Corner, + icon: impl Into, + label: impl Into, + ) -> Self { + self.badges.push((corner, Some(icon.into()), label.into())); + self + } + pub fn tint(mut self, tint: Hsla) -> Self { self.tint = Some(tint); self @@ -393,6 +425,7 @@ impl RenderOnce for Card { collapsed, drag_start, menu, + badges, } = self; let theme = *cx.theme(); @@ -440,6 +473,7 @@ impl RenderOnce for Card { .when(accent, Artwork::accent) .into_any_element(), }; + let has_play = play.is_some(); let leading = match play { None => leading, Some(play) => { @@ -573,6 +607,59 @@ impl RenderOnce for Card { } }; + let leading = match badges.is_empty() { + true => leading, + false => { + let frosted = blurring(cx); + div() + .relative() + .flex_none() + .size(art) + .child(leading) + .children(badges.into_iter().map(|(corner, icon, label)| { + div() + .absolute() + .map(|this| match corner { + Corner::TopLeft => this.top(BADGE_INSET).left(BADGE_INSET), + Corner::BottomLeft => this.bottom(BADGE_INSET).left(BADGE_INSET), + Corner::BottomRight => this.bottom(BADGE_INSET).right(BADGE_INSET), + }) + .when(corner == Corner::BottomRight && has_play, |this| { + // The play button is always there while playing, and only on + // hover otherwise. + match playing { + true => this.invisible(), + false => { + this.group_hover(CARD_GROUP, |style| style.invisible()) + } + } + }) + .h(BADGE_HEIGHT) + .min_w(BADGE_HEIGHT) + .px(BADGE_PAD) + .flex() + .items_center() + .justify_center() + .gap(BADGE_GAP) + .rounded_full() + .bg(theme.overlay) + .text_color(theme.overlay_foreground) + .text_size(theme.text(Text::Small)) + .font_weight(FontWeight::SEMIBOLD) + .when(frosted, |this| this.backdrop_blur(GLASS_BLUR)) + .children(icon.map(|icon| { + svg() + .path(icons::path(icon)) + .size(theme.text(Text::Small)) + .flex_none() + .text_color(theme.overlay_foreground) + })) + .child(label) + })) + .into_any_element() + } + }; + // The meta line is an element no reader can reach, so the description or the eyebrow // stands in for it, and the explicit badge is read after them. let about = [ diff --git a/crates/ui/src/filters.rs b/crates/ui/src/filters.rs index 8a183cba1..4b4fe9e70 100644 --- a/crates/ui/src/filters.rs +++ b/crates/ui/src/filters.rs @@ -16,6 +16,7 @@ use crate::time::clock; const TRACK: f32 = 0.5; const THUMB: f32 = 1.5; const HIT: f32 = 2.; +const STOP_WIDTH: Pixels = px(1.); /// How far one screen reader step moves a handle of a range without stops, as a share of its /// length. const STEP: f32 = 0.05; @@ -198,6 +199,7 @@ pub struct RangeScrubber { active: Rc>, value: (f32, f32), stops: Rc<[f32]>, + lock_high: bool, filled: Hsla, empty: Hsla, thumb: Hsla, @@ -218,6 +220,7 @@ impl RangeScrubber { active: state.active.clone(), value: (value.0.clamp(0., 1.), value.1.clamp(0., 1.)), stops: Rc::from(Vec::new()), + lock_high: false, filled: gpui::white(), empty: gpui::black(), thumb: gpui::white(), @@ -232,6 +235,12 @@ impl RangeScrubber { self } + /// Fixes the high endpoint in place while the low endpoint selects a bounded window. + pub fn lock_high(mut self) -> Self { + self.lock_high = true; + self + } + pub fn colors(mut self, filled: Hsla, empty: Hsla, thumb: Hsla) -> Self { self.filled = filled; self.empty = empty; @@ -281,6 +290,7 @@ impl RenderOnce for RangeScrubber { active, value, stops, + lock_high, filled, empty, thumb, @@ -303,7 +313,7 @@ impl RenderOnce for RangeScrubber { let stops = stops.clone(); move |event: &MouseDownEvent, window: &mut Window, cx: &mut App| { let share = snap(state.share_at(event.position.x, pad), &stops); - let near = match (share - value.0).abs() <= (share - value.1).abs() { + let near = match lock_high || (share - value.0).abs() <= (share - value.1).abs() { true => Handle::Low, false => Handle::High, }; @@ -404,8 +414,25 @@ impl RenderOnce for RangeScrubber { .right(relative(1. - value.1.max(value.0))) .bg(filled), ) + .when(!stops.is_empty(), |track| { + let height = pad * 1.5; + track.children(stops.iter().copied().map(|stop| { + div() + .absolute() + .top((line - height) / 2.) + .left(relative(stop)) + .ml(Pixels::ZERO - STOP_WIDTH / 2.) + .w(STOP_WIDTH) + .h(height) + .rounded_full() + .bg(thumb.opacity(0.6)) + })) + }) .child(knob(Handle::Low, low_value)) - .child(knob(Handle::High, high_value)), + .child(match lock_high { + true => handle(value.1, line, pin, thumb).into_any_element(), + false => knob(Handle::High, high_value).into_any_element(), + }), ) .child( canvas(move |b, _, _| bounds.set(b), |_, _, _, _| {}) diff --git a/crates/ui/src/info_card.rs b/crates/ui/src/info_card.rs index 6abc6928f..9f8d2d921 100644 --- a/crates/ui/src/info_card.rs +++ b/crates/ui/src/info_card.rs @@ -20,6 +20,8 @@ pub struct InfoCard { plain: bool, untitled: bool, flush: bool, + /// Something to set at the right of the title row, such as badges that describe the card. + trailing: Option, } impl InfoCard { @@ -34,6 +36,7 @@ impl InfoCard { plain: false, untitled: false, flush: false, + trailing: None, } } @@ -67,6 +70,12 @@ impl InfoCard { self } + /// Sets `element` at the right end of the title row, level with the title. + pub fn trailing(mut self, element: impl IntoElement) -> Self { + self.trailing = Some(element.into_any_element()); + self + } + /// Exposes the card to screen readers as a group named by its title, under the element id /// `id`. Without it the title is drawn but never read. pub fn spoken(mut self, id: impl Into) -> Self { @@ -105,6 +114,7 @@ impl RenderOnce for InfoCard { plain, untitled, flush, + trailing, } = self; let theme = *cx.theme(); @@ -126,7 +136,17 @@ impl RenderOnce for InfoCard { this.border_1().border_color(theme.border) }) }) - .when(!untitled, |this| this.child(eyebrow(title.clone(), cx))) + .when(!untitled, |this| { + this.child( + div() + .flex() + .items_center() + .justify_between() + .gap_3() + .child(eyebrow(title.clone(), cx)) + .children(trailing), + ) + }) .children(children); card.style().refine(&overrides); diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 6047b2bfb..d91fe76e1 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -72,7 +72,7 @@ pub use artwork::{ }; pub use button::{Button, SMALL_INSET}; pub use card::CARD_GROUP; -pub use card::Card; +pub use card::{Card, Corner}; pub use checkbox::Checkbox; pub use controls::WindowControls; #[cfg(any(target_os = "linux", target_os = "freebsd"))] diff --git a/crates/views/src/chrome/sidebar_left.rs b/crates/views/src/chrome/sidebar_left.rs index 5043bb9cb..cfe52a4f2 100644 --- a/crates/views/src/chrome/sidebar_left.rs +++ b/crates/views/src/chrome/sidebar_left.rs @@ -33,7 +33,7 @@ const PINS: &str = "sidebar-pins"; /// open one page of the merged streaming and local library. Settings lives in the account menu of /// the title bar and shows here only when added. It opens on the settings page last visited /// rather than on the one named here. -pub(crate) const NAV: [(NavEntry, &str, Destination); 8] = [ +pub(crate) const NAV: [(NavEntry, &str, Destination); 9] = [ (NavEntry::Home, "icons/house.svg", Destination::Home), (NavEntry::Search, "icons/search.svg", Destination::Search), ( @@ -41,6 +41,7 @@ pub(crate) const NAV: [(NavEntry, &str, Destination); 8] = [ "icons/rotate-ccw-clock.svg", Destination::History, ), + (NavEntry::Stats, "icons/gauge.svg", Destination::Stats), ( NavEntry::Settings, "icons/settings.svg", diff --git a/crates/views/src/chrome/title_bar.rs b/crates/views/src/chrome/title_bar.rs index 00adae9f6..986da0d3d 100644 --- a/crates/views/src/chrome/title_bar.rs +++ b/crates/views/src/chrome/title_bar.rs @@ -283,6 +283,11 @@ impl TitleBar { .icon("icons/rotate-ccw-clock.svg") .on_click(|_, _, cx| navigate(Destination::History, cx)), ) + .item( + MenuItem::new("account-stats", t!("nav-stats")) + .icon("icons/gauge.svg") + .on_click(|_, _, cx| navigate(Destination::Stats, cx)), + ) .item( MenuItem::new("account-settings", t!("nav-settings")) .icon("icons/settings.svg") diff --git a/crates/views/src/root.rs b/crates/views/src/root.rs index bb5eb4de2..6b8758145 100644 --- a/crates/views/src/root.rs +++ b/crates/views/src/root.rs @@ -25,6 +25,7 @@ use crate::chrome::{ }; use crate::screens::search::SearchView; use crate::screens::settings::SettingsHeader; +use crate::screens::stats::StatsView; use crate::shared::ambient::{self, Ambient}; use crate::shared::confirm::Confirm; use crate::shared::playlist_editor::PlaylistEditor; @@ -54,6 +55,7 @@ const TOAST_LAYER: usize = 1; struct Screens { home: Entity, history: Entity, + stats: Entity, library: Entity, artist: Option>, artist_detail: Option>, @@ -262,6 +264,9 @@ impl Root { let history = Sonora::global(cx).history.clone(); let history = cx.new(|cx| HistoryView::new(history, playback.clone(), window, cx)); + let stats = + cx.new(|cx| StatsView::new(Sonora::global(cx).stats.clone(), playback.clone(), cx)); + let queries = cx.new(|cx| Search::new(session.clone(), library.clone(), io.clone(), cx)); let suggestions = cx.new(|cx| Search::new(session.clone(), library.clone(), io.clone(), cx)); @@ -401,6 +406,7 @@ impl Root { screens: Screens { home, history, + stats, library: library_view, artist: None, artist_detail: None, @@ -710,6 +716,10 @@ impl Root { let history = Sonora::global(cx).history.clone(); Box::new(move |cx| matches!(history.read(cx).state(), HistoryState::Loading)) } + Destination::Stats => { + let stats = Sonora::global(cx).stats.clone(); + Box::new(move |cx| stats.read(cx).is_loading()) + } Destination::Library(_) => { let session = Sonora::global(cx).session.clone(); let streaming = shelf(Shelf::Streaming); @@ -756,6 +766,10 @@ impl Root { let history = Sonora::global(cx).history.clone(); history.update(cx, |history, cx| history.reload(cx)); } + Destination::Stats => { + let stats = Sonora::global(cx).stats.clone(); + stats.update(cx, |stats, cx| stats.refresh(cx)); + } Destination::Library(_) => library.update(cx, |library, cx| { library.reload(Shelf::Streaming, cx); library.reload(Shelf::Local, cx); @@ -1013,6 +1027,11 @@ impl Root { toolbar = Some(history.read(cx).toolbar()); history.into() } + Destination::Stats => { + let stats = self.screens.stats.clone(); + stats.update(cx, |view, cx| view.ensure(cx)); + stats.into() + } Destination::Library(tab) => { self.screens .library diff --git a/crates/views/src/screens/artist.rs b/crates/views/src/screens/artist.rs index 5b2f8e483..34e0275ed 100644 --- a/crates/views/src/screens/artist.rs +++ b/crates/views/src/screens/artist.rs @@ -938,6 +938,7 @@ impl ArtistView { tile: card, columns, tabs: None, + note: None, }, window, cx, diff --git a/crates/views/src/screens/detail.rs b/crates/views/src/screens/detail.rs index 3bf93a3e3..053995666 100644 --- a/crates/views/src/screens/detail.rs +++ b/crates/views/src/screens/detail.rs @@ -802,6 +802,7 @@ impl DetailView { tile: card, columns, tabs, + note: None, }, window, cx, diff --git a/crates/views/src/screens/mod.rs b/crates/views/src/screens/mod.rs index 64f33a922..0c4ae03c7 100644 --- a/crates/views/src/screens/mod.rs +++ b/crates/views/src/screens/mod.rs @@ -9,4 +9,5 @@ pub(crate) mod login; pub(crate) mod search; pub(crate) mod settings; pub(crate) mod song; +pub(crate) mod stats; pub(crate) mod user; diff --git a/crates/views/src/screens/stats/charts.rs b/crates/views/src/screens/stats/charts.rs new file mode 100644 index 000000000..3cdebfcb4 --- /dev/null +++ b/crates/views/src/screens/stats/charts.rs @@ -0,0 +1,224 @@ +use gpui::accesskit::Role; +use gpui::prelude::*; + +use gpui::{AnyElement, App, Context, Hsla, Pixels, SharedString, div, relative}; +use i18n::t; +use music::{Overview, Ranked}; +use ui::{ActiveTheme as _, Perch, Text, Tipped as _}; + +use super::StatsView; + +/// The hours labelled under the listening clock. +const HOUR_MARKS: [usize; 5] = [0, 6, 12, 18, 23]; + +impl StatsView { + /// A grid of the plays in each hour of each weekday, darker where there were more, with the + /// peak hour beside the heading. Nothing shows for a source without play times. + pub(super) fn clock( + &self, + overview: &Overview, + cx: &Context, + ) -> Option<(AnyElement, Option)> { + if overview.clock.is_empty() { + return None; + } + let note = self.badges( + [overview.peak_hour.map(|hour| { + ( + t!("stats-badge-peak", hour = hour_label(usize::from(hour))), + false, + ) + })], + cx, + ); + let theme = *cx.theme(); + let most = overview + .clock + .iter() + .copied() + .max() + .unwrap_or_default() + .max(1); + let gap = theme.metrics.pad / 4.; + let grid = + div() + .id("stats-clock") + .role(Role::List) + .aria_label(t!("stats-clock-title")) + .flex() + .flex_col() + .gap(gap) + .children((0..7).map(|day| { + let plays = &overview.clock[day * 24..(day + 1) * 24]; + let name = weekday(day); + let summary = t!( + "stats-clock-day", + day = name.as_str(), + count = plays.iter().sum::() + ); + div() + .id(("stats-clock-day", day)) + .role(Role::ListItem) + .aria_label(summary) + .flex() + .items_center() + .gap(theme.metrics.pad) + .child( + div() + .w(theme.metrics.pad * 4.) + .flex_none() + .child(ui::faint(cx).child(name.clone())), + ) + .child(div().flex().flex_1().gap(gap).children( + plays.iter().enumerate().map(|(hour, count)| { + div() + .id(("stats-clock-cell", day * 24 + hour)) + .tip_label( + format!("{name} {} · {count}", hour_label(hour)), + Perch::Above, + ) + .flex_1() + .h(theme.metrics.pad * 1.75) + .rounded(theme.radius / 2.) + .bg(heat(*count, most, cx)) + }), + )) + })) + .child( + div() + .flex() + .justify_between() + .pl(theme.metrics.pad * 5.) + .children(HOUR_MARKS.map(|hour| ui::faint(cx).child(hour_label(hour)))), + ) + .into_any_element(); + Some((grid, note)) + } +} + +/// The colour of a cell that holds `count` of at most `most`. +fn heat(count: usize, most: usize, cx: &App) -> Hsla { + let theme = cx.theme(); + match count { + 0 => theme.muted_foreground.opacity(0.1), + _ => theme + .primary + .opacity(0.2 + 0.8 * count as f32 / most as f32), + } +} + +fn weekday(day: usize) -> SharedString { + t!("stats-weekday", day = day) +} + +fn hour_label(hour: usize) -> String { + format!("{hour:02}:00") +} + +/// How far round the colour wheel each successive term moves, so neighbours never look alike. +const HUE_STEP: f32 = 0.618_034; +/// How many rows the terms are packed into. +const ROWS: usize = 2; +/// The height of a row, as a multiple of the theme's row height. +const ROW_SCALE: f32 = 0.9; +/// How opaque a tile's colour is until it is hovered. +const TILE_OPACITY: f32 = 0.8; +/// The smallest share, in percent, that a term needs to get a tile. +const MIN_SHARE: usize = 2; +/// How wide a character of a label is, as a multiple of its text size. +const GLYPH: f32 = 0.65; + +impl StatsView { + /// Packs the ranked terms into rounded tiles whose widths follow their shares. A name shows + /// on a tile that has room for it, and the share is in the tooltip. + pub(super) fn distribution( + &self, + tag: &'static str, + label: SharedString, + terms: &[Ranked], + width: Pixels, + cx: &Context, + ) -> AnyElement { + let theme = *cx.theme(); + let hits = |term: &Ranked| term.count.unwrap_or_default(); + let total = terms.iter().map(hits).sum::().max(1); + let terms: Vec<_> = terms + .iter() + .filter(|term| hits(term) * 100 >= total * MIN_SHARE) + .cloned() + .collect(); + let terms = terms.as_slice(); + let gap = theme.metrics.pad / 2.; + div() + .id(SharedString::from(format!("{tag}-distribution"))) + .role(Role::List) + .aria_label(label) + .flex() + .flex_col() + .gap(gap) + .children(rows(terms).into_iter().map(|row| { + let row_hits = row.iter().map(|&at| hits(&terms[at])).sum::().max(1); + div() + .flex() + .w_full() + .h(theme.metrics.row * ROW_SCALE) + .gap(gap) + .children(row.into_iter().map(|at| { + let term = &terms[at]; + let share = hits(term) as f32 / row_hits as f32; + let name = term.item.as_str(); + let summary = t!( + "stats-genre-share", + genre = name, + percent = (hits(term) as f32 / total as f32 * 100.).round() as usize + ); + let room = theme.text(Text::Small) * name.chars().count() as f32 * GLYPH + + theme.metrics.pad * 2.; + let colour = theme.primary_of(Hsla { + h: (theme.primary.h + at as f32 * HUE_STEP).fract(), + ..theme.primary + }); + div() + .id(SharedString::from(format!("{tag}-term-{name}"))) + .role(Role::ListItem) + .aria_label(summary.clone()) + .aria_position_in_set(at + 1) + .aria_size_of_set(terms.len()) + .tip_label(summary, Perch::Above) + .flex() + .items_center() + .justify_center() + .min_w_0() + .w(relative(share)) + .h_full() + .px(theme.metrics.pad / 2.) + .rounded(theme.radius / 2.) + .bg(colour.opacity(TILE_OPACITY)) + .hover(|tile| tile.bg(colour)) + .text_size(theme.text(Text::Small)) + .text_color(theme.primary_foreground) + .when(width * share >= room, |tile| { + tile.child(div().truncate().child(name.to_owned())) + }) + })) + })) + .into_any_element() + } +} + +/// Splits the terms into up to `ROWS` consecutive rows of nearly equal total weight, each term +/// going to the row its midpoint falls in. +fn rows(terms: &[Ranked]) -> Vec> { + let weight = |term: &Ranked| term.count.unwrap_or_default().max(1) as f64; + let total: f64 = terms.iter().map(weight).sum(); + let count = terms.len().min(ROWS); + let mut rows = vec![Vec::new(); count]; + let mut running = 0.; + for (at, term) in terms.iter().enumerate() { + let middle = running + weight(term) / 2.; + rows[((middle / total * count as f64) as usize).min(count - 1)].push(at); + running += weight(term); + } + rows.retain(|row| !row.is_empty()); + rows +} diff --git a/crates/views/src/screens/stats/insights.rs b/crates/views/src/screens/stats/insights.rs new file mode 100644 index 000000000..f61da2b73 --- /dev/null +++ b/crates/views/src/screens/stats/insights.rs @@ -0,0 +1,326 @@ +use gpui::accesskit::Role; +use gpui::prelude::*; +use gpui::{ + AnyElement, App, Context, Div, FontWeight, Hsla, Pixels, SharedString, div, px, relative, svg, +}; +use i18n::t; +use music::{Milestone, Trait}; +use ui::{ActiveTheme as _, Fact, Perch, Text, Theme, Tipped as _}; + +use super::timeline::date_label; +use super::{BAR_OFF, BAR_ON, StatsView, TILE_FILL, TILE_PAD, peak_era}; + +/// The size of a tile's icon, as a multiple of the theme pad, which is about the height of the +/// tile, and how faint a caption on the accent is. +const ICON_SIZE: f32 = 3.; +const ICON_QUIET: f32 = 0.8; +/// The narrowest a listening style tile is, as a multiple of the cover size. +const TRAIT_WIDTH: f32 = 2.6; +/// What a tile gives up of its share of a row, so that rounding never pushes one onto the next. +const ROUNDING: Pixels = px(1.); + +impl StatsView { + /// How the listener listens, in a few labels worked out from the figures, or nothing when + /// the source has too few to say. + pub(super) fn style( + &self, + traits: Vec, + width: Pixels, + cx: &Context, + ) -> Option { + let theme = *cx.theme(); + // As many to a row as the width holds, shared out so that the rows come out even and + // each tile grows to fill its row. + let gap = theme.metrics.pad; + let narrowest = theme.metrics.cover * TRAIT_WIDTH; + let fit = (((width + gap) / (narrowest + gap)) as usize).max(1); + let rows = traits.len().div_ceil(fit).max(1); + let columns = traits.len().div_ceil(rows).max(1); + let each = (width - gap * (columns as f32 - 1.)) / columns as f32; + (!traits.is_empty()).then(|| { + div() + .id("stats-style") + .role(Role::List) + .aria_label(t!("stats-style-title")) + .flex() + .flex_wrap() + .gap(theme.metrics.pad) + .children(traits.into_iter().map(|which| { + let (icon, name, note) = wording(which); + div() + .id(SharedString::from(format!("stats-trait-{name}"))) + .role(Role::ListItem) + .aria_label(SharedString::from(format!("{name}. {note}"))) + .flex_1() + .min_w(each - ROUNDING) + .child(tile(&theme, icon, name, note)) + })) + .into_any_element() + }) + } + + /// Small rounded labels for the figures that go with a section, the lit ones in the accent + /// colour. Nothing shows when there are none. + pub(super) fn badges( + &self, + items: impl IntoIterator>, + cx: &App, + ) -> Option { + let theme = *cx.theme(); + let items: Vec<_> = items.into_iter().flatten().collect(); + (!items.is_empty()).then(|| { + div() + .flex() + .flex_wrap() + .items_center() + .gap(theme.metrics.pad / 2.) + .children(items.into_iter().map(|(text, lit)| { + div() + .flex_none() + .px(theme.metrics.pad) + .py(theme.metrics.pad / 8.) + .rounded_full() + .text_size(theme.text(Text::Small)) + .font_weight(FontWeight::MEDIUM) + .map(|this| match lit { + true => this + .bg(theme.primary.opacity(0.18)) + .text_color(theme.primary), + false => this + .bg(theme.secondary.opacity(TILE_FILL)) + .text_color(theme.muted_foreground), + }) + .child(text) + })) + .into_any_element() + }) + } + + /// The plays of the whole history that reached a round number, oldest first, as the same + /// label and value rows the song page lists its details in. + pub(super) fn milestones(&self, milestones: &[Milestone]) -> Option { + (!milestones.is_empty()).then(|| { + div() + .id("stats-milestones") + .role(Role::List) + .aria_label(t!("stats-milestones-title")) + .flex() + .flex_col() + .children(milestones.iter().enumerate().map(|(index, milestone)| { + let label = match milestone.number { + 1 => t!("stats-milestone-first"), + count => t!("stats-milestone-nth", count = count), + }; + let (title, artist) = (&milestone.title, &milestone.artist); + let value = format!("{title} · {artist} · {}", date_label(milestone.at)); + Fact::new(label, value) + .spoken(("stats-milestone", milestone.number)) + .striped(index % 2 == 1) + })) + .into_any_element() + }) + } + + /// Bars for how many of the songs came out in each year, from the oldest to the newest, with + /// the years between that none came out in left empty. The years of the peak era stand out. + pub(super) fn years(&self, years: &[(i32, usize)], cx: &App) -> Option { + let (first, last) = (years.first()?.0, years.last()?.0); + let era = peak_era(years); + let bars = (first..=last) + .map(|year| { + let count = years + .iter() + .find(|(at, _)| *at == year) + .map_or(0, |(_, count)| *count); + let in_era = era.is_some_and(|(from, to)| (from..=to).contains(&year)); + ( + t!("stats-year-songs", year = year, count = count), + count, + in_era, + ) + }) + .collect(); + Some(self.histogram( + "stats-years", + t!("stats-years-label", from = first, to = last), + bars, + (first.to_string(), last.to_string()), + cx, + )) + } + + /// Bars for how many of the songs play at each tempo, slowest to fastest in bands of ten + /// beats per minute, with the busiest band standing out. + pub(super) fn tempo(&self, bands: &[(u16, usize)], cx: &App) -> Option { + let (first, last) = (bands.first()?.0, bands.last()?.0); + let most = bands.iter().map(|(_, count)| *count).max()?; + let bars = (first..=last) + .step_by(10) + .map(|band| { + let count = bands + .iter() + .find(|(at, _)| *at == band) + .map_or(0, |(_, count)| *count); + ( + t!( + "stats-tempo-songs", + from = band, + to = band + 9, + count = count + ), + count, + count == most, + ) + }) + .collect(); + Some(self.histogram( + "stats-tempo", + t!("stats-tempo-label", from = first, to = last + 9), + bars, + ( + t!("stats-tempo-bpm", bpm = first).to_string(), + t!("stats-tempo-bpm", bpm = last + 9).to_string(), + ), + cx, + )) + } + + /// Bars standing on a floor line, each with its tooltip, its count and whether it stands out, + /// under the labels of the first and the last. The release years and the tempos share it. + fn histogram( + &self, + id: &'static str, + label: SharedString, + bars: Vec<(SharedString, usize, bool)>, + ends: (String, String), + cx: &App, + ) -> AnyElement { + let theme = *cx.theme(); + let most = bars + .iter() + .map(|(_, count, _)| *count) + .max() + .unwrap_or_default() + .max(1); + div() + .id(id) + .role(Role::Group) + .aria_label(label) + .flex() + .flex_col() + .gap(theme.metrics.pad / 2.) + .child( + floor(&theme).children(bars.into_iter().enumerate().map( + |(at, (tip, count, stands_out))| { + let fill = match (count, stands_out) { + (0, _) => theme.muted_foreground.opacity(BAR_OFF), + (_, true) => theme.primary, + (_, false) => theme.primary.opacity(BAR_ON), + }; + bar(&theme, count as f32 / most as f32, fill) + .id((id, at)) + .tip_label(tip, Perch::Above) + }, + )), + ) + .child( + div() + .flex() + .justify_between() + .child(ui::faint(cx).child(ends.0)) + .child(ui::faint(cx).child(ends.1)), + ) + .into_any_element() + } +} + +/// The row that bars stand in, resting on a floor line. +pub(super) fn floor(theme: &Theme) -> Div { + div() + .flex() + .items_end() + .gap(theme.metrics.pad / 8.) + .h(theme.metrics.cover / 2.) + .border_b_1() + .border_color(theme.muted_foreground.opacity(BAR_OFF)) +} + +/// A bar `share` as tall as the row, rounded at the top only, so that it stands on the floor. +pub(super) fn bar(theme: &Theme, share: f32, fill: Hsla) -> Div { + div() + .flex_1() + .h(relative(share)) + .min_h(theme.metrics.pad / 4.) + .rounded_t(theme.radius / 2.) + .bg(fill) +} + +/// The icon of a trait, its name and a sentence on what it means. The name and the sentence are +/// the Fluent messages `stats-trait-` and `stats-trait--note`. +fn wording(which: Trait) -> (&'static str, SharedString, SharedString) { + let (icon, slug) = match which { + Trait::EarlyBird => ("icons/sunrise.svg", "early-bird"), + Trait::Daytime => ("icons/sun.svg", "daytime"), + Trait::Evening => ("icons/sunset.svg", "evening"), + Trait::NightOwl => ("icons/moon.svg", "night-owl"), + Trait::Weekender => ("icons/calendar-days.svg", "weekender"), + Trait::Weekday => ("icons/briefcase.svg", "weekday"), + Trait::Explorer => ("icons/compass.svg", "explorer"), + Trait::Loyalist => ("icons/heart.svg", "loyalist"), + Trait::Mainstream => ("icons/trending-up.svg", "mainstream"), + Trait::DeepDiver => ("icons/gem.svg", "deep-diver"), + Trait::Throwback => ("icons/rotate-ccw-clock.svg", "throwback"), + Trait::FreshEars => ("icons/sparkles.svg", "fresh-ears"), + Trait::Collaborator => ("icons/users-round-collaboration.svg", "collaborator"), + Trait::Superfan => ("icons/star.svg", "superfan"), + Trait::Daily => ("icons/flame.svg", "daily"), + Trait::Rising => ("icons/rocket.svg", "rising"), + Trait::FastLane => ("icons/zap.svg", "fast-lane"), + Trait::SlowBurner => ("icons/snail.svg", "slow-burner"), + }; + let key = format!("stats-trait-{slug}"); + ( + icon, + i18n::lookup(&key, None), + i18n::lookup(&format!("{key}-note"), None), + ) +} + +/// A tile of the accent colour with a large icon beside a name over a quieter sentence. +fn tile(theme: &Theme, icon: &'static str, title: SharedString, caption: SharedString) -> Div { + div() + .flex() + .items_center() + .gap(theme.metrics.pad * TILE_PAD) + .w_full() + .px(theme.metrics.pad * TILE_PAD) + .py(theme.metrics.pad) + .rounded(theme.radius) + .bg(theme.primary) + .child( + svg() + .path(icons::path(icon)) + .size(theme.metrics.pad * ICON_SIZE) + .flex_none() + .text_color(theme.primary_foreground), + ) + .child( + div() + .flex() + .flex_col() + .min_w_0() + .child( + div() + .text_size(theme.text(Text::Large)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.primary_foreground) + .child(title), + ) + .child( + div() + .text_size(theme.text(Text::Small)) + .text_color(theme.primary_foreground.opacity(ICON_QUIET)) + .child(caption), + ), + ) +} diff --git a/crates/views/src/screens/stats/mod.rs b/crates/views/src/screens/stats/mod.rs new file mode 100644 index 000000000..28b9c5000 --- /dev/null +++ b/crates/views/src/screens/stats/mod.rs @@ -0,0 +1,380 @@ +mod charts; +mod insights; +mod rankings; +mod timeline; + +use std::rc::Rc; + +use gpui::prelude::*; +use gpui::{AnyElement, App, Context, Entity, Render, SharedString, Window, div}; +use i18n::t; +use music::{Ranked, StatsPeriod}; +use state::{Playback, Sonora, Stats, StatsSource}; +use ui::{ActiveTheme as _, Button, Input, RangeState, Scrollbar, Scroller, TabBar, Text}; + +use crate::chrome::Chrome; +use crate::shared::album_grid::CardGrid; +use crate::shared::shelves::{Rail, STACK_GAP, section}; +use crate::shared::trouble; +use rankings::Kind; + +/// How much of the secondary colour the stats tiles, rows and badges are filled with. +const TILE_FILL: f32 = 0.6; +/// The inner padding of a tile, as a multiple of the theme pad. +const TILE_PAD: f32 = 1.5; + +/// How opaque a bar of a bar chart is where it counts and where it does not, in the primary and +/// the muted colour. +const BAR_ON: f32 = 0.6; +const BAR_OFF: f32 = 0.25; + +/// How many years the era of a listener's songs spans. +const ERA: i32 = 5; + +/// A section's tag, its title, the badges beside the title, and its body when it has one. +type Part = ( + &'static str, + SharedString, + Option, + Option, +); + +/// The room one stats section has, and what its rail needs to repaint the page. +#[derive(Clone, Copy)] +struct Layout<'a> { + columns: usize, + width: gpui::Pixels, + window: &'a Window, + notify: &'a Rc, +} + +/// Personal rankings from the provider, a linked scrobbler or the plays Sonora recorded, over +/// the window or the dates the listener picks. +pub(crate) struct StatsView { + stats: Entity, + playback: Entity, + scrollbar: Entity, + range: RangeState, + start: Entity, + end: Entity, + invalid: bool, + rails: Vec, +} + +impl StatsView { + pub(crate) fn new( + stats: Entity, + playback: Entity, + cx: &mut Context, + ) -> Self { + let chrome = Chrome::entity(cx); + cx.observe(&chrome, |_, _, cx| cx.notify()).detach(); + cx.observe(&stats, |this, _, cx| { + this.sync_dates(cx); + cx.notify(); + }) + .detach(); + cx.observe(&playback, |_, _, cx| cx.notify()).detach(); + let session = Sonora::global(cx).session.clone(); + cx.observe(&session, |_, _, cx| cx.notify()).detach(); + let host = cx.entity_id(); + let field = |name, cx: &mut Context| { + cx.new(|cx| Input::new("stats-date-hint", cx).compact().name(name)) + }; + let (start, end) = (field("range-from", cx), field("range-to", cx)); + for input in [&start, &end] { + cx.observe(input, |this, _, cx| this.apply_dates(cx)) + .detach(); + } + Self { + stats, + playback, + scrollbar: cx.new(|_| Scrollbar::inset().watching(host)), + range: RangeState::new("stats-date-range"), + start, + end, + invalid: false, + rails: Kind::ALL.iter().map(|_| Rail::new(host)).collect(), + } + } + + /// Loads the page when it has nothing current, so that coming back to it is instant. + pub(crate) fn ensure(&mut self, cx: &mut Context) { + self.stats.update(cx, |stats, cx| stats.ensure(cx)); + } + + pub(crate) fn refresh(&mut self, cx: &mut Context) { + self.rewind(); + self.stats.update(cx, |stats, cx| stats.refresh(cx)); + } + + /// Brings every rail back to its first card, since the cards behind it are about to change. + fn rewind(&self) { + for rail in &self.rails { + rail.rewind(); + } + } + + fn select(&mut self, source: StatsSource, period: StatsPeriod, cx: &mut Context) { + self.rewind(); + self.stats + .update(cx, |stats, cx| stats.select(source, period, cx)); + cx.notify(); + } + + /// The tab row that picks where the rankings come from. + fn source_tabs( + &self, + source: StatsSource, + period: StatsPeriod, + cx: &mut Context, + ) -> AnyElement { + let provider = SharedString::from( + Sonora::global(cx) + .session + .read(cx) + .provider_name() + .unwrap_or_default() + .to_owned(), + ); + let sources = self.stats.read(cx).sources(cx); + TabBar::new("stats-source-tabs") + .name(t!("stats-source")) + .items(sources.into_iter().map(|candidate| { + let (id, label) = match candidate { + StatsSource::Recorded => ("recorded", t!("stats-recorded")), + StatsSource::Provider => ("provider", provider.clone()), + StatsSource::Scrobbler(id) => { + (id, i18n::lookup(&format!("settings-{id}"), None)) + } + }; + Button::new(SharedString::from(format!("stats-source-{id}"))) + .label(label) + .small() + .ghost() + .selected(candidate == source) + .on_click(cx.listener(move |this, _, _, cx| this.select(candidate, period, cx))) + })) + .into_any_element() + } + + /// What replaces the rankings when the source failed to answer. + fn failure(&self, cx: &mut Context) -> AnyElement { + let detail = t!("stats-failed"); + let retry = cx.listener(|this, _, _, cx| this.refresh(cx)); + trouble::lost( + "stats-lost", + t!("trouble-not-loaded"), + Some(&detail), + retry, + cx, + ) + .into_any_element() + } + + /// Every section of the selected source in reading order, or the stand-ins for the rankings + /// while they load. + fn sections(&self, layout: &Layout<'_>, cx: &mut Context) -> Vec { + let stats = self.stats.read(cx); + if stats.failed() { + return vec![self.failure(cx)]; + } + if stats.is_loading() { + let tile = CardGrid::layout(layout.width).card; + return Kind::MAIN + .iter() + .map(|kind| { + Rail::pending(kind.title(), tile, layout.columns.max(1), layout.window, cx) + }) + .collect(); + } + + let data = stats.data(); + let barren = data.tracks.is_empty() && data.artists.is_empty() && data.albums.is_empty(); + let (traits, times) = (data.traits(), data.overview.clone()); + let (genres, tags, years) = (data.genres.clone(), data.tags.clone(), data.years.clone()); + let (tempos, milestones) = (data.tempos.clone(), data.milestones.clone()); + // Moods the app names itself are Fluent keys, and a provider's own are plain words. + let moods: Vec<_> = data + .moods + .iter() + .cloned() + .map(|mut mood| { + if mood.item.starts_with("stats-mood-") { + mood.item = i18n::lookup(&mood.item, None).to_string(); + } + mood + }) + .collect(); + let rails: Vec<_> = Kind::ALL + .iter() + .filter_map(|kind| self.rail(*kind, layout, cx)) + .collect(); + let era = self.badges( + [ + peak_era(&years) + .map(|(from, to)| (t!("stats-badge-era", from = from, to = to), false)), + times + .recent_share + .map(|share| (t!("stats-badge-recent", share = share), true)), + ], + cx, + ); + let bpm = self.badges( + [times + .avg_bpm + .map(|bpm| (t!("stats-badge-bpm", bpm = bpm), false))], + cx, + ); + let terms = |tag: &'static str, title: SharedString, terms: Vec>| { + let body = (!terms.is_empty()) + .then(|| self.distribution(tag, title.clone(), &terms, layout.width, cx)); + (tag, title, None, body) + }; + let (clock, note) = match self.clock(×, cx) { + Some((grid, note)) => (Some(grid), note), + None => (None, None), + }; + // The page reads from how much was listened to, to what the listening was like, to + // when it happened. + let before: Vec = vec![( + "stats-style", + t!("stats-style-title"), + None, + self.style(traits, layout.width, cx), + )]; + let after: Vec = vec![ + ( + "stats-years", + t!("stats-years-title"), + era, + self.years(&years, cx), + ), + ( + "stats-tempo", + t!("stats-tempo-title"), + bpm, + self.tempo(&tempos, cx), + ), + terms("stats-top-genres", t!("stats-top-genres"), genres), + terms("stats-top-moods", t!("stats-top-moods"), moods), + terms("stats-top-tags", t!("stats-top-tags"), tags), + ("stats-clock", t!("stats-clock-title"), note, clock), + ( + "stats-milestones", + t!("stats-milestones-title"), + None, + self.milestones(&milestones), + ), + ]; + let framed = |parts: Vec| -> Vec { + parts + .into_iter() + .filter_map(|(tag, title, note, body)| { + Some(section(tag, title, note, body?, layout.window, cx)) + }) + .collect() + }; + let mut sections = framed(before); + sections.extend(rails); + sections.extend(framed(after)); + if barren && sections.is_empty() { + sections.push(ui::vacant(t!("stats-empty"), cx).into_any_element()); + } + sections + } +} + +impl Render for StatsView { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = *cx.theme(); + let (source, period, periods) = { + let stats = self.stats.read(cx); + (stats.source(), stats.period(), stats.periods(cx)) + }; + let width = + (Chrome::content(window, cx) - theme.metrics.inset * 2.).max(theme.metrics.cover); + for rail in &self.rails { + rail.sync(); + } + let weak = cx.entity().downgrade(); + let notify: Rc = Rc::new(move |cx: &mut App| { + weak.update(cx, |_, cx| cx.notify()).ok(); + }); + let layout = Layout { + columns: CardGrid::layout(width).columns, + width, + window, + notify: ¬ify, + }; + + // The header stays above the page. Once the page has scrolled the timeline away, it also + // names the window the page is showing. + let scrolled = self.scrollbar.read(cx).offset() > theme.metrics.cover; + let header = div() + .flex() + .flex_none() + .items_center() + .gap(theme.metrics.inset) + .px(theme.metrics.inset) + .pt(theme.metrics.inset) + .pb(theme.metrics.inset / 2.) + .border_b_1() + .border_color(match scrolled { + true => theme.border, + false => theme.border.opacity(0.), + }) + .child( + ui::spoken_heading("stats-title", t!("nav-stats"), 1, cx) + .text_size(theme.text(Text::Display)), + ) + .child(self.source_tabs(source, period, cx)) + .when(scrolled, |header| { + header.child( + div() + .flex_1() + .min_w_0() + .truncate() + .text_right() + .child(ui::faint(cx).child(self.window_label(cx))), + ) + }); + let timeline = self.timeline(source, &periods, period, cx); + let sections = self.sections(&layout, cx); + div().flex().flex_col().size_full().child(header).child( + Scroller::new("stats-page", &self.scrollbar) + .w_full() + .flex_1() + .min_h_0() + .bottom_inset(Chrome::bottom(cx)) + .p(theme.metrics.inset) + .child( + div() + .flex() + .flex_col() + .gap(STACK_GAP) + .child(timeline) + .children(sections), + ), + ) + } +} + +/// The five consecutive release years that hold the most of the songs, as the first and last of +/// them, which is the era the listener's songs mostly come from. +pub(super) fn peak_era(years: &[(i32, usize)]) -> Option<(i32, i32)> { + let first = years.first()?.0; + let last = years.last()?.0; + let held = |start: i32| -> usize { + years + .iter() + .filter(|(year, _)| (start..start + ERA).contains(year)) + .map(|(_, count)| *count) + .sum() + }; + // Only windows that end by the last year with data, so the era never reaches into the future. + let start = (first - ERA + 1..=last - ERA + 1) + .max_by_key(|start| held(*start)) + .filter(|start| held(*start) > 0)?; + Some((start, start + ERA - 1)) +} diff --git a/crates/views/src/screens/stats/rankings.rs b/crates/views/src/screens/stats/rankings.rs new file mode 100644 index 000000000..e24c24de8 --- /dev/null +++ b/crates/views/src/screens/stats/rankings.rs @@ -0,0 +1,482 @@ +use std::rc::Rc; + +use gpui::accesskit::Role; +use gpui::prelude::*; +use gpui::{AnyElement, App, ClickEvent, Context, Pixels, SharedString, Window, div}; +use i18n::t; +use music::{Ranked, Track}; +use router::Destination; +use state::{Entry, Found, Origin, StatsSource}; +use ui::{Card, Corner}; + +use super::{Layout, StatsView}; +use crate::shared::album_grid::CardGrid; +use crate::shared::shelves::RailSpec; +use crate::shared::track_card::{StartHandler, TrackCard}; +use crate::shared::{cards, cells}; + +/// A ranking the page lists as a rail of cards. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Kind { + Artists, + Songs, + Albums, + Songwriters, + Producers, +} + +impl Kind { + pub(super) const ALL: [Self; 5] = [ + Self::Artists, + Self::Songs, + Self::Albums, + Self::Songwriters, + Self::Producers, + ]; + /// The rails every source has, which stand in for the page while it loads. + pub(super) const MAIN: [Self; 3] = [Self::Artists, Self::Songs, Self::Albums]; + + fn tag(self) -> &'static str { + match self { + Self::Artists => "stats-top-artists", + Self::Songs => "stats-top-songs", + Self::Albums => "stats-top-albums", + Self::Songwriters => "stats-top-songwriters", + Self::Producers => "stats-top-producers", + } + } + + /// The heading, which is the message the tag names. + pub(super) fn title(self) -> SharedString { + i18n::lookup(self.tag(), None) + } +} + +/// What the cards of a songs rail play from. +struct Queue { + /// Only the songs that can play. A chart entry the catalogue has not matched has no id. + tracks: Rc>, + /// Where each ranked song sits in `tracks`, or nothing for one that is left out. + places: Vec>, + start: StartHandler, +} + +/// A card for a ranked item that has no catalogue page of its own. +struct Plain { + title: String, + subtitle: SharedString, + cover: Option, + icon: &'static str, + circle: bool, + entry: Option, +} + +impl StatsView { + /// A ranking in a sideways rail with paging arrows, or nothing when it is empty. + pub(super) fn rail( + &self, + kind: Kind, + layout: &Layout<'_>, + cx: &mut Context, + ) -> Option { + let data = self.stats.read(cx).data(); + let count = match kind { + Kind::Artists => data.artists.len(), + Kind::Songs => data.tracks.len(), + Kind::Albums => data.albums.len(), + Kind::Songwriters => data.songwriters.len(), + Kind::Producers => data.producers.len(), + }; + if count == 0 { + return None; + } + + let tile = CardGrid::layout(layout.width).card; + let queue = (kind == Kind::Songs).then(|| { + let mut playable = Vec::new(); + let places = data + .tracks + .iter() + .map(|ranked| { + ranked.item.id.is_some().then(|| { + playable.push(ranked.item.clone()); + playable.len() - 1 + }) + }) + .collect(); + let tracks = Rc::new(playable); + let (playback, queued) = (self.playback.clone(), tracks.clone()); + let start: StartHandler = Rc::new(move |place, cx| { + playback.update(cx, |playback, cx| { + playback.start(queued.as_ref().clone(), place, None, cx) + }); + }); + Queue { + tracks, + places, + start, + } + }); + let weak = cx.entity().downgrade(); + Some(self.rails[kind as usize].render( + RailSpec { + tag: kind.tag(), + place: 0, + title: kind.title(), + count, + tile, + columns: layout.columns.max(1), + tabs: None, + note: self.notes(kind, cx), + }, + layout.window, + cx, + layout.notify, + move |at, _, cx| { + let Some(view) = weak.upgrade() else { + return div().into_any_element(); + }; + let Some((id, card)) = view.read(cx).card(kind, at, tile, queue.as_ref(), cx) + else { + return div().into_any_element(); + }; + div() + .id(id) + .role(Role::ListItem) + .aria_label(t!("stats-rank", rank = at + 1)) + .aria_position_in_set(at + 1) + .aria_size_of_set(count) + .child(card) + .into_any_element() + }, + )) + } + + /// What the rail counts, as badges beside its heading: how many, and how many are new. + fn notes(&self, kind: Kind, cx: &App) -> Option { + let data = self.stats.read(cx).data(); + let o = &data.overview; + // A source with no totals still says how many its rail lists. + let listed = |count: usize| Some(count).filter(|count| *count > 0); + let (total, new, extras) = match kind { + Kind::Artists => ( + o.artists + .or_else(|| listed(data.artists.len())) + .map(|count| t!("count-artists", count = count)), + o.new_artists, + vec![ + o.collab_share + .map(|share| t!("stats-badge-collabs", share = share)), + ], + ), + Kind::Songs => ( + o.tracks + .or_else(|| listed(data.tracks.len())) + .map(|count| t!("count-songs", count = count)), + o.new_tracks, + vec![ + o.plays.map(|plays| { + let value = cells::compact(plays as u64); + t!("stats-badge-plays", count = plays, value = value.as_str()) + }), + o.avg_length.map(|secs| { + let length = ui::clock(std::time::Duration::from_secs(secs)).to_string(); + t!("stats-badge-length", length = length) + }), + o.mainstream + .map(|score| t!("stats-badge-mainstream", score = score)), + ], + ), + Kind::Songwriters | Kind::Producers => (None, None, Vec::new()), + Kind::Albums => ( + o.albums + .or_else(|| listed(data.albums.len())) + .map(|count| t!("count-albums", count = count)), + None, + Vec::new(), + ), + }; + self.badges( + [ + total.map(|text| (text, false)), + new.map(|count| (t!("stats-badge-new", count = count), true)), + ] + .into_iter() + .chain( + extras + .into_iter() + .map(|text| text.map(|text| (text, false))), + ), + cx, + ) + } + + /// The card at rank `at + 1`, under an id that stays with its item as the ranking changes. + fn card( + &self, + kind: Kind, + at: usize, + tile: Pixels, + queue: Option<&Queue>, + cx: &App, + ) -> Option<(SharedString, AnyElement)> { + let stats = self.stats.read(cx); + let data = stats.data(); + let charted = matches!(stats.source(), StatsSource::Scrobbler(_)); + let (id, standing, card) = match kind { + Kind::Artists | Kind::Songwriters | Kind::Producers => { + let list = match kind { + Kind::Songwriters => &data.songwriters, + Kind::Producers => &data.producers, + _ => &data.artists, + }; + let ranked = list.get(at)?; + let artist = &ranked.item; + let id = format!( + "{}-{}", + kind.tag(), + identity(&artist.id, &ranked.external_url, &artist.name) + ); + let card = match artist.id.is_empty() { + false => cards::artist_card(card_id(&id), artist, &self.playback, cx), + true => self.plain( + &id, + Plain { + title: artist.name.clone(), + subtitle: i18n::lookup("artist-eyebrow", None), + cover: artist.cover.clone(), + icon: "icons/user-round.svg", + circle: true, + entry: charted.then(|| Entry::Artist { + name: artist.name.clone(), + }), + }, + ), + }; + (id, standing(at + 1, ranked, 0), card) + } + Kind::Songs => { + let ranked = data.tracks.get(at)?; + let track = &ranked.item; + let id = format!( + "stats-track-{}-{}", + identity( + track.id.as_deref().unwrap_or_default(), + &ranked.external_url, + &track.name + ), + track.artists + ); + let seat = queue.and_then(|queue| Some((queue, (*queue.places.get(at)?)?))); + let card = match seat { + Some((queue, place)) => TrackCard::new( + "stats-track-card", + place, + queue.tracks.clone(), + self.playback.clone(), + ) + .start(Some(queue.start.clone())) + .render(cx) + .underline() + .press({ + let id = track.id.clone().unwrap_or_default(); + move |_, _, cx| router::navigate(Destination::Song(id.clone().into()), cx) + }), + _ => self.plain( + &id, + Plain { + title: track.name.clone(), + subtitle: track.artists.clone().into(), + cover: track.cover.clone(), + icon: "icons/music.svg", + circle: false, + entry: charted.then(|| Entry::Track { + title: track.name.clone(), + artist: track.artists.clone(), + }), + }, + ), + }; + (id, standing(at + 1, ranked, track.popularity), card) + } + Kind::Albums => { + let ranked = data.albums.get(at)?; + let album = &ranked.item; + let id = format!( + "stats-album-{}-{}", + identity(&album.id, &ranked.external_url, &album.name), + album.artists + ); + let card = match album.id.is_empty() { + false => cards::album_card(card_id(&id), album, &self.playback, cx), + true => self.plain( + &id, + Plain { + title: album.name.clone(), + subtitle: album.artists.clone().into(), + cover: album.cover.clone(), + icon: "icons/music.svg", + circle: false, + entry: charted.then(|| Entry::Album { + title: album.name.clone(), + artist: album.artists.clone(), + }), + }, + ), + }; + (id, standing(at + 1, ranked, 0), card) + } + }; + let card = standing.dress(card.tile(tile).flat()); + Some((SharedString::from(id), card.into_any_element())) + } + + /// A card for an item the active catalogue has not matched. A chart entry opens and plays + /// by being matched on demand. + fn plain(&self, id: &str, plain: Plain) -> Card { + let Plain { + title, + subtitle, + cover, + icon, + circle, + entry, + } = plain; + Card::new(card_id(id), title) + .cover(cover) + .fallback(icon) + .description(subtitle.clone()) + .meta(subtitle) + .when(circle, Card::circle) + .when_some(entry, |card, entry| { + card.press(self.open(entry.clone(), false)) + .play(false, self.open(entry, true)) + }) + } + + /// Matches a chart entry to the catalogue, then opens its page, or starts it playing from the + /// card's play button. A song plays as a radio. + fn open( + &self, + entry: Entry, + play: bool, + ) -> impl Fn(&ClickEvent, &mut Window, &mut App) + 'static { + let (stats, playback) = (self.stats.clone(), self.playback.clone()); + move |_, _, cx| { + let playback = playback.clone(); + stats.update(cx, |stats, cx| { + stats.resolve( + entry.clone(), + move |found, cx| { + let Some(found) = found else { + return; + }; + let origin = match (&found, play) { + (Found::Track(track), true) => { + return playback + .update(cx, |playback, cx| playback.play_radio(track, cx)); + } + (Found::Artist(artist), true) => { + Origin::artist(artist.id.clone()).named(artist.name.clone()) + } + (Found::Album(album), true) => { + Origin::album(album.id.clone()).named(album.name.clone()) + } + (_, false) => { + return router::navigate( + match found { + Found::Track(track) => { + Destination::Song(track.id.unwrap_or_default().into()) + } + Found::Artist(artist) => { + Destination::Artist(artist.id.into()) + } + Found::Album(album) => Destination::Album(album.id.into()), + }, + cx, + ); + } + }; + playback.update(cx, |playback, cx| playback.toggle_origin(&origin, cx)); + }, + cx, + ); + }); + } + } +} + +/// What the source knows of a ranked item: its place, plays, whether it is new and how popular +/// the song is. A source that ranks by affinity alone has no plays, and none are invented. +struct Standing { + rank: usize, + count: Option, + fresh: bool, + popularity: u32, +} + +fn standing(rank: usize, ranked: &Ranked, popularity: u32) -> Standing { + Standing { + rank, + count: ranked.count, + fresh: ranked.fresh, + popularity, + } +} + +impl Standing { + /// The word that marks an item as new to the ranking. A rank that only moved has none. + fn movement(&self) -> Option { + self.fresh.then(|| t!("stats-rank-new")) + } + + /// Lays the standing over the card's artwork: the place, with how it moved, in the top left, + /// the song's popularity in the bottom left and the plays in the bottom right, where the play + /// button takes over on hover. The card's spoken description carries all of it. + fn dress(self, card: Card) -> Card { + let place = t!("stats-rank", rank = self.rank); + let movement = self.movement(); + let plays = self.count.map(|count| { + let value = cells::compact(count as u64); + t!("stats-badge-plays", count = count, value = value.as_str()) + }); + let spoken = [ + Some(place.clone()), + movement.clone(), + plays.clone(), + (self.popularity > 0).then(|| t!("stats-rank-popularity", score = self.popularity)), + ] + .into_iter() + .flatten() + .collect::>() + .join(", "); + let place = match movement { + Some(movement) => SharedString::from(format!("{place} {movement}")), + None => place, + }; + card.description(spoken) + .badge(Corner::TopLeft, place) + .when(self.popularity > 0, |card| { + card.icon_badge( + Corner::BottomLeft, + "icons/flame.svg", + self.popularity.to_string(), + ) + }) + .when_some(plays, |card, plays| card.badge(Corner::BottomRight, plays)) + } +} + +/// What keeps a row's id steady as the ranking changes: the catalogue id when it has one, else +/// the chart's own page, else the name. +fn identity<'a>(id: &'a str, url: &'a Option, name: &'a str) -> &'a str { + match id.is_empty() { + true => url.as_deref().unwrap_or(name), + false => id, + } +} + +/// The id of the card in the row that has `row` for its id. +fn card_id(row: &str) -> SharedString { + SharedString::from(format!("{row}-card")) +} diff --git a/crates/views/src/screens/stats/timeline.rs b/crates/views/src/screens/stats/timeline.rs new file mode 100644 index 000000000..64f525fdf --- /dev/null +++ b/crates/views/src/screens/stats/timeline.rs @@ -0,0 +1,511 @@ +use gpui::prelude::*; +use gpui::{AnyElement, App, Context, FontWeight, SharedString, div, relative}; +use i18n::t; +use jiff::civil::Date; +use jiff::tz::TimeZone; +use jiff::{Span, Timestamp, Unit}; +use music::StatsPeriod; +use state::StatsSource; +use ui::{ActiveTheme as _, Button, InfoCard, RangeScrubber, TabBar, Text}; + +use super::insights::{bar, floor}; +use super::{BAR_OFF, BAR_ON, StatsView}; + +const EPOCH: Date = Date::constant(1970, 1, 1); +/// The quick ranges over recorded plays, longest first like the windows of a provider and the +/// scrubber's track: the Fluent key naming each, and its length in days. +const PRESETS: [(&str, i64); 5] = [ + ("stats-year", 365), + ("stats-six-months", 182), + ("stats-quarter", 91), + ("stats-month", 30), + ("stats-week", 7), +]; +/// How far the scrubber's track is inset from its ends, as a multiple of the theme pad. +const TRACK_INSET: f32 = 0.75; + +impl StatsView { + /// The window the rankings cover, and the way to change it: a free range of dates over the + /// recorded plays, or a pick among the fixed windows of a provider or scrobbler. + pub(super) fn timeline( + &self, + source: StatsSource, + periods: &[StatsPeriod], + period: StatsPeriod, + cx: &mut Context, + ) -> AnyElement { + let parts = match source { + StatsSource::Provider => self.fixed_window(source, periods, period, cx), + _ => self.dated_window(cx), + }; + // What the window held sits at the right of the title row, level with the title. + let overview = &self.stats.read(cx).data().overview; + let hours = overview + .time + .filter(|secs| *secs > 0) + .map(|secs| match secs >= 3600 { + true => t!("stats-badge-hours", count = secs / 3600), + false => t!("stats-badge-minutes", count = secs / 60), + }); + let held = [ + overview.plays_per_day.map(|plays| { + t!( + "stats-badge-per-day", + count = plays.round().max(1.) as usize + ) + }), + hours, + overview + .replay_share + .map(|share| t!("stats-badge-replays", share = share)), + overview + .change + .map(|change| t!("stats-badge-change", change = format!("{change:+}"))), + ]; + let badges = self.badges(held.map(|text| text.map(|text| (text, false))), cx); + InfoCard::new(t!("stats-period-title")) + .spoken("stats-period") + .children(parts) + .when_some(badges, |card, badges| card.trailing(badges)) + .into_any_element() + } + + /// Names what the figures and rankings on show cover: the selected dates of the recorded + /// plays, or the fixed window of any other source. + pub(super) fn window_label(&self, cx: &App) -> SharedString { + let stats = self.stats.read(cx); + match (stats.source(), stats.dates()) { + (StatsSource::Provider, _) => i18n::lookup(period_key(stats.period()), None), + (_, Some((from, to))) => t!( + "stats-selected-dates", + from = date_label(from), + to = date_label(to) + ), + (_, None) => t!("stats-all-time"), + } + } + + /// Keeps the date fields on the selected range, or on all the history, once either changes. + pub(super) fn sync_dates(&mut self, cx: &mut Context) { + let stats = self.stats.read(cx); + if stats.source() == StatsSource::Provider { + return; + } + let Some((from, to)) = stats.dates().or_else(|| stats.bounds()) else { + return; + }; + for (field, seconds) in [(&self.start, from), (&self.end, to)] { + let label = date_label(seconds); + field.update(cx, |input, cx| { + if input.text() != label { + input.set_text(label, cx); + } + }); + } + } + + /// The fixed windows of a source, laid along one track from the broadest on the left to the + /// shortest on the right, all ending now. A source with a single window has nothing to pick. + fn fixed_window( + &self, + source: StatsSource, + periods: &[StatsPeriod], + period: StatsPeriod, + cx: &mut Context, + ) -> Vec { + let theme = *cx.theme(); + let windows: Vec<_> = periods.iter().copied().rev().collect(); + let label = i18n::lookup(period_key(period), None); + let mut parts = vec![headline(label.clone(), None, cx)]; + if windows.len() < 2 { + parts.push( + ui::faint(cx) + .child(t!("stats-window-fixed")) + .into_any_element(), + ); + return parts; + } + + let count = windows.len(); + let middle = |index: usize| (index as f32 + 0.5) / count as f32; + let selected = windows + .iter() + .position(|window| *window == period) + .unwrap_or(0); + let picks = windows.clone(); + parts.push( + RangeScrubber::new(&self.range, (middle(selected), 1.)) + .stops((0..count).map(middle).collect()) + .lock_high() + .name(t!("stats-period-title")) + .values(label, t!("stats-now")) + .colors(theme.primary, theme.secondary, theme.foreground) + .on_change(cx.listener(move |this, &(low, _): &(f32, f32), _, cx| { + let index = + ((low * count as f32 - 0.5).round().max(0.) as usize).min(count - 1); + let chosen = picks[index]; + if chosen != this.stats.read(cx).period() { + this.select(source, chosen, cx); + } + })) + .into_any_element(), + ); + parts.push( + TabBar::new("stats-windows") + .name(t!("stats-period-title")) + .items(windows.into_iter().enumerate().map(|(index, window)| { + Button::new(("stats-window", index)) + .label(i18n::lookup(period_key(window), None)) + .small() + .ghost() + .selected(window == period) + .on_click( + cx.listener(move |this, _, _, cx| this.select(source, window, cx)), + ) + })) + .into_any_element(), + ); + parts + } + + /// A free range over the recorded plays: a scrubber under the shape of the listening, quick + /// ranges, and exact dates. + fn dated_window(&self, cx: &mut Context) -> Vec { + let theme = *cx.theme(); + let (bounds, dates) = { + let stats = self.stats.read(cx); + (stats.bounds(), stats.dates()) + }; + let label = self.window_label(cx); + let Some(bounds) = bounds else { + return vec![headline(label, None, cx)]; + }; + + let low = day_number(bounds.0); + let width = (day_number(bounds.1).max(low + 1) - low) as f32; + let share = |seconds| ((day_number(seconds) - low) as f32 / width).clamp(0., 1.); + let value = dates.map_or((0., 1.), |(from, to)| (share(from), share(to))); + let days = dates.map_or(width as i64 + 1, |(from, to)| { + day_number(to) - day_number(from) + 1 + }); + let inset = theme.metrics.pad * TRACK_INSET; + let place = |date: Date| ((date_number(date) - low) as f32 / width).clamp(0., 1.); + let (busiest, streak) = { + let stats = self.stats.read(cx); + let history = stats.history(); + let busiest = history + .and_then(|history| history.busiest_day) + .map(|(day, plays)| { + ( + place(day), + t!("stats-mark-busiest", day = day.to_string(), count = plays), + ) + }); + let streak = history + .and_then(|history| history.streak) + .map(|(from, to)| { + let days = to + .since((Unit::Day, from)) + .map_or(1, |span| span.get_days() + 1); + ( + (place(from), place(to)), + t!("stats-mark-streak", count = days), + ) + }); + (busiest, streak) + }; + let mut parts = vec![ + self.date_row(Some(t!("count-days", count = days)), cx), + div() + .flex() + .flex_col() + .children( + (!self.stats.read(cx).density().is_empty()) + .then(|| self.brush(value, cx).px(inset)), + ) + .child( + RangeScrubber::new(&self.range, value) + .name(t!("stats-period-title")) + .values( + date_label(dates.map_or(bounds.0, |dates| dates.0)), + date_label(dates.map_or(bounds.1, |dates| dates.1)), + ) + .colors(theme.primary, theme.secondary, theme.foreground) + .on_change(cx.listener(move |this, &(a, b): &(f32, f32), _, cx| { + let day = |share: f32| low + (share * width).round() as i64; + if let Some(dates) = span(day(a), day(b)) { + this.set_dates(Some(dates), cx); + } + })), + ) + .into_any_element(), + ]; + parts.extend( + self.annotations(busiest, streak, cx) + .map(|lane| lane.px(inset).into_any_element()), + ); + parts.push(self.presets(dates, cx)); + parts + } + + /// Bars for the plays across the whole history, in colour where the selection covers them, + /// standing on a floor line. + fn brush(&self, selection: (f32, f32), cx: &App) -> gpui::Div { + let theme = *cx.theme(); + let density = self.stats.read(cx).density(); + let most = density.iter().copied().max().unwrap_or_default().max(1); + floor(&theme).children(density.iter().enumerate().map(|(index, count)| { + let at = (index as f32 + 0.5) / density.len() as f32; + let covered = (selection.0..=selection.1).contains(&at); + bar( + &theme, + *count as f32 / most as f32, + match covered { + true => theme.primary.opacity(BAR_ON), + false => theme.muted_foreground.opacity(BAR_OFF), + }, + ) + })) + } + + /// Marks the busiest day and the longest streak of the whole history under the scrubber, so + /// they stay put as the window moves. The streak is a bar across its days with its length + /// inside, and the busiest day a line up to its day with its label below. Each is a share of + /// the track's width. Nothing shows when the source has neither. + fn annotations( + &self, + busiest: Option<(f32, SharedString)>, + streak: Option<((f32, f32), SharedString)>, + cx: &App, + ) -> Option { + let theme = *cx.theme(); + if busiest.is_none() && streak.is_none() { + return None; + } + Some( + div() + .flex() + .flex_col() + .gap(theme.metrics.pad) + .children(streak.map(|((from, to), text)| { + div().relative().h(theme.metrics.pad * 2.5).child( + div() + .absolute() + .top_0() + .bottom_0() + .left(relative(from)) + .w(relative(to - from)) + .min_w(theme.metrics.cover * 1.5) + .flex() + .items_center() + .justify_center() + .overflow_hidden() + .rounded_full() + .bg(theme.primary) + .text_size(theme.text(Text::Small)) + .font_weight(FontWeight::SEMIBOLD) + .text_color(theme.primary_foreground) + .whitespace_nowrap() + .child(text), + ) + })) + .children(busiest.map(|(at, text)| { + let label = div() + .absolute() + .top(theme.metrics.pad * 2.) + .whitespace_nowrap() + .child(ui::faint(cx).child(text)); + div() + .relative() + .h(theme.metrics.pad * 4.5) + .child( + div() + .absolute() + .top_0() + .left(relative(at)) + .w(theme.metrics.pad / 8.) + .h(theme.metrics.pad * 1.5) + .rounded_full() + .bg(theme.foreground), + ) + .child(match at > 0.5 { + true => label.right(relative(1. - at)), + false => label.left(relative(at)), + }) + })), + ) + } + + /// The whole history, and quick ranges ending today, longest first. + fn presets(&self, dates: Option<(i64, i64)>, cx: &mut Context) -> AnyElement { + let today = day_number(Timestamp::now().as_second()); + let all = Button::new("stats-preset-all") + .label(t!("stats-all-time")) + .small() + .ghost() + .selected(dates.is_none()) + .on_click(cx.listener(|this, _, _, cx| this.set_dates(None, cx))); + let recent = PRESETS.into_iter().map(|(key, days)| { + let first = today - (days - 1); + let chosen = dates + .is_some_and(|(from, to)| day_number(from) == first && day_number(to) == today); + Button::new(("stats-preset", days as usize)) + .label(i18n::lookup(key, None)) + .small() + .ghost() + .selected(chosen) + .on_click(cx.listener(move |this, _, _, cx| { + this.set_dates(span(first, today), cx); + })) + }); + TabBar::new("stats-presets") + .name(t!("stats-period-title")) + .items(std::iter::once(all).chain(recent)) + .into_any_element() + } + + /// The selected dates as two fields that take the window the moment they hold dates in + /// order, with a quieter note beside them. + fn date_row(&self, note: Option, cx: &App) -> AnyElement { + let theme = cx.theme(); + let field = + |input: &gpui::Entity| div().w(theme.metrics.cover).child(input.clone()); + div() + .flex() + .items_center() + .justify_between() + .gap(theme.metrics.pad) + .child( + div() + .flex() + .items_center() + .gap(theme.metrics.pad / 2.) + .child(field(&self.start)) + .child(ui::faint(cx).child("–")) + .child(field(&self.end)), + ) + .children(note.map(|note| ui::faint(cx).child(note))) + .into_any_element() + } + + /// Applies a range of dates, where one covering the whole history counts as all of it. + fn set_dates(&mut self, dates: Option<(i64, i64)>, cx: &mut Context) { + self.rewind(); + let bounds = self.stats.read(cx).bounds(); + let whole = |(from, to): (i64, i64)| { + bounds.is_some_and(|bounds| { + day_number(from) <= day_number(bounds.0) && day_number(to) >= day_number(bounds.1) + }) + }; + let dates = dates.filter(|dates| !whole(*dates)); + self.stats + .update(cx, |stats, cx| stats.set_dates(dates, cx)); + cx.notify(); + } + + /// Applies the typed dates once they are dates in order, and flags the fields while they + /// are not. Typing a range that is already selected changes nothing. + pub(super) fn apply_dates(&mut self, cx: &mut Context) { + let typed = parse_date(self.start.read(cx).text(), false) + .zip(parse_date(self.end.read(cx).text(), true)) + .filter(|(from, to)| from <= to); + let invalid = typed.is_none(); + if invalid != self.invalid { + self.invalid = invalid; + for field in [&self.start, &self.end] { + field.update(cx, |input, cx| input.set_invalid(invalid, cx)); + } + } + let current = { + let stats = self.stats.read(cx); + stats.dates().or_else(|| stats.bounds()) + }; + let same = |(from, to): (i64, i64)| { + current.is_some_and(|(now_from, now_to)| { + day_number(from) == day_number(now_from) && day_number(to) == day_number(now_to) + }) + }; + if let Some(dates) = typed.filter(|dates| !same(*dates)) { + self.set_dates(Some(dates), cx); + } + } +} + +/// The selected window as a heading, with a quieter note beside it. +fn headline(label: SharedString, note: Option, cx: &App) -> AnyElement { + div() + .flex() + .items_baseline() + .justify_between() + .gap(cx.theme().metrics.pad) + .child(ui::heading(label, cx)) + .children(note.map(|note| ui::faint(cx).child(note))) + .into_any_element() +} + +fn period_key(period: StatsPeriod) -> &'static str { + match period { + StatsPeriod::Weeks => "stats-four-weeks", + StatsPeriod::Months => "stats-six-months", + StatsPeriod::Year => "stats-year", + } +} + +/// A typed local date as the first second of its day, or as the last when it ends a range. +fn parse_date(value: &str, end: bool) -> Option { + let date: Date = value.trim().parse().ok()?; + match end { + true => end_of(date), + false => start_of(date), + } +} + +/// The local calendar date of a Unix second. +pub(super) fn local_date(seconds: i64) -> Option { + Some( + Timestamp::from_second(seconds) + .ok()? + .to_zoned(TimeZone::system()) + .date(), + ) +} + +pub(super) fn date_label(seconds: i64) -> String { + local_date(seconds) + .map(|date| date.to_string()) + .unwrap_or_default() +} + +/// The first second of a local date. Local midnight is looked up for the date itself, so a day +/// with a daylight saving change is still whole. +fn start_of(date: Date) -> Option { + let midnight = date.at(0, 0, 0, 0).to_zoned(TimeZone::system()).ok()?; + Some(midnight.timestamp().as_second()) +} + +/// The last second of a local date. +fn end_of(date: Date) -> Option { + Some(start_of(date.tomorrow().ok()?)? - 1) +} + +/// The whole days from the first day to the last, as the seconds that start and end them. +fn span(first: i64, last: i64) -> Option<(i64, i64)> { + Some((start_of(date_at(first)?)?, end_of(date_at(last)?)?)) +} + +/// The count of days from 1970-01-01 to the local date of a Unix second, which makes a slider +/// handle land on whole days. +fn day_number(seconds: i64) -> i64 { + local_date(seconds).map_or(0, date_number) +} + +/// The count of days from 1970-01-01 to a date. +fn date_number(date: Date) -> i64 { + date.since((Unit::Day, EPOCH)) + .map_or(0, |days| i64::from(days.get_days())) +} + +/// The date `day_number` counted `day` days from 1970-01-01 for. +fn date_at(day: i64) -> Option { + EPOCH.checked_add(Span::new().try_days(day).ok()?).ok() +} diff --git a/crates/views/src/shared/cells.rs b/crates/views/src/shared/cells.rs index 47ba8febc..e832a9698 100644 --- a/crates/views/src/shared/cells.rs +++ b/crates/views/src/shared/cells.rs @@ -420,6 +420,26 @@ pub(crate) fn count(value: u64) -> SharedString { SharedString::from(grouped) } +/// A count in the short form a badge has room for: 109k for 109,637, 1.2M for 1,234,567, and the +/// plain grouped number below ten thousand. +pub(crate) fn compact(value: u64) -> SharedString { + let short = |value: f64, unit: u64| { + let scaled = value / unit as f64; + // One decimal helps while the number is small, and is noise once it has three digits. + match scaled < 100. { + true => format!("{:.1}", (scaled * 10.).floor() / 10.) + .trim_end_matches(".0") + .to_owned(), + false => format!("{}", scaled.floor() as u64), + } + }; + match value { + ..10_000 => count(value), + 10_000..1_000_000 => t!("number-thousand", value = short(value as f64, 1_000)), + _ => t!("number-million", value = short(value as f64, 1_000_000)), + } +} + pub(crate) fn title( cell: &Cell, value: impl Into, diff --git a/crates/views/src/shared/shelves.rs b/crates/views/src/shared/shelves.rs index e59ed7c0c..72f44d95d 100644 --- a/crates/views/src/shared/shelves.rs +++ b/crates/views/src/shared/shelves.rs @@ -21,7 +21,8 @@ const ROWS: usize = 3; const STEADY: Pixels = px(0.5); const PENDING: usize = 3; const RAIL_GAP: Pixels = px(16.); -const STACK_GAP: Pixels = px(32.); +/// The space between the sections of a page that stacks rails and other sections. +pub(crate) const STACK_GAP: Pixels = px(32.); const LANE_GAP: Pixels = px(8.); const HEADING_GAP: Pixels = px(12.); const LEADING: f32 = 1.4; @@ -505,6 +506,7 @@ impl Rail { tile, columns, tabs, + note, } = spec; let tall = Card::tile_height(tile, window, cx); let inset = cx.theme().metrics.inset; @@ -528,11 +530,20 @@ impl Rail { .justify_between() .gap_4() .h(head(window, cx)) - .child(shelf_heading( - SharedString::from(format!("{tag}-heading-{place}")), - title, - cx, - )) + .child( + div() + .flex() + .items_center() + .h_full() + .gap_3() + .min_w_0() + .child(shelf_heading( + SharedString::from(format!("{tag}-heading-{place}")), + title, + cx, + )) + .children(note), + ) .children(arrows), ) .children(tabs.map(|tabs| div().px(inset).child(tabs))) @@ -625,6 +636,39 @@ pub(crate) struct RailSpec { pub tile: Pixels, pub columns: usize, pub tabs: Option, + /// Small badges beside the heading, such as what the rail counts. + pub note: Option, +} + +/// A page section that is no rail, under the same heading and spacing as one. +pub(crate) fn section( + tag: &'static str, + title: SharedString, + note: Option, + body: impl IntoElement, + window: &Window, + cx: &App, +) -> AnyElement { + div() + .flex() + .flex_col() + .gap_3() + .child( + div() + .flex() + .items_end() + .h(head(window, cx)) + .gap_3() + .items_center() + .child(shelf_heading( + SharedString::from(format!("{tag}-heading")), + title, + cx, + )) + .children(note), + ) + .child(body) + .into_any_element() } /// The paging arrows of a rail head, which is what tells a crowded rail from a short one.