Scrobble plays from the UI, and vary suggestions between rebuilds
Scrobbling: the UI reports "now playing" when a song starts, and a listen once half of it (or 4 minutes) has actually been played. Library songs go through Subsonic's scrobble endpoint, which keeps play counts and passes them on to the user's Listenbrainz/Last.fm; YouTube songs go straight to Listenbrainz with listenbrainz.token. discover.scrobble = false turns it off. Also stops the previous YouTube video when moving to the next YouTube song, as it played on while the next was looked up. Fresher suggestions: each mix's suggestions are a random sample of its best 3 x discovery_count candidates, weighted by fit squared, rather than always the top ones. Suggestions left alone for a week expire, and stay out of the mixes for 60 days. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
39cd2b69f1
commit
b75f66c205
18 files changed
+437
-15
No files matched your search
+15
@@ -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"
|
||||
}
|
||||
+9
-3
@@ -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"
|
||||
}
|
||||
+15
@@ -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"
|
||||
}
|
||||
+7
-1
@@ -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"
|
||||
|
||||
+7
-1
@@ -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"
|
||||
|
||||
+7
-1
@@ -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"
|
||||
|
||||
@@ -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/<cover art id>` | Library cover art from Subsonic |
|
||||
| `GET /youtube/<suggestion id>?refresh=` | YouTube videos for a suggestion, best first (`refresh` searches again) |
|
||||
| `PUT /youtube/<suggestion id>` | 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:
|
||||
|
||||
|
||||
@@ -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<void>("/scrobble", json("POST", listen)),
|
||||
/** The video that played, when it wasn't the first one */
|
||||
setYoutubeVideo: (suggestionId: string, videoId: string) =>
|
||||
request<void>(`/youtube/${suggestionId}`, json("PUT", { video_id: videoId })),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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"
|
||||
@@ -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';
|
||||
@@ -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<dyn std::error::Error>> {
|
||||
// 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<String> = 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(())
|
||||
}
|
||||
+54
-2
@@ -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<T>(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::<f64>().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<String, f64>, profile: &HashMap<String, f64>, 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<String> = 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<String, usize> = 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<usize> = 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::<Vec<_>>());
|
||||
assert_eq!(order[6..], (6..20).collect::<Vec<_>>());
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -531,3 +531,65 @@ pub async fn radio(prompt: &str, mode: &str, token: &str) -> Result<Vec<String>,
|
||||
})
|
||||
.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<String>,
|
||||
pub recording_mbid: Option<String>,
|
||||
pub duration_ms: Option<u64>,
|
||||
/// e.g. "youtube.com"
|
||||
pub music_service: &'static str,
|
||||
/// Where it was played from, e.g. the YouTube video
|
||||
pub origin_url: Option<String>,
|
||||
}
|
||||
|
||||
/// 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<i64>,
|
||||
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::<serde_json::Value>(request).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -248,4 +248,8 @@ pub struct MixSuggestion {
|
||||
pub status: String,
|
||||
pub youtube_id: Option<String>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
/// When it expired, for status "expired" (only used in SQL)
|
||||
#[serde(skip)]
|
||||
#[allow(dead_code)]
|
||||
pub expired_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
@@ -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::<serde_json::Value>(
|
||||
"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::<serde_json::Value>("deletePlaylist", &[("id", playlist_id.to_string())])
|
||||
.await?;
|
||||
|
||||
+112
-2
@@ -34,7 +34,8 @@ pub fn routes() -> Vec<Route> {
|
||||
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<f64>,
|
||||
/// The YouTube video played
|
||||
video_id: Option<String>,
|
||||
}
|
||||
|
||||
/// 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::<bool>("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 = "<listen>")]
|
||||
async fn scrobble(
|
||||
_user: User,
|
||||
listen: Json<Listen>,
|
||||
pool: &State<PgPool>,
|
||||
media_client: &State<Arc<Subsonic>>,
|
||||
) -> 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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user