diff --git a/.sqlx/query-31bb71a0aa408eef106d263020d928b91514677637f585cdc53344b86c138f7a.json b/.sqlx/query-31bb71a0aa408eef106d263020d928b91514677637f585cdc53344b86c138f7a.json new file mode 100644 index 0000000..1c82131 --- /dev/null +++ b/.sqlx/query-31bb71a0aa408eef106d263020d928b91514677637f585cdc53344b86c138f7a.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n DELETE FROM \"mix_suggestion\"\n WHERE rule_id = $1 AND status = 'expired' AND expired_at < NOW() - make_interval(days => $2)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "31bb71a0aa408eef106d263020d928b91514677637f585cdc53344b86c138f7a" +} diff --git a/.sqlx/query-8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7.json b/.sqlx/query-8cdf21728821fa2672912ea9c151f7138c09e3ef76ec38465c94a389adcf2c5c.json similarity index 83% rename from .sqlx/query-8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7.json rename to .sqlx/query-8cdf21728821fa2672912ea9c151f7138c09e3ef76ec38465c94a389adcf2c5c.json index 5dc751b..fd4bbff 100644 --- a/.sqlx/query-8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7.json +++ b/.sqlx/query-8cdf21728821fa2672912ea9c151f7138c09e3ef76ec38465c94a389adcf2c5c.json @@ -1,6 +1,6 @@ { "db_name": "PostgreSQL", - "query": "\n SELECT * FROM \"mix_suggestion\"\n WHERE mix_id = $1 AND status <> 'dismissed'\n ORDER BY score DESC\n ", + "query": "\n SELECT * FROM \"mix_suggestion\"\n WHERE mix_id = $1 AND status IN ('new', 'liked')\n ORDER BY score DESC\n ", "describe": { "columns": [ { @@ -62,6 +62,11 @@ "ordinal": 11, "name": "created_at", "type_info": "Timestamptz" + }, + { + "ordinal": 12, + "name": "expired_at", + "type_info": "Timestamptz" } ], "parameters": { @@ -81,8 +86,9 @@ false, false, true, - false + false, + true ] }, - "hash": "8b606b7e728f8e0d6505a7246f785dab6370f62fd442ede54a5e79c075bae8b7" + "hash": "8cdf21728821fa2672912ea9c151f7138c09e3ef76ec38465c94a389adcf2c5c" } diff --git a/.sqlx/query-ca7e7a1692e7a2510b792bede575f218f62438ee3d47728caac0dc07841fd49d.json b/.sqlx/query-ca7e7a1692e7a2510b792bede575f218f62438ee3d47728caac0dc07841fd49d.json new file mode 100644 index 0000000..6e84621 --- /dev/null +++ b/.sqlx/query-ca7e7a1692e7a2510b792bede575f218f62438ee3d47728caac0dc07841fd49d.json @@ -0,0 +1,15 @@ +{ + "db_name": "PostgreSQL", + "query": "\n UPDATE \"mix_suggestion\" SET status = 'expired', expired_at = NOW()\n WHERE rule_id = $1 AND status = 'new' AND created_at < NOW() - make_interval(days => $2)\n ", + "describe": { + "columns": [], + "parameters": { + "Left": [ + "Uuid", + "Int4" + ] + }, + "nullable": [] + }, + "hash": "ca7e7a1692e7a2510b792bede575f218f62438ee3d47728caac0dc07841fd49d" +} diff --git a/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json b/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json index b8f0a87..d93e1ba 100644 --- a/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json +++ b/.sqlx/query-d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76.json @@ -62,6 +62,11 @@ "ordinal": 11, "name": "created_at", "type_info": "Timestamptz" + }, + { + "ordinal": 12, + "name": "expired_at", + "type_info": "Timestamptz" } ], "parameters": { @@ -81,7 +86,8 @@ false, false, true, - false + false, + true ] }, "hash": "d46de753581651896a2b6e9385d3821d22c323ca30f73f37ca845e95472fcc76" diff --git a/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json b/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json index c2f3ab2..936d4b8 100644 --- a/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json +++ b/.sqlx/query-d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9.json @@ -62,6 +62,11 @@ "ordinal": 11, "name": "created_at", "type_info": "Timestamptz" + }, + { + "ordinal": 12, + "name": "expired_at", + "type_info": "Timestamptz" } ], "parameters": { @@ -81,7 +86,8 @@ false, false, true, - false + false, + true ] }, "hash": "d56f95b38163d21d48148082557bbe4afc99732fbf2eb73ac1fee91c761387e9" diff --git a/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json b/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json index 474f978..184a90c 100644 --- a/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json +++ b/.sqlx/query-e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b.json @@ -62,6 +62,11 @@ "ordinal": 11, "name": "created_at", "type_info": "Timestamptz" + }, + { + "ordinal": 12, + "name": "expired_at", + "type_info": "Timestamptz" } ], "parameters": { @@ -82,7 +87,8 @@ false, false, true, - false + false, + true ] }, "hash": "e5b622cf8653fb19c5c1728c31af759a9acbc46adcbdacaff93800552ac5426b" diff --git a/README.md b/README.md index 8862d5a..ce78261 100644 --- a/README.md +++ b/README.md @@ -188,7 +188,11 @@ Each time the mixes are rebuilt, playlistd also looks for new songs for each mix Listenbrainz user it's for. Every candidate's MusicBrainz genres are compared with each mix's, and it's suggested in the mix -it fits best (if it fits well enough), skipping songs already in your library. +it fits best (if it fits well enough), skipping songs already in your library. Each mix's +suggestions are picked at random from its best-fitting candidates (three times as many as +`discovery_count`), weighted by how well they fit, so they vary from one rebuild to the next. +A suggestion that's been in a mix for a week without being liked, hidden or listened to expires, +and isn't suggested again for 60 days. In the UI, songs from your library stream from Subsonic. New songs are found on YouTube with [yt-dlp](https://github.com/yt-dlp/yt-dlp) on the server (keep it up to date: YouTube changes can @@ -200,6 +204,14 @@ new song to keep it in "Liked new songs", or hide it so it isn't suggested again Mobile browsers pause embedded YouTube videos when the screen locks or the tab is in the background, so new songs only play while the UI is open. +What you play in the UI is scrobbled, following Listenbrainz's rule: "now playing" when a song +starts, and a listen once you've played half of it or 4 minutes, whichever comes first (skipping +ahead doesn't count). Library songs are scrobbled through Subsonic, which keeps their play counts +and passes them on to whatever scrobbling the Subsonic user has set up (in Navidrome, linking +Listenbrainz or Last.fm in its personal settings). New songs from YouTube go straight to +Listenbrainz with `listenbrainz.token`, so without a token they aren't scrobbled. Set +`discover.scrobble` (or `DISCOVER_SCROBBLE`) to `false` to turn scrobbling off. + "Play mix" plays a mix's new songs in random order with songs you already know (the songs in the mix you've played recently) mixed in evenly, so that `familiar_ratio` of what you hear is familiar. If a mix has too few known songs to keep that ratio, all of them are used. @@ -268,6 +280,7 @@ The UI uses these endpoints under `/api/discover`: | `GET /cover/` | Library cover art from Subsonic | | `GET /youtube/?refresh=` | YouTube videos for a suggestion, best first (`refresh` searches again) | | `PUT /youtube/` | Remember the video that played (`video_id`) | +| `POST /scrobble` | Scrobble a song played in the UI (`source`: `library` or `youtube`, `id`, `submission`, `started_at`, `duration`, `video_id`) | and these under `/api/tracked` for tracked playlists: diff --git a/discover/src/api.ts b/discover/src/api.ts index 1c67d5b..7b72b7e 100644 --- a/discover/src/api.ts +++ b/discover/src/api.ts @@ -49,6 +49,18 @@ export type Suggestion = { youtube_id: string | null; }; +export type Listen = { + source: "library" | "youtube"; + /** Subsonic song id, or suggestion id */ + id: string; + submission: boolean; + /** Unix seconds */ + started_at: number; + /** Seconds */ + duration?: number; + video_id?: string; +}; + export type MixDetail = MixSummary & { songs: Song[]; /** Songs in `songs` the user played recently */ @@ -99,6 +111,8 @@ export const api = { /** Videos to play a suggestion with, best first. `refresh` searches again. */ youtubeVideos: (suggestionId: string, refresh = false) => request<{ video_ids: string[]; cached: boolean }>(`/youtube/${suggestionId}?refresh=${refresh}`), + /** Record a song played here (`submission: false` when it starts, true once listened to) */ + scrobble: (listen: Listen) => request("/scrobble", json("POST", listen)), /** The video that played, when it wasn't the first one */ setYoutubeVideo: (suggestionId: string, videoId: string) => request(`/youtube/${suggestionId}`, json("PUT", { video_id: videoId })), diff --git a/discover/src/queue.ts b/discover/src/queue.ts index 44a83e8..81c6076 100644 --- a/discover/src/queue.ts +++ b/discover/src/queue.ts @@ -5,6 +5,8 @@ export type QueueItem = { source: "library" | "youtube"; /** Audio to stream, for library songs. YouTube ones play from `suggestionId`. */ src: string; + /** The library song's Subsonic id */ + songId?: string; title: string; artist: string; album?: string | null; @@ -16,6 +18,7 @@ export const fromSong = (song: Song): QueueItem => ({ key: `song:${song.id}`, source: "library", src: streamUrl(song.id), + songId: song.id, title: song.title, artist: song.artist, album: song.album, diff --git a/discover/src/usePlayer.ts b/discover/src/usePlayer.ts index 6708eea..4294c2e 100644 --- a/discover/src/usePlayer.ts +++ b/discover/src/usePlayer.ts @@ -218,6 +218,58 @@ export function usePlayer(onError: (item: QueueItem) => void) { return () => window.clearInterval(t); }, [onYouTube, status]); + // ---------- scrobbling ---------- + // "Now playing" when an item starts, and a listen once half of it, or 4 minutes, has been + // played (Listenbrainz's rule). Seeking doesn't count as listening. + + const listen = useRef<{ + key: string; + startedAt: number; + /** Seconds actually played */ + played: number; + last: number; + submitted: boolean; + } | null>(null); + + const scrobble = useCallback( + (item: QueueItem, submission: boolean, startedAt: number, duration: number, video: string | null) => { + const id = item.source === "youtube" ? item.suggestionId : item.songId; + if (!id) return; + void api + .scrobble({ + source: item.source, + id, + submission, + started_at: startedAt, + duration: duration || undefined, + video_id: item.source === "youtube" ? video ?? undefined : undefined, + }) + .catch(() => undefined); + }, + [], + ); + + useEffect(() => { + if (status !== "playing" || !current || listen.current?.key === current.key) return; + const startedAt = Math.floor(Date.now() / 1000); + listen.current = { key: current.key, startedAt, played: 0, last: time, submitted: false }; + scrobble(current, false, startedAt, duration, videoId); + }, [status, current, time, duration, videoId, scrobble]); + + useEffect(() => { + const l = listen.current; + if (!l || !current || l.key !== current.key) return; + const delta = time - l.last; + l.last = time; + // (a jump is a seek, or the time going back to 0 for a new item) + if (status !== "playing" || delta <= 0 || delta > 2) return; + l.played += delta; + if (!l.submitted && duration > 0 && l.played >= Math.min(duration / 2, 240)) { + l.submitted = true; + scrobble(current, true, l.startedAt, duration, videoId); + } + }, [time]); // eslint-disable-line react-hooks/exhaustive-deps + // ---------- loading items ---------- useEffect(() => { @@ -233,6 +285,8 @@ export function usePlayer(onError: (item: QueueItem) => void) { el.pause(); el.removeAttribute("src"); el.load(); + // the previous YouTube song would play on while this one is looked up + youtube.current?.stop(); attempt.current = null; void playYouTube(current.suggestionId, load, false); } else { diff --git a/etc/playlistd/playlistd.toml b/etc/playlistd/playlistd.toml index 7f53733..4a1557d 100644 --- a/etc/playlistd/playlistd.toml +++ b/etc/playlistd/playlistd.toml @@ -21,7 +21,8 @@ url = "postgres:///navidrome-playlists" [listenbrainz] # Your Listenbrainz user token (listenbrainz.org/settings). Optional: lets the discover UI -# find new songs for each mix's genres with LB Radio, on top of your recommendations. +# find new songs for each mix's genres with LB Radio, on top of your recommendations, and +# scrobble the new songs it plays from YouTube to this account. # Used for every mix, whichever Listenbrainz user it's for # token = "" @@ -30,6 +31,10 @@ url = "postgres:///navidrome-playlists" ui = "/usr/share/playlistd/discover" # yt-dlp binary used to find suggested songs that aren't in your library on YouTube # ytdlp = "yt-dlp" +# Scrobble what's played in the discover UI (default true): library songs through Subsonic, +# which keeps play counts and passes them on to its Listenbrainz/Last.fm, and new songs played +# from YouTube straight to Listenbrainz, with listenbrainz.token +# scrobble = true # Format to ask Subsonic to stream in ("raw" = no transcoding), e.g. "mp3" if your # library has files browsers can't play # format = "raw" diff --git a/migrations/20261124120000_expire_suggestions.sql b/migrations/20261124120000_expire_suggestions.sql new file mode 100644 index 0000000..779ea70 --- /dev/null +++ b/migrations/20261124120000_expire_suggestions.sql @@ -0,0 +1,6 @@ +-- Suggestions left alone for a while expire (status 'expired'), and are kept out of the mixes +-- until some time after `expired_at`, so the suggestions change from one rebuild to the next +ALTER TABLE "mix_suggestion" + ADD COLUMN expired_at TIMESTAMPTZ; + +COMMENT ON COLUMN "mix_suggestion".status IS 'new, liked, dismissed or expired'; diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs index 140d880..272058b 100644 --- a/src/daemon/cluster_mixes.rs +++ b/src/daemon/cluster_mixes.rs @@ -294,6 +294,11 @@ pub async fn build_mixes( Ok(()) } +/// Days a suggestion stays in its mix without being liked, dismissed or listened to +const EXPIRE_AFTER_DAYS: i32 = 7; +/// Days an expired suggestion is kept out of the mixes, before it can be suggested again +const EXPIRED_FOR_DAYS: i32 = 60; + async fn save_suggestions( media_client: &Subsonic, rule: &ClusterMixRule, @@ -301,7 +306,31 @@ async fn save_suggestions( recently_played: &RecentlyPlayed, database: &PgPool, ) -> Result<(), Box> { - // liked and dismissed suggestions stay as they are + // suggestions that have been there a while go, to make room for others; ones that expired + // long enough ago can come back (as new suggestions) + sqlx::query!( + r#" + DELETE FROM "mix_suggestion" + WHERE rule_id = $1 AND status = 'expired' AND expired_at < NOW() - make_interval(days => $2) + "#, + rule.id, + EXPIRED_FOR_DAYS, + ) + .execute(database) + .await?; + let expired = sqlx::query!( + r#" + UPDATE "mix_suggestion" SET status = 'expired', expired_at = NOW() + WHERE rule_id = $1 AND status = 'new' AND created_at < NOW() - make_interval(days => $2) + "#, + rule.id, + EXPIRE_AFTER_DAYS, + ) + .execute(database) + .await? + .rows_affected(); + + // liked, dismissed and expired suggestions stay as they are let exclude: HashSet = sqlx::query_scalar!( r#"SELECT recording_mbid FROM "mix_suggestion" WHERE rule_id = $1 AND status <> 'new'"#, rule.id @@ -359,9 +388,10 @@ async fn save_suggestions( .await?; log::info!( - "{}: {} new songs suggested", + "{}: {} new songs suggested, {} expired", rule.tracking_user, - suggestions.len() + suggestions.len(), + expired ); Ok(()) } diff --git a/src/discover.rs b/src/discover.rs index 7a08ac6..2aabbff 100644 --- a/src/discover.rs +++ b/src/discover.rs @@ -5,11 +5,15 @@ //! `listenbrainz.token` is configured, an LB Radio prompt built from each mix's //! top genres. Every candidate's MusicBrainz genres are compared with each //! mix's genre profile (cosine similarity) and it's assigned to the mix it fits -//! best. Songs already in the library, or played recently, are skipped. +//! best. Each mix's suggestions are a random sample of its best-fitting candidates, weighted +//! by fit, so they change from one rebuild to the next. Songs already in the library, or +//! played recently, are skipped. use crate::listenbrainz::{self, RecordingInfo}; use crate::mix::{name_key, normalize, RecentlyPlayed}; use crate::subsonic::Subsonic; +use rand::rngs::StdRng; +use rand::{Rng, SeedableRng}; use std::collections::{HashMap, HashSet}; use uuid::Uuid; @@ -21,6 +25,8 @@ const PER_ARTIST: usize = 2; const RECOMMENDATIONS: usize = 1000; /// Genres per LB Radio prompt const RADIO_GENRES: usize = 3; +/// Each mix's suggestions are sampled from its best `SAMPLE_FROM` × `per_mix` candidates +const SAMPLE_FROM: usize = 3; pub struct MixTarget { pub mix_id: Uuid, @@ -35,6 +41,24 @@ pub struct Suggestion { pub score: f64, } +/// The order to take a mix's candidates in, given them sorted best first: a weighted random +/// sample of the best `per_mix * SAMPLE_FROM`, then the rest in order of fit, in case too many +/// of those are skipped (e.g. as they're in the library) +fn sample_order(mut found: Vec<(f64, T)>, per_mix: usize, rng: &mut impl Rng) -> Vec<(f64, T)> { + let rest = found.split_off(found.len().min(per_mix * SAMPLE_FROM)); + // Efraimidis-Spirakis: sorting by u^(1/w) samples without replacement, weighted by w (the + // square of the fit, as in the mixes, to favour the best fits more strongly) + let mut keyed: Vec<(f64, (f64, T))> = found + .into_iter() + .map(|(score, item)| { + let w = (score * score).max(f64::MIN_POSITIVE); + (rng.gen::().powf(1.0 / w), (score, item)) + }) + .collect(); + keyed.sort_by(|a, b| b.0.total_cmp(&a.0)); + keyed.into_iter().map(|(_, item)| item).chain(rest).collect() +} + /// Cosine similarity between a recording's genres and a mix profile fn fit(genres: &HashMap, profile: &HashMap, profile_norm: f64) -> f64 { let (mut dot, mut norm) = (0.0, 0.0); @@ -133,12 +157,18 @@ pub async fn suggest( // ---- pick the best per mix, skipping songs already in the library ---- let mut suggestions = vec![]; let mut seen_names: HashSet = HashSet::new(); + let mut rng = StdRng::from_entropy(); for (target, mut found) in targets.iter().zip(per_target) { found.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.cmp(b.1))); + let found = sample_order( + found.into_iter().map(|(score, mbid, info)| (score, (mbid, info))).collect(), + per_mix, + &mut rng, + ); let mut artists: HashMap = HashMap::new(); let mut taken = 0; - for (score, mbid, info) in found { + for (score, (mbid, info)) in found { if taken >= per_mix { break; } @@ -209,4 +239,26 @@ mod tests { assert_eq!(fit(&folk, &profile, norm), 0.0); assert_eq!(fit(&HashMap::new(), &profile, norm), 0.0); } + + #[test] + fn sample_order_samples_from_the_best() { + // best first, as the caller sorts them + let found: Vec<(f64, usize)> = (0..20).map(|i| (1.0 - i as f64 * 0.04, i)).collect(); + let mut orders = HashSet::new(); + for seed in 0..20 { + let order: Vec = sample_order(found.clone(), 2, &mut StdRng::seed_from_u64(seed)) + .into_iter() + .map(|(_, i)| i) + .collect(); + // the best 6 come first, in some order, then the rest as they were + let mut head = order[..6].to_vec(); + head.sort(); + assert_eq!(head, (0..6).collect::>()); + assert_eq!(order[6..], (6..20).collect::>()); + orders.insert(order[..2].to_vec()); + } + // different picks from one run to the next + assert!(orders.len() > 1); + assert!(sample_order(Vec::<(f64, usize)>::new(), 5, &mut StdRng::seed_from_u64(0)).is_empty()); + } } diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index 0c679db..d34dcfa 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -531,3 +531,65 @@ pub async fn radio(prompt: &str, mode: &str, token: &str) -> Result, }) .collect()) } + +/// A listen to submit, for a song played from outside the library (library songs are scrobbled +/// through Subsonic, which passes them on to Listenbrainz itself) +pub struct NewListen { + pub artist: String, + pub title: String, + pub release: Option, + pub recording_mbid: Option, + pub duration_ms: Option, + /// e.g. "youtube.com" + pub music_service: &'static str, + /// Where it was played from, e.g. the YouTube video + pub origin_url: Option, +} + +/// Submit a listen. `listened_at` (a unix timestamp) submits a finished listen; without it, the +/// song is marked as playing now. +pub async fn submit_listen( + listen: &NewListen, + listened_at: Option, + token: &str, +) -> Result<(), reqwest::Error> { + let mut additional_info = serde_json::json!({ + "media_player": "playlistd", + "submission_client": "playlistd", + "submission_client_version": env!("CARGO_PKG_VERSION"), + "music_service": listen.music_service, + }); + let info = additional_info.as_object_mut().expect("an object"); + if let Some(mbid) = &listen.recording_mbid { + info.insert("recording_mbid".into(), mbid.clone().into()); + } + if let Some(duration) = listen.duration_ms { + info.insert("duration_ms".into(), duration.into()); + } + if let Some(url) = &listen.origin_url { + info.insert("origin_url".into(), url.clone().into()); + } + + let mut track_metadata = serde_json::json!({ + "artist_name": listen.artist, + "track_name": listen.title, + "additional_info": additional_info, + }); + if let Some(release) = &listen.release { + track_metadata["release_name"] = release.clone().into(); + } + let mut payload = serde_json::json!({ "track_metadata": track_metadata }); + if let Some(at) = listened_at { + payload["listened_at"] = at.into(); + } + + let request = reqwest::Client::new() + .post(format!("{}/submit-listens", BASE)) + .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)) + .json(&serde_json::json!({ + "listen_type": if listened_at.is_some() { "single" } else { "playing_now" }, + "payload": [payload], + })); + send_json::(request).await?; + Ok(()) +} diff --git a/src/models.rs b/src/models.rs index 0204099..d670de8 100644 --- a/src/models.rs +++ b/src/models.rs @@ -248,4 +248,8 @@ pub struct MixSuggestion { pub status: String, pub youtube_id: Option, pub created_at: DateTime, + /// When it expired, for status "expired" (only used in SQL) + #[serde(skip)] + #[allow(dead_code)] + pub expired_at: Option>, } diff --git a/src/subsonic.rs b/src/subsonic.rs index 4aca222..70a5b37 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -385,6 +385,21 @@ impl Subsonic { .await } + /// Report a song as playing now, or (`submission`) as played, from `time` (unix ms). The + /// server keeps play counts and passes it on to the user's scrobbling services. + pub async fn scrobble(&self, id: &str, submission: bool, time: i64) -> Result<(), SubsonicError> { + self.request::( + "scrobble", + &[ + ("id", id.to_string()), + ("submission", submission.to_string()), + ("time", time.to_string()), + ], + ) + .await?; + Ok(()) + } + pub async fn delete_playlist(&self, playlist_id: &str) -> Result<(), SubsonicError> { self.request::("deletePlaylist", &[("id", playlist_id.to_string())]) .await?; diff --git a/src/web.rs b/src/web.rs index 2ee3219..5df2879 100644 --- a/src/web.rs +++ b/src/web.rs @@ -34,7 +34,8 @@ pub fn routes() -> Vec { stream, cover, youtube, - set_youtube_video + set_youtube_video, + scrobble ] } @@ -280,7 +281,7 @@ async fn mix( MixSuggestion, r#" SELECT * FROM "mix_suggestion" - WHERE mix_id = $1 AND status <> 'dismissed' + WHERE mix_id = $1 AND status IN ('new', 'liked') ORDER BY score DESC "#, id @@ -575,3 +576,112 @@ async fn set_youtube_video( Err(e) => db_error(e), } } + +#[derive(Deserialize)] +#[serde(rename_all = "lowercase")] +enum ListenSource { + /// A library song, by its Subsonic id + Library, + /// A suggested song played from YouTube, by the suggestion's id + YouTube, +} + +#[derive(Deserialize)] +struct Listen { + source: ListenSource, + id: String, + /// false: the song has just started. true: it's been listened to (half of it, or 4 minutes). + submission: bool, + /// When it started playing (unix seconds) + started_at: i64, + /// Seconds + duration: Option, + /// The YouTube video played + video_id: Option, +} + +/// Whether to scrobble what the UI plays: `discover.scrobble`, on unless set to false +fn scrobbling() -> bool { + crate::CONFIG + .get() + .and_then(|c| c.get::("discover.scrobble").ok()) + .unwrap_or(true) +} + +/// Record a song played in the UI: library songs through Subsonic (which keeps play counts and +/// passes them on to the user's Listenbrainz or Last.fm), YouTube ones straight to Listenbrainz +/// with `listenbrainz.token` +#[post("/scrobble", data = "")] +async fn scrobble( + _user: User, + listen: Json, + pool: &State, + media_client: &State>, +) -> Status { + if !scrobbling() { + return Status::NoContent; + } + match listen.source { + ListenSource::Library => { + match media_client + .scrobble(&listen.id, listen.submission, listen.started_at * 1000) + .await + { + Ok(()) => Status::NoContent, + Err(e) => { + log::warn!("Couldn't scrobble song {}: {}", listen.id, e); + Status::BadGateway + } + } + } + ListenSource::YouTube => { + let Some(token) = crate::listenbrainz::token() else { + return Status::NoContent; + }; + let Ok(id) = parse_id(&listen.id) else { + return Status::NotFound; + }; + let suggestion = match sqlx::query_as!( + MixSuggestion, + r#"SELECT * FROM "mix_suggestion" WHERE id = $1"#, + id + ) + .fetch_one(pool.inner()) + .await + { + Ok(s) => s, + Err(e) => return db_error(e), + }; + let video_id = listen + .video_id + .as_ref() + .filter(|v| valid_video_id(v)) + .or(suggestion.youtube_id.as_ref()); + let new_listen = crate::listenbrainz::NewListen { + artist: suggestion.artist, + title: suggestion.title, + release: suggestion.release, + recording_mbid: Some(suggestion.recording_mbid).filter(|m| !m.is_empty()), + duration_ms: listen + .duration + .filter(|d| d.is_finite() && *d > 0.0) + .map(|d| (d * 1000.0).round() as u64), + music_service: "youtube.com", + origin_url: video_id.map(|v| format!("https://www.youtube.com/watch?v={}", v)), + }; + let listened_at = listen.submission.then_some(listen.started_at); + match crate::listenbrainz::submit_listen(&new_listen, listened_at, &token).await { + Ok(()) => Status::NoContent, + Err(e) => { + log::warn!( + "Couldn't submit a listen of {} - {}: {}", + new_listen.artist, + new_listen.title, + e + ); + Status::BadGateway + } + } + } + } +}