Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 61 additions & 8 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -627,21 +627,55 @@ pub async fn track_rows(session: &Session, uris: Vec<String>) -> Res<Vec<Row>> {
/// Songs Spotify recommends for a list (its radio station), for smart shuffle. Seeded by
/// the list (playlists, albums, artists), else by `track` (Liked Songs, search). Up to 50.
pub async fn recommendations(session: &Session, list: &str, track: &str) -> Vec<Row> {
async fn station(session: &Session, seed: &str) -> Vec<String> {
let scope = if seed.starts_with("spotify:track:") { "tracks" } else { "stations" };
let Ok(body) = session.spclient().get_apollo_station(scope, seed, Some(50), Vec::new(), false).await else {
return Vec::new();
};
let v: Value = serde_json::from_slice(&body).unwrap_or_default();
station_uris(&v)
}
let mut uris = if list.starts_with("spotify:") { station(session, list).await } else { Vec::new() };
if uris.is_empty() {
uris = station(session, track).await;
}
track_rows(session, uris).await.unwrap_or_default()
}

/// Up to 50 songs of Spotify's radio for a list or a song (empty if it has none).
pub async fn station(session: &Session, seed: &str) -> Vec<String> {
let scope = if seed.starts_with("spotify:track:") { "tracks" } else { "stations" };
let Ok(body) = session.spclient().get_apollo_station(scope, seed, Some(50), Vec::new(), false).await else {
return Vec::new();
};
let v: Value = serde_json::from_slice(&body).unwrap_or_default();
station_uris(&v)
}

/// Each song's first artist, as (artist uri, name), from one batched metadata request.
pub async fn track_artists(session: &Session, uris: &[String]) -> Res<HashMap<String, (String, String)>> {
Ok(entities::<PTrack>(session, uris, ExtensionKind::TRACK_V4)
.await?
.into_iter()
.filter_map(|(u, t)| {
let a = t.artist.first()?;
Some((u, (gid_uri("artist", a.gid())?, a.name().to_string())))
})
.collect())
}

/// What an artist's page lists besides their music: related artists (uri, name), and the
/// uris of their top songs. The same GraphQL query the artist page uses for play counts.
pub async fn artist_overview(session: &Session, uri: &str) -> Res<(Vec<(String, String)>, Vec<String>)> {
let v = gql(session, GQL_ARTIST, serde_json::json!({ "uri": uri, "locale": "", "includePrerelease": false })).await?;
Ok(overview_of(&v["data"]["artistUnion"]))
}

fn overview_of(a: &Value) -> (Vec<(String, String)>, Vec<String>) {
let items = |v: &Value| v["items"].as_array().cloned().unwrap_or_default();
let related = items(&a["relatedContent"]["relatedArtists"])
.iter()
.filter_map(|r| Some((r["uri"].as_str()?.to_string(), r["profile"]["name"].as_str().unwrap_or("").to_string())))
.collect();
let top = items(&a["discography"]["topTracks"])
.iter()
.filter_map(|t| t["track"]["uri"].as_str().filter(|u| u.starts_with("spotify:track:")).map(String::from))
.collect();
(related, top)
}

fn station_uris(v: &Value) -> Vec<String> {
v["tracks"].as_array().into_iter().flatten().filter_map(|t| t["uri"].as_str()).filter(|u| u.starts_with("spotify:track:")).map(String::from).collect()
}
Expand Down Expand Up @@ -697,6 +731,11 @@ fn list_path(dir: &std::path::Path, uri: &str) -> std::path::PathBuf {
dir.join("lists").join(uri.replace([':', '/', '\\'], "_"))
}

/// How long ago the list was saved.
pub fn list_age(dir: &std::path::Path, uri: &str) -> Option<Duration> {
std::fs::metadata(list_path(dir, uri)).and_then(|m| m.modified()).ok()?.elapsed().ok()
}

pub fn read_list_cache(dir: &std::path::Path, uri: &str) -> Option<Vec<Row>> {
let text = std::fs::read_to_string(list_path(dir, uri)).ok()?;
let mut lines = text.lines();
Expand Down Expand Up @@ -995,6 +1034,20 @@ mod tests {
assert!(station_uris(&Value::Null).is_empty());
}

#[test]
fn reads_artist_overview() {
let v: Value = serde_json::from_str(r#"{
"relatedContent": {"relatedArtists": {"items": [
{"uri": "spotify:artist:a", "profile": {"name": "Nile Rodgers"}}, {"profile": {"name": "no uri"}}]}},
"discography": {"topTracks": {"items": [
{"track": {"uri": "spotify:track:1", "playcount": "5"}}, {"track": {"uri": "spotify:episode:2"}}]}}
}"#).unwrap();
let (related, top) = overview_of(&v);
assert_eq!(related, [("spotify:artist:a".to_string(), "Nile Rodgers".to_string())]);
assert_eq!(top, ["spotify:track:1"]);
assert_eq!(overview_of(&Value::Null), (Vec::new(), Vec::new()));
}

#[test]
fn album_rows_show_year_and_type() {
use librespot_protocol::metadata::{Date, album::Type};
Expand Down
75 changes: 69 additions & 6 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ use crate::{
audio::{AudioSettings, BANDS, Eq},
auth::WebToken,
engine::{Engine, EngineEvent},
discover::{self, FOR_YOU},
mpris::Remote,
};

Expand Down Expand Up @@ -67,8 +68,10 @@ fn weave(order: &mut Vec<usize>, from: usize, mut recs: std::ops::Range<usize>)
}
}

/// Sidebar entries above the playlists: Liked Songs, Albums, Artists, Queue, Search.
const FIXED_SIDE: usize = 5;
/// Sidebar entries above the playlists: Liked Songs, Albums, Artists, For You, Queue, Search.
const FIXED_SIDE: usize = 6;
/// For You is worked out again when it's opened this long after the last time (or on `R`).
const FOR_YOU_FRESH: Duration = Duration::from_secs(12 * 3600);

#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Focus {
Expand Down Expand Up @@ -198,6 +201,7 @@ fn sorted(sort: Sort, uri: &str, rows: Rows) -> (Rows, Option<&'static str>) {
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum SideKind {
Liked,
ForYou,
Queue,
Search,
Playlist,
Expand Down Expand Up @@ -274,6 +278,12 @@ pub struct App {
pub soloist_missing: Option<String>,
/// Where the playlist list is cached so the sidebar fills instantly on start.
pub cache_dir: Option<std::path::PathBuf>,
/// Where settings, the play log and "not interested" live.
pub data_dir: Option<std::path::PathBuf>,
/// Songs never to suggest again (`X`).
pub not_interested: HashSet<String>,
/// The song whose play is already in the log (it's logged once it has played 30 s).
logged: Option<String>,
/// Tag of a newer trill release, shown in the title bar.
pub update: Option<String>,
/// EQ panel open, with this band selected.
Expand Down Expand Up @@ -375,6 +385,10 @@ pub struct App {

const SEEK_MS: u32 = 10_000;

fn for_you_status(n: usize) -> String {
format!("For You: {n} songs from what you play, worked out here. X: not interested · R: new picks")
}

fn playlists_status(n: usize) -> String {
format!("{n} playlists. Tab to switch panes, / to search, ? for keys.")
}
Expand All @@ -398,6 +412,7 @@ impl App {
SideItem { name: "♥ Liked Songs".into(), uri: format!("spotify:user:{user}:collection"), kind: SideKind::Liked, editable: false, pinned: false },
SideItem { name: "◉ Albums".into(), uri: api::SAVED_ALBUMS.into(), kind: SideKind::Liked, editable: false, pinned: false },
SideItem { name: "◈ Artists".into(), uri: api::FOLLOWED_ARTISTS.into(), kind: SideKind::Liked, editable: false, pinned: false },
SideItem { name: "✦ For You".into(), uri: FOR_YOU.into(), kind: SideKind::ForYou, editable: false, pinned: false },
SideItem { name: "≡ Queue".into(), uri: "trill:queue".into(), kind: SideKind::Queue, editable: false, pinned: false },
SideItem { name: "⌕ Search".into(), uri: "trill:search".into(), kind: SideKind::Search, editable: false, pinned: false },
];
Expand Down Expand Up @@ -426,6 +441,9 @@ impl App {
eq,
eq_allowed: true,
cache_dir: None,
data_dir: None,
not_interested: HashSet::new(),
logged: None,
update: None,
eq_panel: None,
help_open: false,
Expand Down Expand Up @@ -524,7 +542,20 @@ impl App {
self.back.remove(0);
}
}
if !force && let Some(rows) = self.cache.get(&uri).cloned() {
if !force && uri != FOR_YOU && let Some(rows) = self.cache.get(&uri).cloned() {
self.show(uri, title, rows);
return;
}
// For You from disk, as it was last worked out, unless that was a while ago
if !force
&& uri == FOR_YOU
&& let Some(dir) = self.cache_dir.as_deref()
&& api::list_age(dir, &uri).is_some_and(|a| a < FOR_YOU_FRESH)
&& let Some(rows) = api::read_list_cache(dir, &uri)
{
let rows: Rows = Arc::new(rows);
self.cache.insert(uri.clone(), rows.clone()); // so `X` can take songs out of it
self.status = for_you_status(rows.len());
self.show(uri, title, rows);
return;
}
Expand Down Expand Up @@ -556,13 +587,30 @@ impl App {
/// Load a list; `known` rows (an older copy) spare re-fetching their songs' details.
fn fetch_rows(&self, uri: String, title: String, known: Rows) {
let (s, tx) = (self.session.clone(), self.tx.clone());
if uri == FOR_YOU {
let Some(dir) = self.data_dir.clone() else { return };
let liked = self.cache.get(&self.liked_uri()).cloned().or_else(|| {
self.cache_dir.as_deref().and_then(|d| api::read_list_cache(d, &self.liked_uri())).map(Arc::new)
});
let exclude: HashSet<String> = self.liked.iter().chain(&self.not_interested).cloned().collect();
tokio::spawn(async move {
let rows = discover::for_you(&s, &dir, liked.unwrap_or_default(), exclude).await;
let _ = tx.send(Msg::Rows { uri, title, rows });
});
return;
}
tokio::spawn(async move {
let rows = api::context_rows(&s, &uri, &known).await;
let _ = tx.send(Msg::Rows { uri, title, rows });
});
}

fn show(&mut self, uri: String, title: String, rows: Rows) {
// another list still loading mustn't replace this one when it arrives
if self.pending.as_deref() != Some(uri.as_str()) {
self.pending = None;
self.loading = false;
}
let (all, sort) = sorted(self.sort_for(&uri), &uri, rows);
// a fresh copy of the list on screen keeps what it's narrowed to
let find = if self.view.uri == uri { std::mem::take(&mut self.view.find) } else { String::new() };
Expand Down Expand Up @@ -669,7 +717,7 @@ impl App {
let rows = self.search_rows.clone();
self.show("trill:search".into(), self.search_title.clone(), rows);
}
SideKind::Liked | SideKind::Playlist => self.open(uri, name, false, false),
SideKind::Liked | SideKind::Playlist | SideKind::ForYou => self.open(uri, name, false, false),
}
// Picking "Search" means "I want to search": open the search box right away.
self.focus = if kind == SideKind::Search { Focus::Input } else { Focus::Main };
Expand Down Expand Up @@ -737,7 +785,7 @@ impl App {
crate::trim_heap();
}
if is_current {
self.status = format!("{title}: {}", count(&rows));
self.status = if uri == FOR_YOU { for_you_status(rows.len()) } else { format!("{title}: {}", count(&rows)) };
self.show(uri, title, rows);
} else if changed && self.view.uri == uri {
// The copy on screen came from disk; this is the fresh one.
Expand Down Expand Up @@ -1008,6 +1056,20 @@ impl App {
/// Seek again while Soloist plays well before the resume point (see `pending_seek`).
/// Runs on each position report and each second: after a restart Soloist first sends
/// the old session's snapshot, then starts our track from 0 and may report nothing more.
/// Log the song playing once it has played 30 s (again after it starts over), for For You.
pub fn note_play(&mut self) {
let Some(now) = self.now.as_ref() else { return };
let pos = self.position_ms();
if pos >= 30_000 && self.logged.as_deref() != Some(now.uri.as_str()) {
if let Some(dir) = self.data_dir.as_deref() {
discover::log_play(dir, now);
}
self.logged = Some(now.uri.clone());
} else if pos < 5_000 && self.logged.as_deref() == Some(now.uri.as_str()) {
self.logged = None; // repeat one, or played again: counts again after 30 s
}
}

pub fn check_resume(&mut self) {
let Some((want, until, last)) = self.pending_seek else { return };
if Instant::now() > until {
Expand Down Expand Up @@ -1772,6 +1834,7 @@ impl App {
self.input = self.view.find.clone();
}
KeyCode::Char('z') => self.cycle_sleep(),
KeyCode::Char('X') => self.mark_not_interested(),
KeyCode::Char(' ') => self.toggle(),
KeyCode::Char('n') => self.next(false),
KeyCode::Char('p') => self.prev(),
Expand Down Expand Up @@ -1820,7 +1883,7 @@ impl App {
if self.focus == Focus::Side || self.view.uri.is_empty() {
self.status = "Reloading playlists…".into();
self.load_playlists();
} else if !self.view.uri.starts_with("trill:") || self.view.uri.starts_with("trill:collection:") {
} else if !self.view.uri.starts_with("trill:") || self.view.uri.starts_with("trill:collection:") || self.view.uri == FOR_YOU {
let (u, t) = (self.view.uri.clone(), self.view.title.clone());
self.open(u, t, false, true);
}
Expand Down
40 changes: 39 additions & 1 deletion src/app/extras.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ use ratatui_image::{FilterType, Resize, picker::Picker, protocol::Protocol};
use super::{App, Focus, Msg, SideKind};
use crate::{
api::{self, Kind, Row},
discover::{self, FOR_YOU},
library::{self, Lyrics},
theme,
};
Expand Down Expand Up @@ -484,6 +485,40 @@ impl App {
});
}

/// `X` on a For You song or a ✦ smart-shuffle song: never suggest it again (kept in
/// `not_interested`). It leaves For You at once; a ✦ song leaves the queue (and is skipped
/// if it's playing).
pub(super) fn mark_not_interested(&mut self) {
let row = match self.focus {
Focus::Main if !self.lyrics_open => self.view.state.selected().and_then(|i| self.view.rows.get(i)).cloned(),
_ => None,
}
.filter(|r| r.kind == Kind::Track && (self.view.uri == FOR_YOU || self.is_rec(&r.uri)))
.or_else(|| self.now.clone().filter(|r| self.is_rec(&r.uri)));
let Some(row) = row else {
self.status = "X is for suggestions: a song in For You, or a ✦ song from smart shuffle.".into();
return;
};
if self.not_interested.insert(row.uri.clone())
&& let Some(d) = self.data_dir.as_deref()
{
discover::add_not_interested(d, &row.uri);
}
self.edit_cached(FOR_YOU, |v| v.retain(|r| r.uri != row.uri));
if let Some(i) = self.recs.iter().position(|r| r.uri == row.uri) {
let idx = self.ctx.len() + i;
if self.now.as_ref().is_some_and(|n| n.uri == row.uri) {
self.next(false);
}
// later in the play order: take it out (the entry at the cursor is what plays now)
if let Some(p) = self.order.iter().position(|&o| o == idx).filter(|&p| p > self.cursor) {
self.order.remove(p);
}
self.refresh_queue_view();
}
self.status = format!("Not interested in “{}”: it won't be suggested again.", row.title);
}

// ---------------------------------------------------------------- lyrics

pub(super) fn toggle_lyrics(&mut self) {
Expand Down Expand Up @@ -776,7 +811,10 @@ impl App {
}
let have: HashSet<&str> = self.ctx.iter().map(|r| r.uri.as_str()).collect();
let mut seen = HashSet::new();
let recs: Vec<Row> = rows.into_iter().filter(|r| !have.contains(r.uri.as_str()) && seen.insert(r.uri.clone())).collect();
let recs: Vec<Row> = rows
.into_iter()
.filter(|r| !have.contains(r.uri.as_str()) && !self.not_interested.contains(&r.uri) && seen.insert(r.uri.clone()))
.collect();
self.recs = recs;
self.weave();
self.refresh_queue_view();
Expand Down
Loading
Loading