From 18b3f0974ef594abd914279f5701761d0697c6d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 14:53:29 +0000 Subject: [PATCH 1/9] Add genre mixes from clustering recent listens A new cluster_mix_rule clusters a Listenbrainz user's listens from the last few months by MusicBrainz genre (with tracks played in the same session pulled together) and maintains one Subsonic playlist per cluster, filled with the cluster's most played tracks plus unheard library songs from the best matching library genres. - listenbrainz: fetch raw listens since a timestamp and bulk recording genres, handling rate limits - cluster: tag TF-IDF + co-listen smoothing, spherical k-means with k chosen by silhouette score - mix: match cluster profiles to library genres and pick songs, with a per-artist cap; reuse playlists across rebuilds by genre overlap - subsonic: getGenres, getSongsByGenre, rename/delete playlist, genre and MBID fields on tracks, API error detection - daemon, migration, POST/GET /api/playlist/mix and README docs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p --- Cargo.lock | 9 +- Cargo.toml | 6 +- README.md | 48 ++ migrations/20261113150000_cluster_mixes.sql | 23 + src/cluster.rs | 539 ++++++++++++++++++++ src/daemon/cluster_mixes.rs | 263 ++++++++++ src/daemon/mod.rs | 2 + src/listenbrainz.rs | 196 +++++++ src/main.rs | 36 +- src/mix.rs | 334 ++++++++++++ src/models.rs | 96 ++++ src/subsonic.rs | 151 ++++++ src/track.rs | 30 ++ 13 files changed, 1728 insertions(+), 5 deletions(-) create mode 100644 migrations/20261113150000_cluster_mixes.sql create mode 100644 src/cluster.rs create mode 100644 src/daemon/cluster_mixes.rs create mode 100644 src/mix.rs diff --git a/Cargo.lock b/Cargo.lock index b958693..bd9a499 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -229,6 +229,7 @@ dependencies = [ "iana-time-zone", "js-sys", "num-traits", + "serde", "wasm-bindgen", "windows-targets 0.52.5", ] @@ -1468,9 +1469,11 @@ dependencies = [ "config", "log", "md5", + "rand", "reqwest", "rocket", "serde", + "serde_json", "sqlx", "thiserror 2.0.17", "tokio", @@ -2088,6 +2091,7 @@ checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" dependencies = [ "base64 0.22.1", "bytes", + "chrono", "crc", "crossbeam-queue", "either", @@ -2164,6 +2168,7 @@ dependencies = [ "bitflags 2.10.0", "byteorder", "bytes", + "chrono", "crc", "digest", "dotenvy", @@ -2206,6 +2211,7 @@ dependencies = [ "base64 0.22.1", "bitflags 2.10.0", "byteorder", + "chrono", "crc", "dotenvy", "etcetera", @@ -2241,6 +2247,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" dependencies = [ "atoi", + "chrono", "flume", "futures-channel", "futures-core", diff --git a/Cargo.toml b/Cargo.toml index 1b1cfd7..d7bc8d9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,7 +9,7 @@ description = "Subsonic playlist daemon" [dependencies] rocket = { version = "0.5.0", features = ["json"] } tokio = { version = "1.0", features = ["full"] } -sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid"] } +sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid", "chrono"] } reqwest = { version = "0.11", features = ["json"] } serde = { version = "1.0", features = ["derive"] } uuid = { version = "1.7", features = ["v4", "serde"] } @@ -17,7 +17,9 @@ md5 = "0.8.0" thiserror = "2.0.17" config = "0.15.19" log = "0.4.21" -chrono = "0.4.38" +chrono = { version = "0.4.38", features = ["serde"] } +rand = "0.8" +serde_json = "1.0" [package.metadata.deb] depends = "$auto" diff --git a/README.md b/README.md index 90ce54c..a8f4b83 100644 --- a/README.md +++ b/README.md @@ -63,3 +63,51 @@ For a yearly top songs playlist, run the following: INSERT INTO create_tracked_playlist (id, name_template, playlist_size, tracking_user, tracking_type) VALUES (gen_random_uuid(), '%Y - Top 100', 100, 'jellywx', 'this_year'); ``` + +### Genre mixes + +A cluster mix rule groups the tracks you've listened to over the last few months by genre, and +keeps one Subsonic playlist ("mix") per group, filled with songs from your library. + +How it works: + +1. Your listens for the period are fetched from Listenbrainz, along with the MusicBrainz genres of + each recording, its release group and its artists. +2. Tracks are clustered on their genres. Tracks you tend to play in the same listening session are + pulled closer together, so untagged tracks and genre-hopping artists land with what you play + them next to. The number of clusters is chosen automatically unless you set one. +3. Each cluster's most characteristic genres are matched against your library's genres + (`getGenres` / `getSongsByGenre`), case and punctuation insensitively, so a library tagged with + MusicBrainz genres by Picard works best. +4. Each mix is made of the cluster's most played tracks (`familiar_ratio` of the mix), plus songs + from the matching genres that you haven't played in the period, picked at random weighted by + how well their genres fit, with at most `playlist_size / 8` songs per artist. + +Mixes are rebuilt every `refresh_hours`. On a rebuild, existing mix playlists are reused for the +new cluster with the most similar genres (and renamed), new playlists are created for new +clusters, and playlists for clusters that no longer appear are deleted. + +Create a rule through the API: + +```sh +curl -X POST localhost:8000/api/playlist/mix -H 'Content-Type: application/json' \ + -d '{"tracking_user": "jellywx", "months": 3, "playlist_size": 50}' +``` + +or with SQL: + +```sql +INSERT INTO cluster_mix_rule (id, tracking_user, months, playlist_size) +VALUES (gen_random_uuid(), 'jellywx', 3, 50); +``` + +| Column | Default | Meaning | +|------------------|-----------------|--------------------------------------------------------------| +| `months` | 3 | Months of listening history to cluster | +| `cluster_count` | automatic | Number of mixes | +| `playlist_size` | 50 | Songs per mix | +| `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks | +| `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres | +| `refresh_hours` | 24 | How often to rebuild the mixes | + +Set `last_run` to `NULL` to rebuild a rule's mixes on the next daemon tick. diff --git a/migrations/20261113150000_cluster_mixes.sql b/migrations/20261113150000_cluster_mixes.sql new file mode 100644 index 0000000..403697b --- /dev/null +++ b/migrations/20261113150000_cluster_mixes.sql @@ -0,0 +1,23 @@ +-- A rule that periodically clusters a user's recent listens by genre and +-- maintains one Subsonic "mix" playlist per cluster. +CREATE TABLE "cluster_mix_rule" +( + id UUID NOT NULL PRIMARY KEY, + tracking_user VARCHAR(250) NOT NULL, -- Listenbrainz user to cluster + months INT NOT NULL DEFAULT 3, -- How many months of listens to cluster + cluster_count INT, -- Number of mixes. NULL = choose automatically + playlist_size INT NOT NULL DEFAULT 50, -- Tracks per mix + familiar_ratio DOUBLE PRECISION NOT NULL DEFAULT 0.3, -- Share of each mix taken from recently played tracks + name_template VARCHAR(250) NOT NULL DEFAULT 'Mix: {label}', -- {label} is replaced by the mix's genres + refresh_hours INT NOT NULL DEFAULT 24, -- How often to rebuild the mixes + last_run TIMESTAMPTZ -- When the mixes were last rebuilt +); + +-- The Subsonic playlists currently owned by a cluster mix rule. +CREATE TABLE "cluster_mix_playlist" +( + id UUID NOT NULL PRIMARY KEY, + rule_id UUID NOT NULL REFERENCES "cluster_mix_rule" (id) ON DELETE CASCADE, + playlist_id VARCHAR(250) NOT NULL, -- ID of the playlist in subsonic + tags TEXT[] NOT NULL -- Genres describing the cluster, used to keep playlists stable across rebuilds +); diff --git a/src/cluster.rs b/src/cluster.rs new file mode 100644 index 0000000..5f57c9d --- /dev/null +++ b/src/cluster.rs @@ -0,0 +1,539 @@ +//! Clustering of listened tracks by genre. +//! +//! Every track gets a TF-IDF vector over its MusicBrainz tags (recording, release +//! group and artist tags, as provided by the caller). To take listening habits +//! into account, each vector is then blended with the vectors of the tracks it +//! is usually played next to (within the same listening session), which also +//! gives untagged tracks a position. The vectors are grouped with spherical +//! k-means, weighted by play count, and each cluster is described by the tags +//! that are both common in it and distinctive compared to the rest. + +use rand::rngs::StdRng; +use rand::{Rng, SeedableRng}; +use std::collections::HashMap; + +pub struct Play { + /// Unix timestamp of the listen + pub ts: i64, + /// Identifies the track; listens with the same key are the same track + pub key: String, +} + +pub struct ClusterOptions { + /// Ignore tracks with fewer plays than this + pub min_plays: usize, + /// Fixed number of clusters. `None` picks one from `k_range` by silhouette score + pub cluster_count: Option, + pub k_range: (usize, usize), + /// Seconds of silence that end a listening session + pub session_gap: i64, + /// How many following tracks in a session count as played "together" + pub window: usize, + /// How strongly a track is pulled towards the tracks played around it + pub context_weight: f64, + pub seed: u64, +} + +impl Default for ClusterOptions { + fn default() -> Self { + Self { + min_plays: 2, + cluster_count: None, + k_range: (4, 10), + session_gap: 30 * 60, + window: 5, + context_weight: 0.5, + seed: 0, + } + } +} + +#[derive(Debug)] +pub struct Cluster { + /// Track keys and their play counts, most played first + pub tracks: Vec<(String, usize)>, + /// Total plays of the cluster's tracks + pub plays: usize, + /// Tags that characterise the cluster, most characteristic first + pub profile: Vec<(String, f64)>, +} + +const PROFILE_SIZE: usize = 40; +/// Profile tags need at least this fraction of the weight of the cluster's most common tag +const PROFILE_FLOOR: f64 = 0.2; +const N_INIT: usize = 5; +const MAX_ITER: usize = 100; +const SILHOUETTE_SAMPLE: usize = 1500; + +pub fn cluster( + plays: &[Play], + tags: &HashMap>, + opts: &ClusterOptions, +) -> Vec { + // ---- tracks ---- + let mut counts: HashMap<&str, usize> = HashMap::new(); + for p in plays { + *counts.entry(p.key.as_str()).or_default() += 1; + } + let mut keys: Vec<&str> = counts + .iter() + .filter(|(_, &n)| n >= opts.min_plays.max(1)) + .map(|(&k, _)| k) + .collect(); + keys.sort_by(|a, b| counts[b].cmp(&counts[a]).then(a.cmp(b))); + let n = keys.len(); + if n < 2 { + return vec![]; + } + let index: HashMap<&str, usize> = keys.iter().enumerate().map(|(i, &k)| (k, i)).collect(); + + // ---- tag TF-IDF ---- + let mut df: HashMap<&str, usize> = HashMap::new(); + for k in &keys { + for (tag, &w) in tags.get(*k).into_iter().flatten() { + if w > 0.0 { + *df.entry(tag.as_str()).or_default() += 1; + } + } + } + // tags on a single track can't relate tracks to each other + let mut vocab: Vec<&str> = df + .iter() + .filter(|(_, &d)| d >= 2) + .map(|(&t, _)| t) + .collect(); + vocab.sort(); + let dims = vocab.len(); + if dims == 0 { + return vec![]; + } + let vocab_index: HashMap<&str, usize> = + vocab.iter().enumerate().map(|(i, &t)| (t, i)).collect(); + let idf: Vec = vocab + .iter() + .map(|t| ((1 + n) as f64 / (1 + df[t]) as f64).ln() + 1.0) + .collect(); + + let mut tag_vecs = vec![vec![0.0; dims]; n]; + for (i, k) in keys.iter().enumerate() { + for (tag, &w) in tags.get(*k).into_iter().flatten() { + if let Some(&j) = vocab_index.get(tag.as_str()) { + if w > 0.0 { + tag_vecs[i][j] = (1.0 + w).ln() * idf[j]; + } + } + } + normalize(&mut tag_vecs[i]); + } + + // ---- listening context ---- + let mut order: Vec<&Play> = plays.iter().collect(); + order.sort_by_key(|p| p.ts); + let mut co: Vec> = vec![HashMap::new(); n]; + let mut session: Vec = vec![]; + let mut prev_ts: Option = None; + for p in order { + if prev_ts.is_some_and(|t| p.ts - t > opts.session_gap) { + add_cooccurrences(&session, opts.window, &mut co); + session.clear(); + } + if let Some(&i) = index.get(p.key.as_str()) { + session.push(i); + } + prev_ts = Some(p.ts); + } + add_cooccurrences(&session, opts.window, &mut co); + + let mut x: Vec> = Vec::with_capacity(n); + for i in 0..n { + let mut v = tag_vecs[i].clone(); + let total: f64 = co[i].values().sum(); + if total > 0.0 { + for (&j, &c) in &co[i] { + let f = opts.context_weight * c / total; + for (a, b) in v.iter_mut().zip(&tag_vecs[j]) { + *a += f * b; + } + } + } + normalize(&mut v); + x.push(v); + } + + // tracks with no tags and no tagged neighbours can't be placed + let placed: Vec = (0..n).filter(|&i| x[i].iter().any(|&v| v != 0.0)).collect(); + if placed.len() < 2 { + return vec![]; + } + let points: Vec> = placed.iter().map(|&i| x[i].clone()).collect(); + let weights: Vec = placed + .iter() + .map(|&i| (1.0 + counts[keys[i]] as f64).ln()) + .collect(); + + // ---- k-means ---- + let mut rng = StdRng::seed_from_u64(opts.seed); + let k = match opts.cluster_count { + Some(k) => k.clamp(1, points.len()), + None => choose_k(&points, &weights, opts.k_range, &mut rng), + }; + let labels = best_kmeans(&points, &weights, k, &mut rng); + + // ---- describe clusters ---- + let mut overall = vec![0.0; dims]; + let total_weight: f64 = weights.iter().sum(); + for (p, &i) in placed.iter().enumerate() { + for (o, v) in overall.iter_mut().zip(&tag_vecs[i]) { + *o += weights[p] * v / total_weight; + } + } + + let mut clusters = vec![]; + for c in 0..k { + let members: Vec = (0..placed.len()).filter(|&p| labels[p] == c).collect(); + if members.is_empty() { + continue; + } + let member_weight: f64 = members.iter().map(|&p| weights[p]).sum(); + let mut mean = vec![0.0; dims]; + for &p in &members { + for (m, v) in mean.iter_mut().zip(&tag_vecs[placed[p]]) { + *m += weights[p] * v / member_weight; + } + } + // frequent in the cluster AND over-represented compared to everything else, + // ignoring tags only a handful of the cluster's tracks have + let floor = PROFILE_FLOOR * mean.iter().cloned().fold(0.0, f64::max); + let mut profile: Vec<(String, f64)> = (0..dims) + .filter(|&j| mean[j] > 0.0 && mean[j] >= floor) + .map(|j| { + let score = mean[j] * (mean[j] / (overall[j] + 1e-9) + 1.0).ln(); + (vocab[j].to_string(), score) + }) + .collect(); + profile.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + profile.truncate(PROFILE_SIZE); + + let mut tracks: Vec<(String, usize)> = members + .iter() + .map(|&p| (keys[placed[p]].to_string(), counts[keys[placed[p]]])) + .collect(); + tracks.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0))); + + clusters.push(Cluster { + plays: tracks.iter().map(|t| t.1).sum(), + tracks, + profile, + }); + } + clusters.sort_by_key(|c| std::cmp::Reverse(c.plays)); + clusters +} + +fn add_cooccurrences(session: &[usize], window: usize, co: &mut [HashMap]) { + for a in 0..session.len() { + for b in (a + 1)..(a + 1 + window).min(session.len()) { + let (i, j) = (session[a], session[b]); + if i != j { + // closer plays count more + let w = 1.0 / (b - a) as f64; + *co[i].entry(j).or_default() += w; + *co[j].entry(i).or_default() += w; + } + } + } +} + +fn normalize(v: &mut [f64]) { + let norm = dot(v, v).sqrt(); + if norm > 0.0 { + v.iter_mut().for_each(|x| *x /= norm); + } +} + +fn dot(a: &[f64], b: &[f64]) -> f64 { + a.iter().zip(b).map(|(x, y)| x * y).sum() +} + +fn argmax_similarity(point: &[f64], centroids: &[Vec]) -> (usize, f64) { + centroids + .iter() + .enumerate() + .map(|(c, centroid)| (c, dot(point, centroid))) + .fold((0, f64::NEG_INFINITY), |best, cur| { + if cur.1 > best.1 { + cur + } else { + best + } + }) +} + +fn weighted_choice(weights: &[f64], rng: &mut StdRng) -> usize { + let total: f64 = weights.iter().sum(); + if total <= 0.0 { + return rng.gen_range(0..weights.len()); + } + let mut r = rng.gen::() * total; + for (i, &w) in weights.iter().enumerate() { + r -= w; + if r <= 0.0 { + return i; + } + } + weights.len() - 1 +} + +/// Spherical k-means (cosine similarity) with k-means++ seeding. +/// Returns the labels and the objective (weighted sum of similarity to the centroid). +fn kmeans(x: &[Vec], w: &[f64], k: usize, rng: &mut StdRng) -> (Vec, f64) { + let n = x.len(); + let mut centroids = vec![x[weighted_choice(w, rng)].clone()]; + while centroids.len() < k { + let d: Vec = (0..n) + .map(|i| { + let (_, sim) = argmax_similarity(&x[i], ¢roids); + w[i] * (1.0 - sim).max(0.0).powi(2) + }) + .collect(); + centroids.push(x[weighted_choice(&d, rng)].clone()); + } + + let mut labels = vec![usize::MAX; n]; + for _ in 0..MAX_ITER { + let mut changed = false; + for i in 0..n { + let (c, _) = argmax_similarity(&x[i], ¢roids); + if labels[i] != c { + labels[i] = c; + changed = true; + } + } + if !changed { + break; + } + + let dims = x[0].len(); + let mut sums = vec![vec![0.0; dims]; k]; + let mut sizes = vec![0usize; k]; + for i in 0..n { + sizes[labels[i]] += 1; + for (s, v) in sums[labels[i]].iter_mut().zip(&x[i]) { + *s += w[i] * v; + } + } + for c in 0..k { + if sizes[c] == 0 { + // re-seed an empty cluster with the worst-fitting point + let worst = (0..n) + .min_by(|&a, &b| { + dot(&x[a], ¢roids[labels[a]]) + .total_cmp(&dot(&x[b], ¢roids[labels[b]])) + }) + .unwrap(); + sums[c] = x[worst].clone(); + labels[worst] = c; + } + normalize(&mut sums[c]); + } + centroids = sums; + } + + let objective = (0..n) + .map(|i| w[i] * dot(&x[i], ¢roids[labels[i]])) + .sum(); + (labels, objective) +} + +fn best_kmeans(x: &[Vec], w: &[f64], k: usize, rng: &mut StdRng) -> Vec { + (0..N_INIT) + .map(|_| kmeans(x, w, k, rng)) + .max_by(|a, b| a.1.total_cmp(&b.1)) + .unwrap() + .0 +} + +/// Mean silhouette score using cosine distance, over the given sample of points. +fn silhouette(sim: &[Vec], labels: &[usize], k: usize) -> f64 { + let n = labels.len(); + let mut total = 0.0; + for i in 0..n { + let mut dist_sum = vec![0.0; k]; + let mut count = vec![0usize; k]; + for j in 0..n { + if i != j { + dist_sum[labels[j]] += 1.0 - sim[i][j]; + count[labels[j]] += 1; + } + } + if count[labels[i]] == 0 { + continue; // singleton clusters score 0 + } + let a = dist_sum[labels[i]] / count[labels[i]] as f64; + let b = (0..k) + .filter(|&c| c != labels[i] && count[c] > 0) + .map(|c| dist_sum[c] / count[c] as f64) + .fold(f64::INFINITY, f64::min); + if b.is_finite() && a.max(b) > 0.0 { + total += (b - a) / a.max(b); + } + } + total / n as f64 +} + +fn choose_k(x: &[Vec], w: &[f64], range: (usize, usize), rng: &mut StdRng) -> usize { + let n = x.len(); + let (lo, hi) = (range.0.max(2), range.1.min(n - 1)); + if lo > hi { + return range.0.clamp(1, n); + } + + // silhouette is quadratic, so score on a sample + let mut sample: Vec = (0..n).collect(); + for i in (1..n).rev() { + sample.swap(i, rng.gen_range(0..=i)); + } + sample.truncate(SILHOUETTE_SAMPLE); + let sim: Vec> = sample + .iter() + .map(|&i| sample.iter().map(|&j| dot(&x[i], &x[j])).collect()) + .collect(); + + let mut best = (f64::NEG_INFINITY, lo); + for k in lo..=hi { + let labels = best_kmeans(x, w, k, rng); + let sample_labels: Vec = sample.iter().map(|&i| labels[i]).collect(); + let score = silhouette(&sim, &sample_labels, k); + if score > best.0 { + best = (score, k); + } + } + best.1 +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tags(pairs: &[(&str, &[&str])]) -> HashMap> { + pairs + .iter() + .map(|(k, ts)| { + ( + k.to_string(), + ts.iter().map(|t| (t.to_string(), 1.0)).collect(), + ) + }) + .collect() + } + + fn plays(keys: &[&str], repeats: usize) -> Vec { + let mut out = vec![]; + let mut ts = 0; + for _ in 0..repeats { + for k in keys { + out.push(Play { + ts, + key: k.to_string(), + }); + ts += 200; + } + ts += 10_000; // new session + } + out + } + + #[test] + fn separates_genres() { + let t = tags(&[ + ("m1", &["metal", "death metal"]), + ("m2", &["metal", "death metal"]), + ("m3", &["metal", "black metal"]), + ("f1", &["folk", "indie folk"]), + ("f2", &["folk", "indie folk"]), + ("f3", &["folk", "folk rock"]), + ]); + let p = plays(&["m1", "m2", "m3", "f1", "f2", "f3"], 3); + let opts = ClusterOptions { + cluster_count: Some(2), + context_weight: 0.0, + ..Default::default() + }; + let clusters = cluster(&p, &t, &opts); + + assert_eq!(clusters.len(), 2); + for c in &clusters { + let first = c.tracks[0].0.chars().next().unwrap(); + assert!( + c.tracks.iter().all(|(k, _)| k.starts_with(first)), + "{:?}", + c + ); + let top = &c.profile[0].0; + assert!(if first == 'm' { + top.contains("metal") + } else { + top.contains("folk") + }); + } + } + + #[test] + fn untagged_tracks_follow_context() { + let t = tags(&[ + ("m1", &["metal"]), + ("m2", &["metal"]), + ("f1", &["folk"]), + ("f2", &["folk"]), + ]); + // "x" has no tags but is always played straight after the metal tracks + let mut p = plays(&["m1", "m2", "x"], 3); + let offset = p.last().unwrap().ts + 100_000; + p.extend(plays(&["f1", "f2"], 3).into_iter().map(|mut pl| { + pl.ts += offset; + pl + })); + let opts = ClusterOptions { + cluster_count: Some(2), + ..Default::default() + }; + let clusters = cluster(&p, &t, &opts); + + let metal = clusters + .iter() + .find(|c| c.tracks.iter().any(|(k, _)| k == "m1")) + .unwrap(); + assert!(metal.tracks.iter().any(|(k, _)| k == "x")); + } + + #[test] + fn picks_k_automatically() { + let genres = ["metal", "folk", "hyperpop", "jazz"]; + let mut pairs: Vec<(String, Vec<&str>)> = vec![]; + for g in genres { + for i in 0..6 { + pairs.push((format!("{g}{i}"), vec![g, "music"])); + } + } + let t: HashMap> = pairs + .iter() + .map(|(k, ts)| (k.clone(), ts.iter().map(|t| (t.to_string(), 1.0)).collect())) + .collect(); + let keys: Vec<&str> = pairs.iter().map(|(k, _)| k.as_str()).collect(); + let p = plays(&keys, 2); + let opts = ClusterOptions { + k_range: (2, 8), + context_weight: 0.0, + ..Default::default() + }; + + assert_eq!(cluster(&p, &t, &opts).len(), 4); + } + + #[test] + fn too_little_data() { + let t = tags(&[("a", &["rock"])]); + assert!(cluster(&plays(&["a"], 3), &t, &ClusterOptions::default()).is_empty()); + assert!(cluster(&[], &t, &ClusterOptions::default()).is_empty()); + } +} diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs new file mode 100644 index 0000000..d97dfc7 --- /dev/null +++ b/src/daemon/cluster_mixes.rs @@ -0,0 +1,263 @@ +use crate::cluster::{self, ClusterOptions, Play}; +use crate::listenbrainz; +use crate::mix::{self, ListenedTrack, MixOptions, RecentlyPlayed}; +use crate::models::{ClusterMixPlaylist, ClusterMixRule}; +use crate::subsonic::Subsonic; +use crate::CONFIG; +use chrono::Utc; +use rand::rngs::StdRng; +use rand::SeedableRng; +use sqlx::postgres::PgPool; +use std::collections::HashMap; +use std::time::Duration; +use tokio::time::{interval, MissedTickBehavior}; +use uuid::Uuid; + +/// Clusters smaller than this don't get a mix +const MIN_CLUSTER_TRACKS: usize = 5; +const SECONDS_PER_MONTH: i64 = 30 * 24 * 60 * 60; + +pub async fn cluster_mixes_daemon( + media_client: impl AsRef + Clone, +) -> Result<(), Box> { + println!("Cluster mix daemon starting..."); + + let database = PgPool::connect( + CONFIG + .get() + .unwrap() + .get::("database.url")? + .as_str(), + ) + .await + .unwrap(); + + let mut ticker = interval(Duration::from_secs( + CONFIG.get().unwrap().get::("daemon.interval")?, + )); + ticker.set_missed_tick_behavior(MissedTickBehavior::Skip); + + loop { + match ClusterMixRule::due(&database).await { + Ok(rules) => { + for rule in rules { + let id = rule.id; + if let Err(e) = build_mixes(media_client.as_ref(), rule, &database).await { + println!("Could not build cluster mixes for rule {}: {:?}", id, e); + } + } + } + + Err(e) => { + println!("Could not fetch cluster_mix_rule: {:?}", e); + } + } + + ticker.tick().await; + } +} + +pub async fn build_mixes( + media_client: &Subsonic, + rule: ClusterMixRule, + database: &PgPool, +) -> Result<(), Box> { + let since = Utc::now().timestamp() - rule.months.max(1) as i64 * SECONDS_PER_MONTH; + let listens = listenbrainz::listens_since(&rule.tracking_user, since).await?; + + // ---- listening history ---- + let mut plays = Vec::with_capacity(listens.len()); + let mut listened: HashMap = HashMap::new(); + let mut recently_played = RecentlyPlayed::default(); + for listen in &listens { + let mbid = listen.recording_mbid(); + let metadata = &listen.track_metadata; + let key = mbid + .clone() + .unwrap_or_else(|| mix::name_key(&metadata.artist_name, &metadata.track_name)); + let track = ListenedTrack { + mbid, + artist: metadata.artist_name.clone(), + title: metadata.track_name.clone(), + }; + recently_played.insert(&track); + listened.entry(key.clone()).or_insert(track); + plays.push(Play { + ts: listen.listened_at, + key, + }); + } + + let mbids: Vec = listened.values().filter_map(|t| t.mbid.clone()).collect(); + let tags = listenbrainz::recording_tags(&mbids).await?; + + // ---- cluster ---- + let clusters = cluster::cluster( + &plays, + &tags, + &ClusterOptions { + cluster_count: rule.cluster_count.map(|k| k.max(1) as usize), + seed: Utc::now().timestamp() as u64, + ..Default::default() + }, + ); + println!( + "{}: {} listens over {} months -> {} clusters", + rule.tracking_user, + listens.len(), + rule.months, + clusters.len() + ); + + // ---- build mixes ---- + let library_genres = mix::genre_index( + media_client + .get_genres() + .await? + .into_iter() + .filter(|g| g.song_count > 0) + .map(|g| g.value), + ); + let options = MixOptions { + size: rule.playlist_size.max(1) as usize, + familiar_ratio: rule.familiar_ratio, + max_genres: 6, + songs_per_genre: 1000, + }; + let mut rng = StdRng::from_entropy(); + + let mut mixes = vec![]; + for cluster in clusters + .iter() + .filter(|c| c.tracks.len() >= MIN_CLUSTER_TRACKS) + { + match mix::build_mix( + media_client, + cluster, + &library_genres, + &listened, + &recently_played, + &options, + &mut rng, + ) + .await? + { + Some(mix) => mixes.push(mix), + None => println!( + "No library genres match cluster {:?}", + cluster + .profile + .iter() + .take(3) + .map(|t| &t.0) + .collect::>() + ), + } + } + + // two clusters can share their top genres + let mut seen_labels: HashMap = HashMap::new(); + for mix in &mut mixes { + let n = seen_labels.entry(mix.label.clone()).or_default(); + *n += 1; + if *n > 1 { + mix.label = format!("{} ({})", mix.label, n); + } + } + + // ---- sync playlists, reusing the previous run's playlists where the genres overlap ---- + let existing = sqlx::query_as!( + ClusterMixPlaylist, + r#"SELECT * FROM "cluster_mix_playlist" WHERE rule_id = $1"#, + rule.id + ) + .fetch_all(database) + .await?; + + let pairs = mix::match_mixes( + &existing.iter().map(|p| p.tags.clone()).collect::>(), + &mixes.iter().map(|m| m.tags.clone()).collect::>(), + ); + let old_for_new: HashMap = pairs.iter().map(|&(o, n)| (n, o)).collect(); + + for (n, mix) in mixes.iter().enumerate() { + let name = rule.name_template.replace("{label}", &mix.label); + + let reused = match old_for_new.get(&n).map(|&o| &existing[o]) { + // the playlist may have been deleted by hand since the last run + Some(old) if media_client.get_playlist(&old.playlist_id).await.is_ok() => { + media_client + .rename_playlist(&old.playlist_id, &name) + .await?; + sqlx::query!( + r#"UPDATE "cluster_mix_playlist" SET tags = $1 WHERE id = $2"#, + &mix.tags, + old.id + ) + .execute(database) + .await?; + Some(old.playlist_id.clone()) + } + Some(old) => { + sqlx::query!( + r#"DELETE FROM "cluster_mix_playlist" WHERE id = $1"#, + old.id + ) + .execute(database) + .await?; + None + } + None => None, + }; + + let playlist_id = match reused { + Some(id) => id, + None => { + let playlist = media_client.create_playlist(&name).await?; + sqlx::query!( + r#" + INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags) + VALUES ($1, $2, $3, $4) + "#, + Uuid::new_v4(), + rule.id, + playlist.id, + &mix.tags, + ) + .execute(database) + .await?; + playlist.id + } + }; + + media_client + .replace_playlist_songs(&playlist_id, mix.song_ids.clone()) + .await?; + println!(" {} ({} songs)", name, mix.song_ids.len()); + } + + // mixes for tastes that no longer show up in the listening history + let kept: Vec = pairs.iter().map(|&(o, _)| o).collect(); + for (o, old) in existing.iter().enumerate() { + if !kept.contains(&o) { + if let Err(e) = media_client.delete_playlist(&old.playlist_id).await { + println!("Could not delete playlist {}: {:?}", old.playlist_id, e); + } + sqlx::query!( + r#"DELETE FROM "cluster_mix_playlist" WHERE id = $1"#, + old.id + ) + .execute(database) + .await?; + } + } + + sqlx::query!( + r#"UPDATE "cluster_mix_rule" SET last_run = NOW() WHERE id = $1"#, + rule.id + ) + .execute(database) + .await?; + + Ok(()) +} diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs index e5f4dd7..1be21c1 100644 --- a/src/daemon/mod.rs +++ b/src/daemon/mod.rs @@ -1,5 +1,7 @@ +pub mod cluster_mixes; pub mod create_playlists; pub mod update_playlists; +pub use cluster_mixes::cluster_mixes_daemon; pub use create_playlists::create_playlists_daemon; pub use update_playlists::update_playlists_daemon; diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index 3617d91..0b0a326 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -1,4 +1,5 @@ use serde::Deserialize; +use std::collections::HashMap; use std::fmt::Display; const BASE: &'static str = "https://api.listenbrainz.org/1"; @@ -108,3 +109,198 @@ pub async fn recordings( .await? .payload) } + +const USER_AGENT: &str = concat!("playlistd/", env!("CARGO_PKG_VERSION")); +const LISTENS_PAGE: usize = 1000; +const METADATA_BATCH: usize = 200; + +/// Send a request, waiting out Listenbrainz rate limits and retrying server errors. +async fn send_json( + request: reqwest::RequestBuilder, +) -> Result { + let mut attempt = 0; + loop { + let response = request + .try_clone() + .expect("request bodies are not streamed") + .header(reqwest::header::USER_AGENT, USER_AGENT) + .send() + .await?; + let status = response.status(); + let reset_in = response + .headers() + .get("X-RateLimit-Reset-In") + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.parse::().ok()) + .unwrap_or(1.0); + + if (status == reqwest::StatusCode::TOO_MANY_REQUESTS || status.is_server_error()) + && attempt < 6 + { + attempt += 1; + let wait = if status.is_server_error() { + 2f64.powi(attempt) + } else { + reset_in + 0.5 + }; + tokio::time::sleep(std::time::Duration::from_secs_f64(wait)).await; + continue; + } + + let remaining = response.headers().get("X-RateLimit-Remaining").cloned(); + let body = response.error_for_status()?.json::().await?; + if remaining.as_ref().and_then(|v| v.to_str().ok()) == Some("0") { + tokio::time::sleep(std::time::Duration::from_secs_f64(reset_in + 0.2)).await; + } + return Ok(body); + } +} + +#[derive(Deserialize)] +struct ListensResponse { + payload: ListensPayload, +} + +#[derive(Deserialize)] +struct ListensPayload { + listens: Vec, +} + +#[derive(Deserialize, Clone)] +pub struct Listen { + pub listened_at: i64, + pub track_metadata: TrackMetadata, +} + +#[derive(Deserialize, Clone)] +pub struct TrackMetadata { + pub artist_name: String, + pub track_name: String, + // Free-form and submitted by clients, so don't trust the field types + #[serde(default)] + pub additional_info: Option, + #[serde(default)] + pub mbid_mapping: Option, +} + +#[derive(Deserialize, Clone)] +pub struct MbidMapping { + #[serde(default)] + pub recording_mbid: Option, +} + +impl Listen { + /// The recording MBID, preferring Listenbrainz's own mapping over the submitting client's + pub fn recording_mbid(&self) -> Option { + self.track_metadata + .mbid_mapping + .as_ref() + .and_then(|m| m.recording_mbid.clone()) + .or_else(|| { + self.track_metadata + .additional_info + .as_ref()? + .get("recording_mbid")? + .as_str() + .map(str::to_string) + }) + .filter(|m| !m.is_empty()) + } +} + +/// All of a user's listens at or after `min_ts`, newest first +pub async fn listens_since(user: impl Display, min_ts: i64) -> Result, reqwest::Error> { + let client = reqwest::Client::new(); + let mut listens: Vec = vec![]; + let mut max_ts: Option = None; + + loop { + let mut request = client + .get(format!("{}/user/{}/listens", BASE, user)) + .query(&[("count", LISTENS_PAGE as i64)]); + if let Some(max_ts) = max_ts { + request = request.query(&[("max_ts", max_ts)]); + } + + let page = send_json::(request).await?.payload.listens; + let Some(oldest) = page.last().map(|l| l.listened_at) else { + break; + }; + listens.extend(page.into_iter().filter(|l| l.listened_at >= min_ts)); + if oldest < min_ts || Some(oldest) == max_ts { + break; + } + // max_ts is exclusive + max_ts = Some(oldest); + } + + Ok(listens) +} + +#[derive(Deserialize, Default)] +struct RecordingMetadata { + #[serde(default)] + tag: Option, +} + +#[derive(Deserialize, Default)] +struct RecordingTags { + #[serde(default)] + recording: Vec, + #[serde(default)] + release_group: Vec, + #[serde(default)] + artist: Vec, +} + +#[derive(Deserialize)] +struct Tag { + tag: String, + #[serde(default)] + count: Option, + /// Only set for tags that are MusicBrainz genres (not e.g. "british" or "female vocals") + #[serde(default)] + genre_mbid: Option, +} + +/// Weighted MusicBrainz genres for each recording, combining the recording's own genres (most +/// specific) with those of its release group and artists (broadest). Names are lowercased. +pub async fn recording_tags( + mbids: &[String], +) -> Result>, reqwest::Error> { + let client = reqwest::Client::new(); + let mut out = HashMap::new(); + + for batch in mbids.chunks(METADATA_BATCH) { + let request = + client + .post(format!("{}/metadata/recording/", BASE)) + .json(&serde_json::json!({ + "recording_mbids": batch, + "inc": "artist tag release", + })); + let metadata = send_json::>(request).await?; + + for (mbid, recording) in metadata { + let mut weights: HashMap = HashMap::new(); + if let Some(tags) = recording.tag { + for (source, weight) in [ + (&tags.recording, 3.0), + (&tags.release_group, 2.0), + (&tags.artist, 1.0), + ] { + for tag in source.iter().filter(|t| t.genre_mbid.is_some()) { + let name = tag.tag.trim().to_lowercase(); + if !name.is_empty() { + *weights.entry(name).or_default() += + weight * (1.0 + tag.count.unwrap_or(1).max(1) as f64).ln(); + } + } + } + } + out.insert(mbid, weights); + } + } + + Ok(out) +} diff --git a/src/main.rs b/src/main.rs index e469947..5985b3c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,13 +1,16 @@ +mod cluster; mod daemon; mod listenbrainz; +mod mix; mod models; mod playlist; mod subsonic; mod track; -use crate::daemon::{create_playlists_daemon, update_playlists_daemon}; +use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon}; use crate::models::{ - CreateTrackedPlaylist, PartialCreateTrackedPlaylist, PartialTrackedPlaylist, TrackedPlaylist, + ClusterMixRule, CreateTrackedPlaylist, PartialClusterMixRule, PartialCreateTrackedPlaylist, + PartialTrackedPlaylist, TrackedPlaylist, }; use crate::subsonic::{Subsonic, SubsonicBuilder}; use config::Config; @@ -61,6 +64,12 @@ async fn main() -> Result<(), Box> { create_playlists_daemon(_media_client).await.unwrap(); }); } + { + let _media_client = media_client.clone(); + tokio::spawn(async move { + cluster_mixes_daemon(_media_client).await.unwrap(); + }); + } rocket::build() .manage(media_client) @@ -72,6 +81,8 @@ async fn main() -> Result<(), Box> { add_tracking_playlist, all_playlists, create_tracking_playlist_rule, + create_cluster_mix_rule, + all_cluster_mix_rules, ], ) .launch() @@ -178,3 +189,24 @@ async fn all_playlists(pool: &State) -> JsonValue { Err(_) => json!([]), } } + +/// Create a rule that maintains genre mixes built from clustering a user's recent listens +#[post("/mix", data = "")] +async fn create_cluster_mix_rule( + pool: &State, + rule: Json, +) -> Json> { + match rule.record(pool.inner()).await { + Ok(rule) => Json(Response::Success(rule)), + Err(e) => Json(Response::Error(e.into())), + } +} + +/// Get all cluster mix rules +#[get("/mix")] +async fn all_cluster_mix_rules(pool: &State) -> JsonValue { + match ClusterMixRule::all(pool.inner()).await { + Ok(rules) => json!(rules), + Err(_) => json!([]), + } +} diff --git a/src/mix.rs b/src/mix.rs new file mode 100644 index 0000000..7b19363 --- /dev/null +++ b/src/mix.rs @@ -0,0 +1,334 @@ +//! Turn a cluster of listened tracks into a playlist of library songs. +//! +//! The cluster's tag profile is matched against the Subsonic library's genres. +//! Songs from the best matching genres are scored by how well their own genres +//! fit the profile, and the mix is made of: +//! * "familiar" tracks: the cluster's most played tracks, if they're in the library +//! * "discovery" tracks: well-fitting songs that weren't played recently, sampled +//! at random (weighted by fit) with a cap on songs per artist + +use crate::cluster::Cluster; +use crate::subsonic::{Subsonic, SubsonicError}; +use crate::track::Track; +use rand::rngs::StdRng; +use rand::seq::SliceRandom; +use rand::Rng; +use std::collections::{HashMap, HashSet}; + +pub struct MixOptions { + pub size: usize, + /// Share of the mix taken from the cluster's recently played tracks + pub familiar_ratio: f64, + /// How many library genres to draw songs from + pub max_genres: usize, + /// Most songs to consider from each genre + pub songs_per_genre: usize, +} + +pub struct Mix { + pub label: String, + /// Normalised genres describing the mix, best first + pub tags: Vec, + pub song_ids: Vec, +} + +/// A track from the listening history +pub struct ListenedTrack { + pub mbid: Option, + pub artist: String, + pub title: String, +} + +/// Lowercase alphanumerics only, so "Post-Hardcore" matches "post hardcore" +pub fn normalize(s: &str) -> String { + s.chars() + .filter(|c| c.is_alphanumeric()) + .flat_map(char::to_lowercase) + .collect() +} + +pub fn name_key(artist: &str, title: &str) -> String { + format!("{}\u{1f}{}", normalize(artist), normalize(title)) +} + +/// Tracks played during the clustered period, for telling "discovery" songs apart +#[derive(Default)] +pub struct RecentlyPlayed { + mbids: HashSet, + names: HashSet, +} + +impl RecentlyPlayed { + pub fn insert(&mut self, track: &ListenedTrack) { + if let Some(mbid) = &track.mbid { + self.mbids.insert(mbid.clone()); + } + self.names.insert(name_key(&track.artist, &track.title)); + } + + fn contains(&self, song: &Track) -> bool { + song.music_brainz_id + .as_ref() + .is_some_and(|m| self.mbids.contains(m)) + || self.names.contains(&name_key(&song.artist, &song.title)) + } +} + +/// Library genres by normalised name +pub fn genre_index(genres: impl IntoIterator) -> HashMap { + let mut index = HashMap::new(); + for genre in genres { + let key = normalize(&genre); + if !key.is_empty() { + index.entry(key).or_insert(genre); + } + } + index +} + +#[derive(Default)] +struct Selection { + songs: Vec, + ids: HashSet, + artists: HashMap, +} + +impl Selection { + fn take(&mut self, song: Track) { + if self.ids.insert(song.id.clone()) { + *self.artists.entry(normalize(&song.artist)).or_default() += 1; + self.songs.push(song); + } + } + + fn artist_count(&self, artist: &str) -> usize { + self.artists.get(&normalize(artist)).copied().unwrap_or(0) + } +} + +pub async fn build_mix( + client: &Subsonic, + cluster: &Cluster, + library_genres: &HashMap, + listened: &HashMap, + recently_played: &RecentlyPlayed, + opts: &MixOptions, + rng: &mut StdRng, +) -> Result, SubsonicError> { + // ---- match the cluster's profile to library genres ---- + let mut weights: HashMap = HashMap::new(); + for (tag, score) in &cluster.profile { + *weights.entry(normalize(tag)).or_default() += score; + } + let mut matched: Vec<(String, f64)> = vec![]; + for (tag, _) in &cluster.profile { + let key = normalize(tag); + if library_genres.contains_key(&key) && !matched.iter().any(|(k, _)| *k == key) { + matched.push((key.clone(), weights[&key])); + } + } + matched.truncate(opts.max_genres); + if matched.is_empty() { + return Ok(None); + } + + // ---- candidate songs ---- + let mut pool: HashMap = HashMap::new(); + for (key, _) in &matched { + for song in client + .songs_by_genre(&library_genres[key], opts.songs_per_genre) + .await? + { + pool.entry(song.id.clone()).or_insert(song); + } + } + + let score = |song: &Track| -> f64 { + let genres = song.genre_names(); + if genres.is_empty() { + return 0.0; + } + let fit: f64 = genres + .iter() + .filter_map(|g| weights.get(&normalize(g))) + .sum(); + // don't let songs tagged with every genre under the sun dominate + fit / (genres.len() as f64).sqrt() + }; + + let by_mbid: HashMap<&str, &Track> = pool + .values() + .filter_map(|s| Some((s.music_brainz_id.as_deref()?, s))) + .filter(|(m, _)| !m.is_empty()) + .collect(); + let by_name: HashMap = pool + .values() + .map(|s| (name_key(&s.artist, &s.title), s)) + .collect(); + + let mut selection = Selection::default(); + let artist_cap = (opts.size / 8).max(2); + + // ---- familiar: the cluster's most played tracks ---- + let familiar_quota = + ((opts.size as f64) * opts.familiar_ratio.clamp(0.0, 1.0)).round() as usize; + for (key, _) in cluster.tracks.iter().take(familiar_quota * 4) { + if selection.songs.len() >= familiar_quota { + break; + } + let Some(track) = listened.get(key) else { + continue; + }; + if selection.artist_count(&track.artist) >= artist_cap { + continue; + } + let found = match track + .mbid + .as_deref() + .and_then(|m| by_mbid.get(m)) + .or_else(|| by_name.get(&name_key(&track.artist, &track.title))) + { + Some(song) => Some((*song).clone()), + // it may be in the library under a genre we didn't pull + None => match &track.mbid { + Some(mbid) => { + let results = client.song_search(mbid.clone()).await?; + if results.len() == 1 { + results.into_iter().next() + } else { + None + } + } + None => None, + }, + }; + if let Some(song) = found { + selection.take(song); + } + } + + // ---- discovery: weighted random sample of well-fitting songs ---- + // Efraimidis-Spirakis: sort by u^(1/w) to sample without replacement, weighted by w + let mut ranked: Vec<(f64, &Track)> = pool + .values() + .filter_map(|song| { + let s = score(song); + (s > 0.0).then(|| (rng.gen::().powf(1.0 / (s * s)), song)) + }) + .collect(); + ranked.sort_by(|a, b| b.0.total_cmp(&a.0).then_with(|| a.1.id.cmp(&b.1.id))); + + // relax the rules in passes if the library is too small to fill the mix + for (allow_recent, cap_artists) in [(false, true), (true, true), (true, false)] { + for (_, song) in &ranked { + if selection.songs.len() >= opts.size { + break; + } + if selection.ids.contains(&song.id) + || (!allow_recent && recently_played.contains(song)) + || (cap_artists && selection.artist_count(&song.artist) >= artist_cap) + { + continue; + } + selection.take((*song).clone()); + } + } + + let mut chosen = selection.songs; + if chosen.is_empty() { + return Ok(None); + } + chosen.shuffle(rng); + + let label = matched + .iter() + .take(3) + .map(|(key, _)| library_genres[key].clone()) + .collect::>() + .join(" / "); + + Ok(Some(Mix { + label, + tags: matched.iter().take(5).map(|(k, _)| k.clone()).collect(), + song_ids: chosen.into_iter().map(|s| s.id).collect(), + })) +} + +/// Pair up previous mixes with new ones by genre overlap, so that playlists keep their identity +/// across rebuilds. Returns `(old index, new index)` pairs. +pub fn match_mixes(old: &[Vec], new: &[Vec]) -> Vec<(usize, usize)> { + let mut pairs: Vec<(f64, usize, usize)> = vec![]; + for (i, a) in old.iter().enumerate() { + for (j, b) in new.iter().enumerate() { + let a: HashSet<_> = a.iter().collect(); + let b: HashSet<_> = b.iter().collect(); + let union = a.union(&b).count(); + let jaccard = if union == 0 { + 0.0 + } else { + a.intersection(&b).count() as f64 / union as f64 + }; + if jaccard > 0.0 { + pairs.push((jaccard, i, j)); + } + } + } + pairs.sort_by(|a, b| b.0.total_cmp(&a.0).then((a.1, a.2).cmp(&(b.1, b.2)))); + + let (mut used_old, mut used_new) = (HashSet::new(), HashSet::new()); + let mut matched = vec![]; + for (_, i, j) in pairs { + if !used_old.contains(&i) && !used_new.contains(&j) { + used_old.insert(i); + used_new.insert(j); + matched.push((i, j)); + } + } + matched +} + +#[cfg(test)] +mod tests { + use super::*; + + fn tags(t: &[&str]) -> Vec { + t.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn normalizes_genre_names() { + assert_eq!(normalize("Post-Hardcore"), normalize("post hardcore")); + assert_eq!(normalize("Drum & Bass"), "drumbass"); + let index = genre_index(["Pop Punk".to_string(), "pop-punk".to_string()]); + assert_eq!(index.len(), 1); + assert_eq!(index["poppunk"], "Pop Punk"); + } + + #[test] + fn matches_mixes_by_overlap() { + let old = vec![ + tags(&["metal", "deathmetal"]), + tags(&["folk"]), + tags(&["jazz"]), + ]; + let new = vec![ + tags(&["folk", "indiefolk"]), + tags(&["metal", "blackmetal"]), + tags(&["pop"]), + ]; + let mut m = match_mixes(&old, &new); + m.sort(); + assert_eq!(m, vec![(0, 1), (1, 0)]); + } + + #[test] + fn genre_names_fall_back_to_genre_field() { + let mut track: Track = serde_json::from_value(serde_json::json!({ + "id": "1", "title": "t", "genre": "Rock; Indie Rock" + })) + .unwrap(); + assert_eq!(track.genre_names(), vec!["Rock", "Indie Rock"]); + track.genres = vec![crate::track::ItemGenre { name: "Emo".into() }]; + assert_eq!(track.genre_names(), vec!["Emo"]); + } +} diff --git a/src/models.rs b/src/models.rs index c0dded5..f306cba 100644 --- a/src/models.rs +++ b/src/models.rs @@ -1,3 +1,4 @@ +use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; use sqlx::error::Error; use sqlx::{Executor, Postgres}; @@ -131,3 +132,98 @@ impl CreateTrackedPlaylist { .await } } + +#[derive(Deserialize)] +pub struct PartialClusterMixRule { + pub tracking_user: String, + pub months: Option, + pub cluster_count: Option, + pub playlist_size: Option, + pub familiar_ratio: Option, + pub name_template: Option, + pub refresh_hours: Option, +} + +impl PartialClusterMixRule { + pub async fn record( + &self, + pool: impl Executor<'_, Database = Postgres> + Copy, + ) -> Result { + let uuid = Uuid::new_v4(); + + sqlx::query!( + r#" + INSERT INTO "cluster_mix_rule" + (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours) + VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24)) + "#, + uuid, + self.tracking_user, + self.months, + self.cluster_count, + self.playlist_size, + self.familiar_ratio, + self.name_template, + self.refresh_hours, + ) + .execute(pool) + .await?; + + ClusterMixRule::rule(pool, uuid).await + } +} + +#[derive(Serialize)] +pub struct ClusterMixRule { + pub id: Uuid, + pub tracking_user: String, + pub months: i32, + pub cluster_count: Option, + pub playlist_size: i32, + pub familiar_ratio: f64, + pub name_template: String, + pub refresh_hours: i32, + pub last_run: Option>, +} + +impl ClusterMixRule { + pub async fn all(pool: impl Executor<'_, Database = Postgres>) -> Result, Error> { + sqlx::query_as!(Self, r#"SELECT * FROM "cluster_mix_rule""#) + .fetch_all(pool) + .await + } + + /// Rules whose mixes haven't been built within their refresh interval + pub async fn due(pool: impl Executor<'_, Database = Postgres>) -> Result, Error> { + sqlx::query_as!( + Self, + r#" + SELECT * FROM "cluster_mix_rule" + WHERE last_run IS NULL OR last_run < NOW() - make_interval(hours => refresh_hours) + "# + ) + .fetch_all(pool) + .await + } + + pub async fn rule( + pool: impl Executor<'_, Database = Postgres>, + uuid: Uuid, + ) -> Result { + sqlx::query_as!( + Self, + r#"SELECT * FROM "cluster_mix_rule" WHERE id = $1"#, + uuid + ) + .fetch_one(pool) + .await + } +} + +#[derive(Serialize)] +pub struct ClusterMixPlaylist { + pub id: Uuid, + pub rule_id: Uuid, + pub playlist_id: String, + pub tags: Vec, +} diff --git a/src/subsonic.rs b/src/subsonic.rs index a185511..b1e2a03 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -43,6 +43,30 @@ struct GetPlaylistResponse { type CreatePlaylistResponse = GetPlaylistResponse; +#[derive(Deserialize)] +struct GetGenresResponse { + genres: GenreList, +} + +#[derive(Deserialize)] +struct GenreList { + #[serde(default)] + genre: Vec, +} + +#[derive(Deserialize, Debug, Clone)] +pub struct Genre { + pub value: String, + #[serde(rename = "songCount", default)] + pub song_count: usize, +} + +#[derive(Deserialize)] +struct SongsByGenreResponse { + #[serde(rename = "songsByGenre")] + songs_by_genre: SearchResponseSongs, +} + struct AuthParams { salt: String, hash: String, @@ -51,6 +75,8 @@ struct AuthParams { #[derive(Debug, Error)] pub enum SubsonicError { Reqwest(reqwest::Error), + Api(String), + Json(serde_json::Error), } impl Display for SubsonicError { @@ -194,6 +220,131 @@ impl Subsonic { self.get_playlist(playlist_id).await } + + /// Authentication and format parameters common to every request + fn base_params(&self) -> Vec<(&'static str, String)> { + let auth_params = self.auth_params(); + vec![ + ("u", self.username.to_string()), + ("s", auth_params.salt), + ("t", auth_params.hash), + ("v", String::from("16")), + ("c", String::from("playlistd")), + ("f", String::from("json")), + ] + } + + async fn request( + &self, + endpoint: &str, + params: &[(&'static str, String)], + ) -> Result { + let mut query = self.base_params(); + query.extend_from_slice(params); + + let response = self + .client + .get(format!("{}/{}", self.base, endpoint)) + .query(&query) + .send() + .await + .map_err(SubsonicError::Reqwest)? + .json::>() + .await + .map_err(SubsonicError::Reqwest)? + .subsonic_response; + + if response.get("status").and_then(|s| s.as_str()) == Some("failed") { + return Err(SubsonicError::Api( + response + .pointer("/error/message") + .and_then(|m| m.as_str()) + .unwrap_or("unknown error") + .to_string(), + )); + } + serde_json::from_value(response).map_err(SubsonicError::Json) + } + + /// All genres in the library + pub async fn get_genres(&self) -> Result, SubsonicError> { + Ok(self + .request::("getGenres", &[]) + .await? + .genres + .genre) + } + + /// Up to `limit` songs with the given genre + pub async fn songs_by_genre( + &self, + genre: &str, + limit: usize, + ) -> Result, SubsonicError> { + // Subsonic caps a single page at 500 + const PAGE: usize = 500; + let mut songs = vec![]; + + while songs.len() < limit { + let count = PAGE.min(limit - songs.len()); + let page = self + .request::( + "getSongsByGenre", + &[ + ("genre", genre.to_string()), + ("count", count.to_string()), + ("offset", songs.len().to_string()), + ], + ) + .await? + .songs_by_genre + .song; + let done = page.len() < count; + songs.extend(page); + if done { + break; + } + } + + Ok(songs) + } + + pub async fn rename_playlist( + &self, + playlist_id: &str, + name: &str, + ) -> Result<(), SubsonicError> { + self.request::( + "updatePlaylist", + &[ + ("playlistId", playlist_id.to_string()), + ("name", name.to_string()), + ], + ) + .await?; + Ok(()) + } + + /// Replace all of a playlist's songs + pub async fn replace_playlist_songs( + &self, + playlist_id: &str, + song_ids: Vec, + ) -> Result { + let playlist = self.get_playlist(playlist_id).await?; + self.update_playlist( + playlist_id.to_string(), + song_ids, + (0..playlist.song_count).collect(), + ) + .await + } + + pub async fn delete_playlist(&self, playlist_id: &str) -> Result<(), SubsonicError> { + self.request::("deletePlaylist", &[("id", playlist_id.to_string())]) + .await?; + Ok(()) + } } #[derive(Default)] diff --git a/src/track.rs b/src/track.rs index 69f9b92..6c6e41c 100644 --- a/src/track.rs +++ b/src/track.rs @@ -4,6 +4,36 @@ use serde::{Deserialize, Serialize}; pub struct Track { pub id: String, pub title: String, + #[serde(default)] pub album: String, + #[serde(default)] pub artist: String, + #[serde(default)] + pub genre: Option, + /// OpenSubsonic: all of the song's genres + #[serde(default)] + pub genres: Vec, + #[serde(rename = "musicBrainzId", default)] + pub music_brainz_id: Option, +} + +#[derive(Serialize, Deserialize, Debug, Clone)] +pub struct ItemGenre { + pub name: String, +} + +impl Track { + /// The song's genres, from the OpenSubsonic `genres` list if the server provides it, + /// otherwise from the plain `genre` field + pub fn genre_names(&self) -> Vec { + if !self.genres.is_empty() { + return self.genres.iter().map(|g| g.name.clone()).collect(); + } + self.genre + .iter() + .flat_map(|g| g.split([';', ',', '/'])) + .map(|g| g.trim().to_string()) + .filter(|g| !g.is_empty()) + .collect() + } } -- 2.34.1 From a8b112377753e19b27e82acdface7c45c0eefbc8 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 16:39:46 +0000 Subject: [PATCH 2/9] Add discover UI with new song suggestions Each mix rebuild now also finds songs that aren't in the library: the user's Listenbrainz recommendations they've never played, plus an LB Radio prompt per mix when a Listenbrainz token is configured. Each candidate goes to the mix whose genre profile it fits best and is skipped if it's already in the library or was played recently. discover/ is a new React app to listen to the mixes: library songs stream from Subsonic and suggested songs are found on YouTube with yt-dlp, both proxied through playlistd with Range support for seeking. Suggestions can be liked (kept in a "Liked new songs" list) or hidden. - discover: candidate gathering, genre fit scoring, library filtering - web: /api/discover routes, Subsonic/YouTube streaming proxy - youtube: yt-dlp search (skipping hour-long results) and audio URLs - mix tags now hold library genre names, for display in the UI - config: listenbrainz.token, discover.ui, discover.ytdlp, discover.format Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p --- Cargo.lock | 29 + Cargo.toml | 4 +- README.md | 45 + discover/.gitignore | 2 + discover/index.html | 13 + discover/package-lock.json | 1757 +++++++++++++++++ discover/package.json | 23 + discover/src/App.tsx | 230 +++ discover/src/LikedView.tsx | 47 + discover/src/MixView.tsx | 121 ++ discover/src/PlayerBar.tsx | 55 + discover/src/TrackRow.tsx | 56 + discover/src/api.ts | 75 + discover/src/icons.tsx | 16 + discover/src/main.tsx | 10 + discover/src/queue.ts | 47 + discover/src/styles.css | 824 ++++++++ discover/src/usePlayer.ts | 124 ++ discover/tsconfig.json | 16 + discover/vite.config.ts | 12 + etc/playlistd/playlistd.toml | 14 + migrations/20261113180000_mix_suggestions.sql | 24 + src/daemon/cluster_mixes.rs | 119 +- src/discover.rs | 210 ++ src/listenbrainz.rs | 184 +- src/main.rs | 26 +- src/mix.rs | 22 +- src/models.rs | 25 +- src/subsonic.rs | 21 + src/track.rs | 5 + src/web.rs | 375 ++++ src/youtube.rs | 133 ++ 32 files changed, 4628 insertions(+), 36 deletions(-) create mode 100644 discover/.gitignore create mode 100644 discover/index.html create mode 100644 discover/package-lock.json create mode 100644 discover/package.json create mode 100644 discover/src/App.tsx create mode 100644 discover/src/LikedView.tsx create mode 100644 discover/src/MixView.tsx create mode 100644 discover/src/PlayerBar.tsx create mode 100644 discover/src/TrackRow.tsx create mode 100644 discover/src/api.ts create mode 100644 discover/src/icons.tsx create mode 100644 discover/src/main.tsx create mode 100644 discover/src/queue.ts create mode 100644 discover/src/styles.css create mode 100644 discover/src/usePlayer.ts create mode 100644 discover/tsconfig.json create mode 100644 discover/vite.config.ts create mode 100644 migrations/20261113180000_mix_suggestions.sql create mode 100644 src/discover.rs create mode 100644 src/web.rs create mode 100644 src/youtube.rs diff --git a/Cargo.lock b/Cargo.lock index bd9a499..e960b85 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -664,6 +664,17 @@ version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a44623e20b9681a318efdd71c299b6b222ed6f231972bfe2f224ebad6311f0c1" +[[package]] +name = "futures-macro" +version = "0.3.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "futures-sink" version = "0.3.30" @@ -685,6 +696,7 @@ dependencies = [ "futures-channel", "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -1467,6 +1479,7 @@ version = "0.2.6" dependencies = [ "chrono", "config", + "futures-util", "log", "md5", "rand", @@ -1477,6 +1490,7 @@ dependencies = [ "sqlx", "thiserror 2.0.17", "tokio", + "tokio-util", "uuid", ] @@ -1658,10 +1672,12 @@ dependencies = [ "system-configuration", "tokio", "tokio-native-tls", + "tokio-util", "tower-service", "url", "wasm-bindgen", "wasm-bindgen-futures", + "wasm-streams", "web-sys", "winreg", ] @@ -2847,6 +2863,19 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e072d4e72f700fb3443d8fe94a39315df013eef1104903cdb0a2abd322bbecd" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + [[package]] name = "web-sys" version = "0.3.69" diff --git a/Cargo.toml b/Cargo.toml index d7bc8d9..6bf666a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ description = "Subsonic playlist daemon" rocket = { version = "0.5.0", features = ["json"] } tokio = { version = "1.0", features = ["full"] } sqlx = { version = "0.8.6", features = ["runtime-tokio", "postgres", "uuid", "chrono"] } -reqwest = { version = "0.11", features = ["json"] } +reqwest = { version = "0.11", features = ["json", "stream"] } serde = { version = "1.0", features = ["derive"] } uuid = { version = "1.7", features = ["v4", "serde"] } md5 = "0.8.0" @@ -20,6 +20,8 @@ log = "0.4.21" chrono = { version = "0.4.38", features = ["serde"] } rand = "0.8" serde_json = "1.0" +futures-util = "0.3" +tokio-util = { version = "0.7", features = ["io"] } [package.metadata.deb] depends = "$auto" diff --git a/README.md b/README.md index a8f4b83..181afce 100644 --- a/README.md +++ b/README.md @@ -109,5 +109,50 @@ VALUES (gen_random_uuid(), 'jellywx', 3, 50); | `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks | | `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres | | `refresh_hours` | 24 | How often to rebuild the mixes | +| `discovery_count`| 15 | New songs (not in your library) to suggest per mix | Set `last_run` to `NULL` to rebuild a rule's mixes on the next daemon tick. + +### Discover UI + +`discover/` is a React app for listening to the genre mixes, alongside new songs that aren't in +your library yet. + +Each time the mixes are rebuilt, playlistd also looks for new songs for each mix: + +* your Listenbrainz recommendations, keeping only recordings you've never listened to, and +* if `listenbrainz.token` is set, an LB Radio playlist for each mix's top genres. + +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. + +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) and streamed through playlistd, so yt-dlp needs to be +installed on the server (keep it up to date: YouTube changes often break older versions). You can +like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again. + +Build it with: + +```sh +cd discover +npm install +npm run build +``` + +and set `discover.ui` (or `DISCOVER_UI`) to the `discover/dist` directory to serve it from +playlistd at `/`. For development, `npm run dev` serves the UI with hot reload and forwards API +requests to playlistd on `localhost:8000` (or `PLAYLISTD_URL`). + +The UI uses these endpoints under `/api/discover`: + +| Endpoint | Purpose | +|--------------------------------|------------------------------------------------------| +| `GET /rules` | Cluster mix rules | +| `GET /rules//mixes` | A rule's mixes | +| `GET /mixes/` | A mix's library songs and new song suggestions | +| `GET /rules//liked` | Liked suggestions | +| `PUT /suggestions/` | Set a suggestion's status (`new`, `liked`, `dismissed`) | +| `POST /rules//rebuild` | Rebuild a rule's mixes on the next daemon tick | +| `GET /stream/` | Stream a library song from Subsonic | +| `GET /cover/` | Library cover art from Subsonic | +| `GET /youtube/` | Stream a suggested song from YouTube | diff --git a/discover/.gitignore b/discover/.gitignore new file mode 100644 index 0000000..f06235c --- /dev/null +++ b/discover/.gitignore @@ -0,0 +1,2 @@ +node_modules +dist diff --git a/discover/index.html b/discover/index.html new file mode 100644 index 0000000..da6a5eb --- /dev/null +++ b/discover/index.html @@ -0,0 +1,13 @@ + + + + + + + Discover + + +
+ + + diff --git a/discover/package-lock.json b/discover/package-lock.json new file mode 100644 index 0000000..47a7bc5 --- /dev/null +++ b/discover/package-lock.json @@ -0,0 +1,1757 @@ +{ + "name": "playlistd-discover", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "playlistd-discover", + "version": "0.1.0", + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "@types/react": "18.3.12", + "@types/react-dom": "18.3.1", + "@vitejs/plugin-react": "4.3.3", + "typescript": "5.6.3", + "vite": "5.4.10" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.13.tgz", + "integrity": "sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.13", + "@babel/helper-compilation-targets": "^7.29.13", + "@babel/helper-module-transforms": "^7.29.13", + "@babel/helpers": "^7.29.13", + "@babel/parser": "^7.29.13", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.13", + "@babel/types": "^7.29.11", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.14.tgz", + "integrity": "sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.14", + "@babel/types": "^7.29.14", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.13", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.13.tgz", + "integrity": "sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.14.tgz", + "integrity": "sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-plugin-utils": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.14.tgz", + "integrity": "sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.14.tgz", + "integrity": "sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.14.tgz", + "integrity": "sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.14" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-self": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz", + "integrity": "sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/plugin-transform-react-jsx-source": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz", + "integrity": "sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-plugin-utils": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0-0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.14.tgz", + "integrity": "sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.14", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.14", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.14", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.14", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.14.tgz", + "integrity": "sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.14", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@rollup/rollup-android-arm-eabi": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.68.3.tgz", + "integrity": "sha512-mqfypgH/liYjaSCoPI4erckUcROgZtmFUUmyOJ05oyayi/tVqOEYAzWP7ufqCoCT3xB31Fw4XIVO/jX42hYvKA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.68.3.tgz", + "integrity": "sha512-5tY+GC/1gpt79cKS2DQzu6iD824j6BmI4q5Zb6qftZ4kWqIQmvR3DD4eJ2Gclu6/nVMYDk2IVpqxypWOiAuWJg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-android-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-android-x64/-/rollup-android-x64-4.68.3.tgz", + "integrity": "sha512-nDBcQ/o3PMmGxmAzGBJFn+n1rb83Va9WSdFIq1AHmlEF3tuibVsyJ3kG5x13r7VIy6WI8SvzCdHVNSlSDIdj8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@rollup/rollup-darwin-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.68.3.tgz", + "integrity": "sha512-dra5zl0QWKkIkaMgNDNPC19gkMlPAfAf41yWlkGztXMIvUQrX9XWZFQRw7abhH3nks+XZGQpybINAxT2pKdFew==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-darwin-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.68.3.tgz", + "integrity": "sha512-xo5xeo/AjEB/ArzQjGn0JRDZuybZicQ5O3VPfko6ocH1li/qNrN4p5+R/WgjavzRz6UwAOaqsau7VvRQA6i6AA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@rollup/rollup-freebsd-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.68.3.tgz", + "integrity": "sha512-zdckkcxHDEEKyDbC1t21DeaaiKGymxbkBU9c3zyfaaz+8N96ItJw4nmzHhZF+Mukgt906fnf2tsc90pVyStuHA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-freebsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.68.3.tgz", + "integrity": "sha512-9oXqI7g/ycEz7TyicdGBC4sL6PfWMXAx8u15f/nd7lYkCLJd8U8VdBfbpc4SSnRBU/e7aPALve3mhzasGDeCYg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@rollup/rollup-linux-arm-gnueabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.68.3.tgz", + "integrity": "sha512-hbgT4NlaOELE3D5UUzSqF+OFgwz4Scvo2SQD9nZJUFjdIsg9Kg3FabQauUxkHKY9N5yjNXfXRRmiKNN4JpLmFA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm-musleabihf": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.68.3.tgz", + "integrity": "sha512-yECcXZ/Bl+JVRhLFgld42rYrXgPdE0LtySGAmmmH6OtkaJM17A4cWG/eCzDymMVb52/jZjW0R54YrTHj4xXlSA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.68.3.tgz", + "integrity": "sha512-q4Q4/B7wyqM+TFqY5tJYQlaz5+ksGopcRmMeMdu4q6eaPK7N1PymTjIaH5LL32mMJBqIzpRof7BhlYLim5JgNQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-arm64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.68.3.tgz", + "integrity": "sha512-Ich3TGl/7GqhQ6G6jVPzgGQGJjd3E5hECxSVanPYchy6Vwcq+WI8wG/gmEMilHNy+ZYCR6U8EN50EejG3TaIgw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.68.3.tgz", + "integrity": "sha512-URBmOhwv4Y0Hi5Hhxc3cmqZLtQlx55DOs5PUhhITDC3zu0qwAfhcNAFAIwAhOUdA6NFVEck07CNZX6cBEs1vTg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-loong64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.68.3.tgz", + "integrity": "sha512-PTdJXuZplRyaE3ECArlbZubI2LlUHWm0oCipCexnE/8LM+L7qIqUiNbU0piBxt46EB5zxXX+cpmDvHX4Z3WwcQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.68.3.tgz", + "integrity": "sha512-IlSQPDExSm9YdtrWeZIHj87GPXI9lYygRvHVwQ1o9t91JHIiB2CihrvNIASpc/zI28atqm04jS3proaQuaJMww==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-ppc64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.68.3.tgz", + "integrity": "sha512-O2ssyDcBTZkH5v2P/9ZaXJreL0hCKvUA5UwuHn0jCKeMLKi4GhspZJ1I5FT5QsHtJ/dPx4pup7pg/Lw0emeY0Q==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.68.3.tgz", + "integrity": "sha512-fesqagxcnc87lH2+aBWne/tFCmQVIGH+YezjY1wQwbUODuTBBlhHoyxju6umwn8LnjHVanjpoeaQdLsXP8JQSQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-riscv64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.68.3.tgz", + "integrity": "sha512-WAjFDtLW3HjJ2RAytKoWdFwlK/hW8rJHrjhRZFw14nR+c9JN//WIlSBkyXUjEYCNOFs2sGLNutOEPQG4iVYHgA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-s390x-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.68.3.tgz", + "integrity": "sha512-+fZiTeHV/1fy/14dRqE4thjYwUOABL6qQjxElOEQg2oHLkCamO8dxhHphVgD4+pFxtVEUIWxsGVduPtwnAlvbg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.68.3.tgz", + "integrity": "sha512-pfn4Zd9Ic3lEaSwW3GsQhTIDd7929C+eiEkOutsSCT2IHD6rDLblwmMQkgeGOso0oDo9Jk/ERtFdtFr9ElLs+g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-linux-x64-musl": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.68.3.tgz", + "integrity": "sha512-eUXzaeNQbKXKNqseL3g/usUqOPmRu+DbQsvwr9MXMdV+VQFUNb9bcWSNAAs/TRV95PCbFK46kLzHEOhFSzujsg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@rollup/rollup-openbsd-x64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.68.3.tgz", + "integrity": "sha512-OiUclE7QDU4H/hr3ACRHhVGKWl+gNx+6Emignfq0hmNmzzTkZnT79wzB9NXKd0QH16S4t/wVqlAFBfC17nkZ5A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ] + }, + "node_modules/@rollup/rollup-openharmony-arm64": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.68.3.tgz", + "integrity": "sha512-s6EclDWmk6zvIfk1yixgYthk7xHNx0xu5cEF5RDpS4IHNTpfswRX6xOXVG5cHF5xWn0B6EpDGARhPQ520KTlsA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, + "node_modules/@rollup/rollup-win32-arm64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.68.3.tgz", + "integrity": "sha512-G2xnmxGnU8XHLwtjnnXNRcLrub+Af3nm9VQ1QzL2aEiAL7woBdRgTCZBslJl8umA+YMqdEFpUh9kJB/Vyzk2wQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-ia32-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.68.3.tgz", + "integrity": "sha512-Y/4tApNVrMUYWbAHsyRWJgwuuJOfhTNhA2B04Xpa6+G9btkPZ9kU3XagUKzPTwF3hg36NpQk748JsnoTVho67Q==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-gnu": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.68.3.tgz", + "integrity": "sha512-i2vH/OA5BcW+TdNg12ZTRC4rn+vILaPMP9CvHqnv+QEpMjBHGGNLo4k4EnEqzjYvTD6x1Xark9WhsQbH4bTzUQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@rollup/rollup-win32-x64-msvc": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.68.3.tgz", + "integrity": "sha512-ADb1Uz2MNM0sxVpAlMNdQG16Hw4sgW1aqVL7NeqBMpcZeiHb192d7W6shZdMQs33D+w9ihDYBBPsYqqc4MlD8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@types/babel__core": { + "version": "7.20.5", + "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", + "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.20.7", + "@babel/types": "^7.20.7", + "@types/babel__generator": "*", + "@types/babel__template": "*", + "@types/babel__traverse": "*" + } + }, + "node_modules/@types/babel__generator": { + "version": "7.27.0", + "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.27.0.tgz", + "integrity": "sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__template": { + "version": "7.4.4", + "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", + "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" + } + }, + "node_modules/@types/babel__traverse": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.28.0.tgz", + "integrity": "sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.2" + } + }, + "node_modules/@types/estree": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz", + "integrity": "sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "22.9.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.9.0.tgz", + "integrity": "sha512-vuyHg81vvWA1Z1ELfvLko2c8f34gyA0zaic0+Rllc5lbCnbSyuvb2Oxpm6TAUAC/2xZN3QGqxBNggD1nNR2AfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.8" + } + }, + "node_modules/@types/prop-types": { + "version": "15.7.15", + "resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz", + "integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/react": { + "version": "18.3.12", + "resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.12.tgz", + "integrity": "sha512-D2wOSq/d6Agt28q7rSI3jhU7G6aiuzljDGZ2hTZHIkrTLUI+AF3WMeKkEZ9nN2fkBAlcktT6vcZjDFiIhMYEQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/prop-types": "*", + "csstype": "^3.0.2" + } + }, + "node_modules/@types/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-qW1Mfv8taImTthu4KoXgDfLuk4bydU6Q/TkADnDWWHwi4NX4BR+LWfTp2sVmTqRrsHvyDDTelgelxJ+SsejKKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/react": "*" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "4.3.3", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-4.3.3.tgz", + "integrity": "sha512-NooDe9GpHGqNns1i8XDERg0Vsg5SSYRhRxxyTGogUdkdNt47jal+fbuYi+Yfq6pzRCKXyoPcWisfxE6RIM3GKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.25.2", + "@babel/plugin-transform-react-jsx-self": "^7.24.7", + "@babel/plugin-transform-react-jsx-source": "^7.24.7", + "@types/babel__core": "^7.20.5", + "react-refresh": "^0.14.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "peerDependencies": { + "vite": "^4.2.0 || ^5.0.0" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.11.37", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.37.tgz", + "integrity": "sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/browserslist": { + "version": "4.29.5", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.5.tgz", + "integrity": "sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.11.33", + "caniuse-lite": "^1.0.30001819", + "electron-to-chromium": "^1.5.464", + "node-releases": "^2.0.60", + "update-browserslist-db": "^1.3.4" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001826", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001826.tgz", + "integrity": "sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.485", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.485.tgz", + "integrity": "sha512-m3uadzR0Z+sR19HGWgfxoZcKv9hE/edVM9OZ+FJ4wNRyfuFtkwZJIDoehEty5sisYVwmge8lKV1tenWOyClVgw==", + "dev": true, + "license": "ISC" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/node-releases": { + "version": "2.0.64", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.64.tgz", + "integrity": "sha512-zAPCKqMcnqs2nGy6nlkm7JduFseiBJy3EXHGLh+8pFR+TxGCBxxiEN21+UROU5CKwX/f4TlUcYjiM+vs/tsyxw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/react": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz", + "integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz", + "integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-refresh": { + "version": "0.14.2", + "resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.2.tgz", + "integrity": "sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/rollup": { + "version": "4.68.3", + "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.3.tgz", + "integrity": "sha512-wd2gavj7CEQv52rdcVqfUupO/KPIKcoJKxyFWl4cOqYZGMQEOSijJRkliz0dRa7gpkj/h4TRqyWa+dJJi6T0OA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "^1.0.10" + }, + "bin": { + "rollup": "dist/bin/rollup" + }, + "engines": { + "node": ">=18.0.0", + "npm": ">=8.0.0" + }, + "optionalDependencies": { + "@rollup/rollup-android-arm-eabi": "4.68.3", + "@rollup/rollup-android-arm64": "4.68.3", + "@rollup/rollup-android-x64": "4.68.3", + "@rollup/rollup-darwin-arm64": "4.68.3", + "@rollup/rollup-darwin-x64": "4.68.3", + "@rollup/rollup-freebsd-arm64": "4.68.3", + "@rollup/rollup-freebsd-x64": "4.68.3", + "@rollup/rollup-linux-arm-gnueabihf": "4.68.3", + "@rollup/rollup-linux-arm-musleabihf": "4.68.3", + "@rollup/rollup-linux-arm64-gnu": "4.68.3", + "@rollup/rollup-linux-arm64-musl": "4.68.3", + "@rollup/rollup-linux-loong64-gnu": "4.68.3", + "@rollup/rollup-linux-loong64-musl": "4.68.3", + "@rollup/rollup-linux-ppc64-gnu": "4.68.3", + "@rollup/rollup-linux-ppc64-musl": "4.68.3", + "@rollup/rollup-linux-riscv64-gnu": "4.68.3", + "@rollup/rollup-linux-riscv64-musl": "4.68.3", + "@rollup/rollup-linux-s390x-gnu": "4.68.3", + "@rollup/rollup-linux-x64-gnu": "4.68.3", + "@rollup/rollup-linux-x64-musl": "4.68.3", + "@rollup/rollup-openbsd-x64": "4.68.3", + "@rollup/rollup-openharmony-arm64": "4.68.3", + "@rollup/rollup-win32-arm64-msvc": "4.68.3", + "@rollup/rollup-win32-ia32-msvc": "4.68.3", + "@rollup/rollup-win32-x64-gnu": "4.68.3", + "@rollup/rollup-win32-x64-msvc": "4.68.3", + "fsevents": "~2.3.2" + } + }, + "node_modules/scheduler": { + "version": "0.23.2", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", + "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", + "license": "MIT", + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/semver": { + "version": "6.3.2", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.2.tgz", + "integrity": "sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/typescript": { + "version": "5.6.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.3.tgz", + "integrity": "sha512-hjcS1mhfuyi4WW8IWtjP7brDrG2cuDZukyrYrSauoXGNgx0S7zceP07adYkJycEr56BOUTNPzbInooiN3fn1qw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/vite": { + "version": "5.4.10", + "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.10.tgz", + "integrity": "sha512-1hvaPshuPUtxeQ0hsVH3Mud0ZanOLwVTneA1EgbAM5LhaZEqyPWGRQ7BtaMvUrTDeEaC8pxtj6a6jku3x4z6SQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "esbuild": "^0.21.3", + "postcss": "^8.4.43", + "rollup": "^4.20.0" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^18.0.0 || >=20.0.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^18.0.0 || >=20.0.0", + "less": "*", + "lightningcss": "^1.21.0", + "sass": "*", + "sass-embedded": "*", + "stylus": "*", + "sugarss": "*", + "terser": "^5.4.0" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "less": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + } + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + } + } +} diff --git a/discover/package.json b/discover/package.json new file mode 100644 index 0000000..960286c --- /dev/null +++ b/discover/package.json @@ -0,0 +1,23 @@ +{ + "name": "playlistd-discover", + "private": true, + "version": "0.1.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc --noEmit && vite build", + "preview": "vite preview" + }, + "dependencies": { + "react": "18.3.1", + "react-dom": "18.3.1" + }, + "devDependencies": { + "@types/node": "^22.9.0", + "@types/react": "18.3.12", + "@types/react-dom": "18.3.1", + "@vitejs/plugin-react": "4.3.3", + "typescript": "5.6.3", + "vite": "5.4.10" + } +} diff --git a/discover/src/App.tsx b/discover/src/App.tsx new file mode 100644 index 0000000..5a4e8d7 --- /dev/null +++ b/discover/src/App.tsx @@ -0,0 +1,230 @@ +import { useCallback, useEffect, useState } from "react"; +import { api, MixDetail, MixSummary, mixTitle, Rule, Suggestion, SuggestionStatus } from "./api"; +import { usePlayer } from "./usePlayer"; +import { MixView, hue } from "./MixView"; +import { LikedView } from "./LikedView"; +import { PlayerBar } from "./PlayerBar"; +import * as Icon from "./icons"; + +type Route = { view: "mix"; id?: string } | { view: "liked" }; + +function parseHash(): Route { + const [, view, id] = window.location.hash.split("/"); + return view === "liked" ? { view: "liked" } : { view: "mix", id: id || undefined }; +} + +type Toast = { message: string; undo?: () => void }; + +function storedRule() { + try { + return localStorage.getItem("discover.rule"); + } catch { + return null; + } +} + +export function App() { + const [rules, setRules] = useState(null); + const [ruleId, setRuleId] = useState(storedRule); + const [mixes, setMixes] = useState(null); + const [detail, setDetail] = useState(null); + const [liked, setLiked] = useState([]); + const [route, setRoute] = useState(parseHash); + const [error, setError] = useState(null); + const [toast, setToast] = useState(null); + + const player = usePlayer((item) => setToast({ message: `Couldn't play “${item.title}”` })); + const rule = rules?.find((r) => r.id === ruleId) ?? rules?.[0]; + + useEffect(() => { + const onHash = () => setRoute(parseHash()); + window.addEventListener("hashchange", onHash); + return () => window.removeEventListener("hashchange", onHash); + }, []); + + useEffect(() => { + if (!toast) return; + const t = window.setTimeout(() => setToast(null), toast.undo ? 6000 : 3500); + return () => window.clearTimeout(t); + }, [toast]); + + const loadRules = useCallback(() => { + api.rules().then(setRules, (e) => setError(`Couldn't reach playlistd (${e.message})`)); + }, []); + useEffect(loadRules, [loadRules]); + + const loadMixes = useCallback(() => { + if (!rule) return; + api.mixes(rule.id).then(setMixes, (e) => setError(e.message)); + api.liked(rule.id).then(setLiked, () => undefined); + }, [rule?.id]); // eslint-disable-line react-hooks/exhaustive-deps + useEffect(loadMixes, [loadMixes]); + + // mixes are built by the daemon; check back while they're pending + const pending = !!rule && (!rule.last_run || mixes?.length === 0); + useEffect(() => { + if (!pending) return; + const t = window.setInterval(() => { + loadRules(); + loadMixes(); + }, 10000); + return () => window.clearInterval(t); + }, [pending, loadRules, loadMixes]); + + const mixId = route.view === "mix" ? route.id ?? mixes?.[0]?.id : undefined; + const loadDetail = useCallback( + (quiet = false) => { + if (!mixId) return; + if (!quiet) setDetail((d) => (d?.id === mixId ? d : null)); + api.mix(mixId).then(setDetail, (e) => !quiet && setError(`Couldn't load mix (${e.message})`)); + }, + [mixId], + ); + useEffect(() => loadDetail(), [loadDetail]); + + // pick up YouTube links once a new song has been found and starts playing + useEffect(() => { + if (player.status === "playing" && player.current?.source === "youtube") { + loadDetail(true); + if (rule) api.liked(rule.id).then(setLiked, () => undefined); + } + }, [player.status, player.current?.key]); // eslint-disable-line react-hooks/exhaustive-deps + + const updateLocal = (id: string, status: SuggestionStatus, previous?: Suggestion) => { + setDetail((d) => { + if (!d) return d; + const suggestions = + status === "dismissed" + ? d.suggestions.filter((s) => s.id !== id) + : d.suggestions.some((s) => s.id === id) + ? d.suggestions.map((s) => (s.id === id ? { ...s, status } : s)) + : previous && previous.mix_id === d.id + ? [...d.suggestions, { ...previous, status }].sort((a, b) => b.score - a.score) + : d.suggestions; + return { ...d, suggestions }; + }); + setLiked((l) => { + const without = l.filter((s) => s.id !== id); + const item = previous ?? l.find((s) => s.id === id); + return status === "liked" && item ? [{ ...item, status }, ...without] : without; + }); + }; + + const onStatus = (s: Suggestion, status: SuggestionStatus) => { + updateLocal(s.id, status, s); + api.setStatus(s.id, status).then( + () => { + loadMixes(); + if (status === "dismissed") { + setToast({ + message: `Hid “${s.title}”`, + undo: () => { + updateLocal(s.id, s.status, s); + api.setStatus(s.id, s.status).then(loadMixes); + setToast(null); + }, + }); + } + }, + () => { + updateLocal(s.id, s.status, s); + setToast({ message: "Couldn't save that, try again" }); + }, + ); + }; + + const rebuild = () => { + if (!rule) return; + api.rebuild(rule.id).then(() => { + setToast({ message: "Rebuilding mixes. This takes a minute or two." }); + loadRules(); + }); + }; + + return ( +
+ + +
+ {error &&
{error}
} + {rules && rules.length === 0 && ( +
+

No mix rules yet

+

Create one, and playlistd will cluster your listens into genre mixes:

+
{`curl -X POST /api/playlist/mix -H 'Content-Type: application/json' \\\n  -d '{"tracking_user": "your-listenbrainz-name"}'`}
+
+ )} + {pending && mixes?.length === 0 && ( +
Building mixes from your recent listens…
+ )} + {route.view === "liked" ? ( + + ) : detail ? ( + + ) : ( + mixId &&
Loading…
+ )} +
+ + + + {toast && ( +
+ {toast.message} + {toast.undo && } +
+ )} +
+ ); +} diff --git a/discover/src/LikedView.tsx b/discover/src/LikedView.tsx new file mode 100644 index 0000000..41e0b71 --- /dev/null +++ b/discover/src/LikedView.tsx @@ -0,0 +1,47 @@ +import { useMemo } from "react"; +import { Suggestion, SuggestionStatus } from "./api"; +import { fromSuggestion } from "./queue"; +import { Player } from "./usePlayer"; +import { TrackRow } from "./TrackRow"; +import { SuggestionActions } from "./MixView"; +import * as Icon from "./icons"; + +type Props = { + liked: Suggestion[]; + player: Player; + onStatus: (s: Suggestion, status: SuggestionStatus) => void; +}; + +export function LikedView({ liked, player, onStatus }: Props) { + const items = useMemo(() => liked.map(fromSuggestion), [liked]); + return ( +
+
+ +
+

Collection

+

Liked new songs

+

Songs you liked that aren't in your library yet: a shopping list.

+
+ +
+
+
+
+ {items.length === 0 ? ( +

Nothing yet. Tap the heart on a new song to keep it here.

+ ) : ( +
    + {liked.map((s, i) => ( + player.playAt(items, i)} + actions={} /> + ))} +
+ )} +
+
+ ); +} diff --git a/discover/src/MixView.tsx b/discover/src/MixView.tsx new file mode 100644 index 0000000..0c50787 --- /dev/null +++ b/discover/src/MixView.tsx @@ -0,0 +1,121 @@ +import { useMemo } from "react"; +import { MixDetail, mixTitle, Suggestion, SuggestionStatus } from "./api"; +import { fromSong, fromSuggestion, interleave, QueueItem } from "./queue"; +import { Player } from "./usePlayer"; +import { TrackRow } from "./TrackRow"; +import * as Icon from "./icons"; + +export function hue(text: string) { + let h = 0; + for (const c of text) h = (h * 31 + c.charCodeAt(0)) % 360; + return h; +} + +export function SuggestionActions({ s, onStatus }: { s: Suggestion; onStatus: (s: Suggestion, status: SuggestionStatus) => void }) { + const liked = s.status === "liked"; + return ( + <> + + {s.youtube_id ? ( + + ) : ( + + )} + {s.status !== "liked" && ( + + )} + + ); +} + +type Props = { + mix: MixDetail; + player: Player; + onStatus: (s: Suggestion, status: SuggestionStatus) => void; +}; + +export function MixView({ mix, player, onStatus }: Props) { + const fresh = useMemo(() => mix.suggestions.map(fromSuggestion), [mix.suggestions]); + const library = useMemo(() => mix.songs.map(fromSong), [mix.songs]); + // clicking a row plays through everything shown, new songs first + const all = useMemo(() => [...fresh, ...library], [fresh, library]); + const title = mixTitle(mix); + const h = hue(mix.tags.join()); + + const play = (items: QueueItem[], at = 0) => items.length && player.playAt(items, at); + const isActive = (item: QueueItem) => player.current?.key === item.key; + + return ( +
+
+ +
+

Mix

+

{title}

+
    + {mix.tags.map((t) =>
  • {t}
  • )} +
+

+ {mix.songs.length} from your library · {mix.suggestions.length} new +

+
+ + +
+
+
+ +
+

New for you

+ {fresh.length === 0 ? ( +

No new songs for this mix yet. They're found when the mixes are rebuilt.

+ ) : ( +
    + {mix.suggestions.map((s, i) => ( + play(all, i)} + meta={{Math.round(s.score * 100)}% match} + actions={} + /> + ))} +
+ )} +
+ +
+

From your library

+
    + {mix.songs.map((song, i) => ( + play(all, fresh.length + i)} + duration={song.duration} + /> + ))} +
+
+
+ ); +} diff --git a/discover/src/PlayerBar.tsx b/discover/src/PlayerBar.tsx new file mode 100644 index 0000000..0be9a1e --- /dev/null +++ b/discover/src/PlayerBar.tsx @@ -0,0 +1,55 @@ +import { Player } from "./usePlayer"; +import { Cover, formatTime } from "./TrackRow"; +import * as Icon from "./icons"; + +export function PlayerBar({ player }: { player: Player }) { + const { current, status, time, duration } = player; + if (!current) return null; + const label = + status === "loading" + ? current.source === "youtube" ? "Finding on YouTube…" : "Loading…" + : status === "error" ? "Couldn't play this one, skipping" : null; + + return ( +
+
+ +
+
{current.title}
+
{current.artist}
+
+ + {current.source === "youtube" ? "YouTube" : "Library"} + +
+
+
+ + + +
+
+ {formatTime(time) || "0:00"} + player.seek(Number(e.target.value))} + aria-label="Seek" + style={{ ["--progress" as string]: `${duration ? (time / duration) * 100 : 0}%` }} + /> + {formatTime(duration)} +
+ {label &&
{label}
} +
+
+ {player.index + 1} / {player.queue.length} +
+
+ ); +} diff --git a/discover/src/TrackRow.tsx b/discover/src/TrackRow.tsx new file mode 100644 index 0000000..5602d2a --- /dev/null +++ b/discover/src/TrackRow.tsx @@ -0,0 +1,56 @@ +import { ReactNode } from "react"; +import { QueueItem } from "./queue"; +import { PlayerStatus } from "./usePlayer"; +import * as Icon from "./icons"; + +export function formatTime(seconds?: number) { + if (!seconds || !Number.isFinite(seconds)) return ""; + const s = Math.floor(seconds); + return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`; +} + +export function Cover({ src, label, size = 44 }: { src?: string | null; label: string; size?: number }) { + return ( + + ); +} + +type Props = { + item: QueueItem; + number: number; + active: boolean; + status: PlayerStatus; + onPlay: () => void; + meta?: ReactNode; + actions?: ReactNode; + duration?: number; +}; + +export function TrackRow({ item, number, active, status, onPlay, meta, actions, duration }: Props) { + const loading = active && status === "loading"; + const playing = active && status === "playing"; + return ( +
  • + + +
    +
    {item.title}
    +
    + {item.artist} + {item.album && · {item.album}} +
    +
    + {meta &&
    {meta}
    } +
    {formatTime(duration)}
    + {actions &&
    {actions}
    } +
  • + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts new file mode 100644 index 0000000..632b95f --- /dev/null +++ b/discover/src/api.ts @@ -0,0 +1,75 @@ +export type Rule = { + id: string; + tracking_user: string; + months: number; + playlist_size: number; + discovery_count: number; + last_run: string | null; +}; + +export type MixSummary = { + id: string; + playlist_id: string; + name: string | null; + tags: string[]; + position: number; + new_count: number; +}; + +export type Song = { + id: string; + title: string; + artist: string; + album: string; + duration?: number; + coverArt?: string; +}; + +export type SuggestionStatus = "new" | "liked" | "dismissed"; + +export type Suggestion = { + id: string; + mix_id: string | null; + recording_mbid: string; + title: string; + artist: string; + release: string | null; + cover_url: string | null; + score: number; + status: SuggestionStatus; + youtube_id: string | null; +}; + +export type MixDetail = MixSummary & { songs: Song[]; suggestions: Suggestion[] }; + +async function request(path: string, init?: RequestInit): Promise { + const response = await fetch(`/api/discover${path}`, init); + if (!response.ok) { + throw new Error(`${response.status} ${response.statusText}`); + } + return response.json(); +} + +export const api = { + rules: () => request("/rules"), + mixes: (ruleId: string) => request(`/rules/${ruleId}/mixes`), + mix: (mixId: string) => request(`/mixes/${mixId}`), + liked: (ruleId: string) => request(`/rules/${ruleId}/liked`), + setStatus: (id: string, status: SuggestionStatus) => + request(`/suggestions/${id}`, { + method: "PUT", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ status }), + }), + rebuild: (ruleId: string) => + fetch(`/api/discover/rules/${ruleId}/rebuild`, { method: "POST" }), +}; + +export const coverUrl = (coverArt: string, size = 120) => + `/api/discover/cover/${encodeURIComponent(coverArt)}?size=${size}`; +export const streamUrl = (songId: string) => `/api/discover/stream/${encodeURIComponent(songId)}`; +export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${suggestionId}`; + +/** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */ +export const mixTitle = (mix: MixSummary) => + (mix.name ?? mix.tags.join(" / ")).replace(/^mix:\s*/i, ""); diff --git a/discover/src/icons.tsx b/discover/src/icons.tsx new file mode 100644 index 0000000..72ae65e --- /dev/null +++ b/discover/src/icons.tsx @@ -0,0 +1,16 @@ +type P = { size?: number }; +const svg = (path: JSX.Element, size = 18) => ( + +); +export const Play = ({ size }: P) => svg(, size); +export const Pause = ({ size }: P) => svg(<>, size); +export const Next = ({ size }: P) => svg(<>, size); +export const Prev = ({ size }: P) => svg(<>, size); +export const Heart = ({ size, filled }: P & { filled?: boolean }) => svg(, size); +export const Close = ({ size }: P) => svg(, size); +export const External = ({ size }: P) => svg(<>, size); +export const Refresh = ({ size }: P) => svg(<>, size); +export const Sparkle = ({ size }: P) => svg(, size); +export const Library = ({ size }: P) => svg(<>, size); +export const Shuffle = ({ size }: P) => svg(<>, size); diff --git a/discover/src/main.tsx b/discover/src/main.tsx new file mode 100644 index 0000000..71c1087 --- /dev/null +++ b/discover/src/main.tsx @@ -0,0 +1,10 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; +import { App } from "./App"; +import "./styles.css"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/discover/src/queue.ts b/discover/src/queue.ts new file mode 100644 index 0000000..335abe6 --- /dev/null +++ b/discover/src/queue.ts @@ -0,0 +1,47 @@ +import { coverUrl, Song, streamUrl, Suggestion, youtubeUrl } from "./api"; + +export type QueueItem = { + key: string; + source: "library" | "youtube"; + src: string; + title: string; + artist: string; + album?: string | null; + cover?: string | null; + suggestionId?: string; +}; + +export const fromSong = (song: Song): QueueItem => ({ + key: `song:${song.id}`, + source: "library", + src: streamUrl(song.id), + title: song.title, + artist: song.artist, + album: song.album, + cover: song.coverArt ? coverUrl(song.coverArt, 300) : null, +}); + +export const fromSuggestion = (s: Suggestion): QueueItem => ({ + key: `suggestion:${s.id}`, + source: "youtube", + src: youtubeUrl(s.id), + title: s.title, + artist: s.artist, + album: s.release, + cover: s.cover_url, + suggestionId: s.id, +}); + +/** Spread new songs evenly through the library songs */ +export function interleave(library: QueueItem[], fresh: QueueItem[]): QueueItem[] { + if (fresh.length === 0) return library; + const out: QueueItem[] = []; + const every = Math.max(1, Math.round((library.length + fresh.length) / fresh.length)); + let l = 0; + let f = 0; + for (let i = 0; l < library.length || f < fresh.length; i++) { + const takeFresh = (i % every === every - 1 && f < fresh.length) || l >= library.length; + out.push(takeFresh ? fresh[f++] : library[l++]); + } + return out; +} diff --git a/discover/src/styles.css b/discover/src/styles.css new file mode 100644 index 0000000..cd11e9b --- /dev/null +++ b/discover/src/styles.css @@ -0,0 +1,824 @@ +:root { + --bg: #f6f5f2; + --surface: #ffffff; + --surface-2: #efede8; + --border: #e2dfd8; + --text: #1d1b18; + --muted: #6d675e; + --accent: #5b3df5; + --accent-text: #ffffff; + --youtube: #d4351c; + --library: #2f7d4f; + --heart: #e0245e; + --shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%); + --art-l: 62%; + --art-s: 70%; + --radius: 12px; + font-family: "Inter", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; + font-size: 15px; + line-height: 1.45; + color: var(--text); + background: var(--bg); + -webkit-font-smoothing: antialiased; +} + +@media (prefers-color-scheme: dark) { + :root { + --bg: #121214; + --surface: #1b1b1f; + --surface-2: #26262b; + --border: #2e2e34; + --text: #f1f0ee; + --muted: #a09d98; + --accent: #8b74ff; + --accent-text: #120d26; + --youtube: #ff6b52; + --library: #5fcf8d; + --heart: #ff5c8a; + --shadow: 0 1px 2px rgb(0 0 0 / 30%), 0 8px 24px rgb(0 0 0 / 30%); + --art-l: 45%; + --art-s: 55%; + } +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + background: var(--bg); +} + +button, +select, +input { + font: inherit; + color: inherit; +} + +a { + color: inherit; +} + +:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; +} + +/* ---------- layout ---------- */ + +.app { + display: grid; + grid-template-columns: 272px minmax(0, 1fr); + min-height: 100vh; +} + +.sidebar { + position: sticky; + top: 0; + height: 100vh; + overflow-y: auto; + padding: 20px 12px; + border-right: 1px solid var(--border); + background: var(--surface); +} + +.with-player .sidebar { + height: calc(100vh - 84px); +} + +.content { + padding: 28px clamp(16px, 4vw, 48px) 48px; + min-width: 0; +} + +.with-player .content { + padding-bottom: 120px; +} + +.brand { + display: flex; + align-items: center; + gap: 10px; + padding: 0 10px 16px; + font-weight: 700; + font-size: 1.15rem; + letter-spacing: -0.01em; +} + +.brand-mark { + display: grid; + place-items: center; + width: 28px; + height: 28px; + border-radius: 8px; + background: var(--accent); + color: var(--accent-text); +} + +.rule-select { + width: calc(100% - 20px); + margin: 0 10px 8px; + padding: 6px 8px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface-2); +} + +.rule-info { + display: flex; + align-items: center; + justify-content: space-between; + margin: 0 0 8px; + padding: 0 4px 0 10px; + color: var(--muted); + font-size: 0.85rem; +} + +.mix-list { + list-style: none; + margin: 0; + padding: 0; +} + +.mix-list a { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + border-radius: 8px; + text-decoration: none; + color: var(--text); +} + +.mix-list a:hover { + background: var(--surface-2); +} + +.mix-list a.selected { + background: hsl(var(--hue) var(--art-s) var(--art-l) / 18%); +} + +.mix-dot { + flex: none; + width: 12px; + height: 12px; + border-radius: 4px; + background: linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 12%))); +} + +.mix-dot.heart { + display: grid; + place-items: center; + background: none; + color: var(--heart); +} + +.mix-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 0.93rem; +} + +.count { + flex: none; + min-width: 22px; + padding: 1px 7px; + border-radius: 999px; + background: var(--accent); + color: var(--accent-text); + font-size: 0.75rem; + font-weight: 600; + text-align: center; +} + +.liked-link { + margin-top: 10px; + padding-top: 10px; + border-top: 1px solid var(--border); +} + +/* ---------- mix header ---------- */ + +.mix-header { + display: flex; + gap: 28px; + align-items: flex-end; + margin-bottom: 32px; +} + +.mix-art { + flex: none; + display: grid; + place-items: end start; + width: 200px; + height: 200px; + padding: 18px; + border-radius: 16px; + background: + radial-gradient(circle at 80% 15%, hsl(calc(var(--hue) + 60) 90% 75% / 70%), transparent 55%), + linear-gradient(135deg, hsl(var(--hue) var(--art-s) var(--art-l)), hsl(calc(var(--hue) + 40) var(--art-s) calc(var(--art-l) - 18%))); + color: #fff; + box-shadow: var(--shadow); + font-weight: 800; + font-size: 1.5rem; + line-height: 1.1; + letter-spacing: -0.02em; + text-shadow: 0 1px 8px rgb(0 0 0 / 25%); + overflow-wrap: anywhere; +} + +.liked-view .mix-art { + place-items: center; +} + +.mix-info { + min-width: 0; +} + +.eyebrow { + margin: 0 0 4px; + color: var(--muted); + font-size: 0.78rem; + font-weight: 600; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +h1 { + margin: 0 0 12px; + font-size: clamp(1.6rem, 3.4vw, 2.6rem); + line-height: 1.1; + letter-spacing: -0.025em; +} + +.tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0 0 12px; + padding: 0; + list-style: none; +} + +.tags li { + padding: 2px 10px; + border-radius: 999px; + background: hsl(var(--hue) var(--art-s) var(--art-l) / 16%); + font-size: 0.82rem; +} + +.mix-counts { + margin: 0 0 16px; + color: var(--muted); + font-size: 0.9rem; +} + +.mix-buttons { + display: flex; + flex-wrap: wrap; + gap: 8px; +} + +.mix-buttons button { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 9px 16px; + border: 1px solid var(--border); + border-radius: 999px; + background: var(--surface); + font-weight: 600; + cursor: pointer; +} + +.mix-buttons button.primary { + border-color: transparent; + background: var(--accent); + color: var(--accent-text); +} + +.mix-buttons button:disabled { + opacity: 0.5; + cursor: default; +} + +/* ---------- track lists ---------- */ + +section + section { + margin-top: 32px; +} + +h2 { + display: flex; + align-items: center; + gap: 8px; + margin: 0 0 8px; + font-size: 1.05rem; +} + +.empty { + color: var(--muted); +} + +.tracks { + margin: 0; + padding: 0; + list-style: none; +} + +.track { + display: grid; + grid-template-columns: 36px 44px minmax(0, 1fr) auto auto auto; + align-items: center; + gap: 12px; + padding: 6px 8px; + border-radius: 10px; +} + +.track:hover, +.track.active { + background: var(--surface); +} + +.track.active { + box-shadow: inset 3px 0 0 var(--accent); +} + +.track-play { + display: grid; + place-items: center; + width: 32px; + height: 32px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + cursor: pointer; +} + +.track-icon { + display: none; +} + +.track:hover .track-number, +.track.active .track-number { + display: none; +} + +.track:hover .track-icon, +.track.active .track-icon, +.track-play:focus-visible .track-icon { + display: grid; + place-items: center; + color: var(--accent); +} + +.track-play:focus-visible .track-number { + display: none; +} + +.track-number { + color: var(--muted); + font-variant-numeric: tabular-nums; + font-size: 0.85rem; +} + +.cover { + position: relative; + display: grid; + place-items: center; + overflow: hidden; + border-radius: 6px; + background: var(--surface-2); + color: var(--muted); + font-weight: 700; +} + +.cover img { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + object-fit: cover; +} + +.track-text { + min-width: 0; +} + +.track-title, +.track-sub { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.track-title { + font-weight: 600; +} + +.track.active .track-title { + color: var(--accent); +} + +.track-sub { + color: var(--muted); + font-size: 0.88rem; +} + +.match { + color: var(--muted); + font-size: 0.82rem; + font-variant-numeric: tabular-nums; + white-space: nowrap; +} + +.track-duration { + color: var(--muted); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +.track-actions { + display: flex; + gap: 2px; +} + +.icon-button { + display: inline-grid; + place-items: center; + width: 34px; + height: 34px; + padding: 0; + border: 0; + border-radius: 50%; + background: none; + color: var(--muted); + cursor: pointer; +} + +.icon-button.small { + width: 28px; + height: 28px; +} + +.icon-button:hover { + background: var(--surface-2); + color: var(--text); +} + +.icon-button.liked { + color: var(--heart); +} + +/* ---------- player ---------- */ + +.player { + position: fixed; + inset: auto 0 0 0; + z-index: 10; + display: grid; + grid-template-columns: minmax(0, 1fr) minmax(0, 1.4fr) minmax(0, 1fr); + align-items: center; + gap: 20px; + height: 84px; + padding: 0 20px; + border-top: 1px solid var(--border); + background: color-mix(in srgb, var(--surface) 92%, transparent); + backdrop-filter: blur(12px); +} + +.player-track { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; +} + +.badge { + flex: none; + padding: 1px 8px; + border-radius: 999px; + border: 1px solid currentColor; + font-size: 0.72rem; + font-weight: 600; +} + +.badge.youtube { + color: var(--youtube); +} + +.badge.library { + color: var(--library); +} + +.player-main { + position: relative; + display: flex; + flex-direction: column; + align-items: center; + gap: 4px; +} + +.player-buttons { + display: flex; + align-items: center; + gap: 10px; +} + +.play-button { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border: 0; + border-radius: 50%; + background: var(--text); + color: var(--bg); + cursor: pointer; +} + +.player-progress { + display: flex; + align-items: center; + gap: 10px; + width: 100%; + color: var(--muted); + font-size: 0.75rem; + font-variant-numeric: tabular-nums; +} + +.player-progress span { + width: 38px; + text-align: center; +} + +.player-progress input { + flex: 1; + height: 4px; + appearance: none; + border-radius: 2px; + background: linear-gradient(to right, var(--accent) var(--progress), var(--border) var(--progress)); + cursor: pointer; +} + +.player-progress input::-webkit-slider-thumb { + appearance: none; + width: 12px; + height: 12px; + border-radius: 50%; + background: var(--text); +} + +.player-progress input::-moz-range-thumb { + width: 12px; + height: 12px; + border: 0; + border-radius: 50%; + background: var(--text); +} + +.player-status { + position: absolute; + top: -26px; + padding: 2px 10px; + border-radius: 999px; + background: var(--surface-2); + font-size: 0.78rem; + white-space: nowrap; +} + +.player-status.error { + color: var(--youtube); +} + +.player-queue { + justify-self: end; + color: var(--muted); + font-size: 0.85rem; + font-variant-numeric: tabular-nums; +} + +/* ---------- feedback ---------- */ + +.spinner { + display: inline-block; + width: 16px; + height: 16px; + border: 2px solid var(--border); + border-top-color: var(--accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; + vertical-align: middle; +} + +.spinner.light { + border-color: color-mix(in srgb, var(--bg) 35%, transparent); + border-top-color: var(--bg); +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +.bars { + display: flex; + align-items: flex-end; + gap: 2px; + height: 14px; +} + +.bars i { + width: 3px; + background: var(--accent); + animation: bar 0.9s ease-in-out infinite; +} + +.bars i:nth-child(2) { + animation-delay: -0.3s; +} + +.bars i:nth-child(3) { + animation-delay: -0.6s; +} + +@keyframes bar { + 0%, + 100% { + height: 30%; + } + 50% { + height: 100%; + } +} + +@media (prefers-reduced-motion: reduce) { + .bars i, + .spinner { + animation: none; + } +} + +.notice { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 24px; + padding: 16px 20px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.notice.error { + border-color: var(--youtube); + color: var(--youtube); +} + +.notice pre { + overflow-x: auto; + margin: 0; + padding: 12px; + border-radius: 8px; + background: var(--surface-2); + font-size: 0.85rem; +} + +.toast { + position: fixed; + left: 50%; + bottom: 104px; + z-index: 20; + display: flex; + align-items: center; + gap: 14px; + max-width: calc(100vw - 32px); + padding: 10px 16px; + border-radius: 10px; + background: var(--text); + color: var(--bg); + box-shadow: var(--shadow); + transform: translateX(-50%); +} + +.app:not(.with-player) .toast { + bottom: 24px; +} + +.toast button { + border: 0; + background: none; + color: var(--accent); + font-weight: 700; + cursor: pointer; +} + +/* ---------- small screens ---------- */ + +@media (max-width: 800px) { + .app { + grid-template-columns: minmax(0, 1fr); + } + + .sidebar, + .with-player .sidebar { + position: static; + height: auto; + padding: 14px 16px 10px; + border-right: 0; + border-bottom: 1px solid var(--border); + } + + .brand { + padding: 0 0 10px; + } + + .rule-info { + padding: 0; + } + + .mix-list { + display: flex; + gap: 6px; + overflow-x: auto; + margin: 0 -16px; + padding: 0 16px 4px; + scrollbar-width: none; + } + + .mix-list a { + border: 1px solid var(--border); + border-radius: 999px; + padding: 6px 12px; + } + + .mix-name { + overflow: visible; + } + + .liked-link { + margin: 0; + padding: 0; + border: 0; + } + + .content { + padding: 20px 16px 40px; + } + + .mix-header { + flex-direction: column; + align-items: stretch; + gap: 18px; + } + + .mix-art { + width: 100%; + height: 140px; + } + + .track { + grid-template-columns: 32px 40px minmax(0, 1fr) auto; + gap: 10px; + padding: 6px 0; + } + + .track-meta, + .track-duration, + .track-album { + display: none; + } + + .player { + grid-template-columns: minmax(0, 1fr) auto; + height: auto; + padding: 10px 16px; + gap: 12px; + } + + .player-main { + flex-direction: row-reverse; + } + + .player-progress, + .player-queue, + .player .badge { + display: none; + } + + .player-status { + right: 0; + top: -38px; + } + + .with-player .content { + padding-bottom: 110px; + } +} diff --git a/discover/src/usePlayer.ts b/discover/src/usePlayer.ts new file mode 100644 index 0000000..efb5ead --- /dev/null +++ b/discover/src/usePlayer.ts @@ -0,0 +1,124 @@ +import { useCallback, useEffect, useRef, useState } from "react"; +import { QueueItem } from "./queue"; + +export type PlayerStatus = "idle" | "loading" | "playing" | "paused" | "error"; + +export type Player = ReturnType; + +export function usePlayer(onError: (item: QueueItem) => void) { + const audio = useRef(null); + if (audio.current === null && typeof Audio !== "undefined") { + audio.current = new Audio(); + audio.current.preload = "auto"; + } + + const [queue, setQueue] = useState([]); + const [index, setIndex] = useState(-1); + const [status, setStatus] = useState("idle"); + const [time, setTime] = useState(0); + const [duration, setDuration] = useState(0); + const current = index >= 0 ? queue[index] : undefined; + + // keep the latest values for the audio element's event handlers + const state = useRef({ queue, index, onError }); + state.current = { queue, index, onError }; + + const playAt = useCallback((items: QueueItem[], at: number) => { + setQueue(items); + setIndex(at); + }, []); + + const next = useCallback(() => { + const { queue, index } = state.current; + if (index + 1 < queue.length) setIndex(index + 1); + else { + audio.current?.pause(); + setStatus("paused"); + } + }, []); + + const previous = useCallback(() => { + const el = audio.current; + if (el && el.currentTime > 3) el.currentTime = 0; + else setIndex((i) => Math.max(0, i - 1)); + }, []); + + const toggle = useCallback(() => { + const el = audio.current; + if (!el || !state.current.queue.length) return; + if (el.paused) void el.play().catch(() => undefined); + else el.pause(); + }, []); + + const seek = useCallback((seconds: number) => { + if (!audio.current) return; + audio.current.currentTime = seconds; + // update now, or the controlled slider snaps back and its change event seeks back too + setTime(seconds); + }, []); + + // load the current item + useEffect(() => { + const el = audio.current; + if (!el || !current) return; + setTime(0); + setDuration(0); + setStatus("loading"); + el.src = current.src; + void el.play().catch(() => undefined); + }, [current?.key]); // eslint-disable-line react-hooks/exhaustive-deps + + useEffect(() => { + const el = audio.current; + if (!el) return; + let errorTimer: number | undefined; + const handlers: Record void> = { + playing: () => setStatus("playing"), + pause: () => setStatus((s) => (s === "error" ? s : "paused")), + waiting: () => setStatus("loading"), + timeupdate: () => setTime(el.currentTime), + durationchange: () => setDuration(Number.isFinite(el.duration) ? el.duration : 0), + ended: () => next(), + error: () => { + if (!el.src) return; + setStatus("error"); + const { queue, index, onError } = state.current; + if (queue[index]) onError(queue[index]); + errorTimer = window.setTimeout(next, 1500); + }, + }; + for (const [event, handler] of Object.entries(handlers)) el.addEventListener(event, handler); + return () => { + window.clearTimeout(errorTimer); + for (const [event, handler] of Object.entries(handlers)) el.removeEventListener(event, handler); + }; + }, [next]); + + // OS media controls and keyboard + useEffect(() => { + if (!("mediaSession" in navigator) || !current) return; + navigator.mediaSession.metadata = new MediaMetadata({ + title: current.title, + artist: current.artist, + album: current.album ?? undefined, + artwork: current.cover ? [{ src: current.cover }] : [], + }); + navigator.mediaSession.setActionHandler("play", toggle); + navigator.mediaSession.setActionHandler("pause", toggle); + navigator.mediaSession.setActionHandler("nexttrack", next); + navigator.mediaSession.setActionHandler("previoustrack", previous); + }, [current, toggle, next, previous]); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + const target = e.target as HTMLElement; + if (e.code !== "Space" || ["INPUT", "TEXTAREA", "BUTTON"].includes(target.tagName)) return; + e.preventDefault(); + toggle(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [toggle]); + + return { queue, index, current, status, time, duration, playAt, next, previous, toggle, seek }; +} diff --git a/discover/tsconfig.json b/discover/tsconfig.json new file mode 100644 index 0000000..4515ae8 --- /dev/null +++ b/discover/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "skipLibCheck": true, + "isolatedModules": true, + "noEmit": true + }, + "include": ["src", "vite.config.ts"] +} diff --git a/discover/vite.config.ts b/discover/vite.config.ts new file mode 100644 index 0000000..019b8d4 --- /dev/null +++ b/discover/vite.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "vite"; +import react from "@vitejs/plugin-react"; + +// During development, API requests go to playlistd (PLAYLISTD_URL, default localhost:8000) +export default defineConfig({ + plugins: [react()], + server: { + proxy: { + "/api": process.env.PLAYLISTD_URL ?? "http://localhost:8000", + }, + }, +}); diff --git a/etc/playlistd/playlistd.toml b/etc/playlistd/playlistd.toml index 3ce6e9a..6301899 100644 --- a/etc/playlistd/playlistd.toml +++ b/etc/playlistd/playlistd.toml @@ -13,3 +13,17 @@ interval = 240 [database] # URL of database to use 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 +# token = "" + +[discover] +# Directory with the built discover UI (discover/dist) to serve at / +# ui = "/usr/share/playlistd/discover" +# yt-dlp binary used to play suggested songs that aren't in your library +# ytdlp = "yt-dlp" +# 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/20261113180000_mix_suggestions.sql b/migrations/20261113180000_mix_suggestions.sql new file mode 100644 index 0000000..c560163 --- /dev/null +++ b/migrations/20261113180000_mix_suggestions.sql @@ -0,0 +1,24 @@ +ALTER TABLE "cluster_mix_rule" + ADD COLUMN discovery_count INT NOT NULL DEFAULT 15; -- New songs to suggest per mix + +ALTER TABLE "cluster_mix_playlist" + ADD COLUMN name VARCHAR(250), -- Name of the playlist in subsonic + ADD COLUMN position INT NOT NULL DEFAULT 0; -- Order of the mix, most listened first + +-- Songs not in the library, recommended by Listenbrainz and matched to a mix by genre +CREATE TABLE "mix_suggestion" +( + id UUID NOT NULL PRIMARY KEY, + rule_id UUID NOT NULL REFERENCES "cluster_mix_rule" (id) ON DELETE CASCADE, + mix_id UUID REFERENCES "cluster_mix_playlist" (id) ON DELETE SET NULL, + recording_mbid VARCHAR(36) NOT NULL, + title VARCHAR(500) NOT NULL, + artist VARCHAR(500) NOT NULL, + release VARCHAR(500), + cover_url TEXT, + score DOUBLE PRECISION NOT NULL, + status VARCHAR(16) NOT NULL DEFAULT 'new', -- new, liked or dismissed + youtube_id VARCHAR(32), -- Cached YouTube match + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + UNIQUE (rule_id, recording_mbid) +); diff --git a/src/daemon/cluster_mixes.rs b/src/daemon/cluster_mixes.rs index d97dfc7..c615f46 100644 --- a/src/daemon/cluster_mixes.rs +++ b/src/daemon/cluster_mixes.rs @@ -1,4 +1,5 @@ use crate::cluster::{self, ClusterOptions, Play}; +use crate::discover::{self, MixTarget}; use crate::listenbrainz; use crate::mix::{self, ListenedTrack, MixOptions, RecentlyPlayed}; use crate::models::{ClusterMixPlaylist, ClusterMixRule}; @@ -8,7 +9,7 @@ use chrono::Utc; use rand::rngs::StdRng; use rand::SeedableRng; use sqlx::postgres::PgPool; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::time::Duration; use tokio::time::{interval, MissedTickBehavior}; use uuid::Uuid; @@ -142,7 +143,7 @@ pub async fn build_mixes( ) .await? { - Some(mix) => mixes.push(mix), + Some(mix) => mixes.push((mix, cluster)), None => println!( "No library genres match cluster {:?}", cluster @@ -157,7 +158,7 @@ pub async fn build_mixes( // two clusters can share their top genres let mut seen_labels: HashMap = HashMap::new(); - for mix in &mut mixes { + for (mix, _) in &mut mixes { let n = seen_labels.entry(mix.label.clone()).or_default(); *n += 1; if *n > 1 { @@ -176,12 +177,17 @@ pub async fn build_mixes( let pairs = mix::match_mixes( &existing.iter().map(|p| p.tags.clone()).collect::>(), - &mixes.iter().map(|m| m.tags.clone()).collect::>(), + &mixes + .iter() + .map(|(m, _)| m.tags.clone()) + .collect::>(), ); let old_for_new: HashMap = pairs.iter().map(|&(o, n)| (n, o)).collect(); - for (n, mix) in mixes.iter().enumerate() { + let mut targets = vec![]; + for (n, (mix, cluster)) in mixes.iter().enumerate() { let name = rule.name_template.replace("{label}", &mix.label); + let position = n as i32; let reused = match old_for_new.get(&n).map(|&o| &existing[o]) { // the playlist may have been deleted by hand since the last run @@ -190,13 +196,15 @@ pub async fn build_mixes( .rename_playlist(&old.playlist_id, &name) .await?; sqlx::query!( - r#"UPDATE "cluster_mix_playlist" SET tags = $1 WHERE id = $2"#, + r#"UPDATE "cluster_mix_playlist" SET tags = $1, name = $2, position = $3 WHERE id = $4"#, &mix.tags, + name, + position, old.id ) .execute(database) .await?; - Some(old.playlist_id.clone()) + Some((old.id, old.playlist_id.clone())) } Some(old) => { sqlx::query!( @@ -210,25 +218,32 @@ pub async fn build_mixes( None => None, }; - let playlist_id = match reused { - Some(id) => id, + let (mix_id, playlist_id) = match reused { + Some(ids) => ids, None => { let playlist = media_client.create_playlist(&name).await?; + let mix_id = Uuid::new_v4(); sqlx::query!( r#" - INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags) - VALUES ($1, $2, $3, $4) + INSERT INTO "cluster_mix_playlist" (id, rule_id, playlist_id, tags, name, position) + VALUES ($1, $2, $3, $4, $5, $6) "#, - Uuid::new_v4(), + mix_id, rule.id, playlist.id, &mix.tags, + name, + position, ) .execute(database) .await?; - playlist.id + (mix_id, playlist.id) } }; + targets.push(MixTarget { + mix_id, + profile: cluster.profile.clone(), + }); media_client .replace_playlist_songs(&playlist_id, mix.song_ids.clone()) @@ -252,6 +267,17 @@ pub async fn build_mixes( } } + // ---- songs that aren't in the library ---- + // a failure here shouldn't stop the mixes from being marked as built + if let Err(e) = + save_suggestions(media_client, &rule, &targets, &recently_played, database).await + { + println!( + "Could not find new songs for {}: {:?}", + rule.tracking_user, e + ); + } + sqlx::query!( r#"UPDATE "cluster_mix_rule" SET last_run = NOW() WHERE id = $1"#, rule.id @@ -261,3 +287,70 @@ pub async fn build_mixes( Ok(()) } + +async fn save_suggestions( + media_client: &Subsonic, + rule: &ClusterMixRule, + targets: &[MixTarget], + recently_played: &RecentlyPlayed, + database: &PgPool, +) -> Result<(), Box> { + // liked and dismissed 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 + ) + .fetch_all(database) + .await? + .into_iter() + .collect(); + + let suggestions = discover::suggest( + media_client, + &rule.tracking_user, + targets, + recently_played, + &exclude, + rule.discovery_count.max(0) as usize, + ) + .await?; + + for s in &suggestions { + sqlx::query!( + r#" + INSERT INTO "mix_suggestion" (id, rule_id, mix_id, recording_mbid, title, artist, release, cover_url, score) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) + ON CONFLICT (rule_id, recording_mbid) DO UPDATE + SET mix_id = EXCLUDED.mix_id, score = EXCLUDED.score, title = EXCLUDED.title, + artist = EXCLUDED.artist, release = EXCLUDED.release, cover_url = EXCLUDED.cover_url + "#, + Uuid::new_v4(), + rule.id, + s.mix_id, + s.mbid, + s.info.title, + s.info.artist, + s.info.release, + s.info.cover_url, + s.score, + ) + .execute(database) + .await?; + } + + // drop untouched suggestions from previous runs + let kept: Vec = suggestions.iter().map(|s| s.mbid.clone()).collect(); + sqlx::query!( + r#" + DELETE FROM "mix_suggestion" + WHERE rule_id = $1 AND status = 'new' AND NOT (recording_mbid = ANY($2)) + "#, + rule.id, + &kept, + ) + .execute(database) + .await?; + + println!(" {} new songs suggested", suggestions.len()); + Ok(()) +} diff --git a/src/discover.rs b/src/discover.rs new file mode 100644 index 0000000..e73efc6 --- /dev/null +++ b/src/discover.rs @@ -0,0 +1,210 @@ +//! Find songs that aren't in the library to suggest alongside each mix. +//! +//! Candidates come from Listenbrainz's collaborative filtering recommendations +//! for the user (filtered to recordings they've never listened to) and, if a +//! 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. + +use crate::listenbrainz::{self, RecordingInfo}; +use crate::mix::{name_key, normalize, RecentlyPlayed}; +use crate::subsonic::Subsonic; +use std::collections::{HashMap, HashSet}; +use uuid::Uuid; + +/// Candidates must fit a mix at least this well (cosine similarity of genres) +const MIN_FIT: f64 = 0.2; +/// Most suggestions per artist in one mix +const PER_ARTIST: usize = 2; +/// Recommendations to request from Listenbrainz +const RECOMMENDATIONS: usize = 1000; +/// Genres per LB Radio prompt +const RADIO_GENRES: usize = 3; + +pub struct MixTarget { + pub mix_id: Uuid, + /// The mix's genres (as in the cluster profile, best first) and their weights + pub profile: Vec<(String, f64)>, +} + +pub struct Suggestion { + pub mix_id: Uuid, + pub mbid: String, + pub info: RecordingInfo, + pub score: f64, +} + +/// 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); + for (genre, w) in genres { + norm += w * w; + if let Some(p) = profile.get(&normalize(genre)) { + dot += w * p; + } + } + if norm == 0.0 || profile_norm == 0.0 { + 0.0 + } else { + dot / (norm.sqrt() * profile_norm) + } +} + +pub async fn suggest( + client: &Subsonic, + user: &str, + targets: &[MixTarget], + recently_played: &RecentlyPlayed, + // recordings that already have a suggestion the user acted on + exclude: &HashSet, + per_mix: usize, +) -> Result, Box> { + if targets.is_empty() || per_mix == 0 { + return Ok(vec![]); + } + + // ---- candidates ---- + let mut candidates: Vec = listenbrainz::recommendations(user, RECOMMENDATIONS) + .await? + .into_iter() + .filter(|r| r.latest_listened_at.is_none()) + .map(|r| r.recording_mbid) + .collect(); + + if let Some(token) = listenbrainz::token() { + for target in targets { + let genres: Vec<&str> = target + .profile + .iter() + .take(RADIO_GENRES) + .map(|(g, _)| g.as_str()) + .collect(); + // LB Radio prompts can't contain these + if genres.iter().any(|g| g.contains([',', '(', ')', ':'])) { + continue; + } + let prompt = format!("tag:({})::or", genres.join(", ")); + match listenbrainz::radio(&prompt, "medium", &token).await { + Ok(mbids) => candidates.extend(mbids), + Err(e) => println!("LB Radio failed for {}: {:?}", prompt, e), + } + } + } + + let mut seen = HashSet::new(); + candidates.retain(|m| !exclude.contains(m) && seen.insert(m.clone())); + let metadata = listenbrainz::recording_metadata(&candidates).await?; + + // ---- assign each candidate to the mix it fits best ---- + let profiles: Vec<(HashMap, f64)> = targets + .iter() + .map(|t| { + let mut p: HashMap = HashMap::new(); + for (genre, w) in &t.profile { + *p.entry(normalize(genre)).or_default() += w; + } + let norm = p.values().map(|w| w * w).sum::().sqrt(); + (p, norm) + }) + .collect(); + + let mut per_target: Vec> = vec![vec![]; targets.len()]; + for (mbid, info) in &metadata { + if info.title.is_empty() + || recently_played.contains_recording(Some(mbid), &info.artist, &info.title) + { + continue; + } + let best = profiles + .iter() + .enumerate() + .map(|(i, (p, n))| (i, fit(&info.genres, p, *n))) + .max_by(|a, b| a.1.total_cmp(&b.1)); + if let Some((i, score)) = best { + if score >= MIN_FIT { + per_target[i].push((score, mbid, info)); + } + } + } + + // ---- pick the best per mix, skipping songs already in the library ---- + let mut suggestions = vec![]; + let mut seen_names: HashSet = HashSet::new(); + 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 mut artists: HashMap = HashMap::new(); + let mut taken = 0; + + for (score, mbid, info) in found { + if taken >= per_mix { + break; + } + let artist_count = artists.entry(normalize(&info.artist)).or_default(); + if *artist_count >= PER_ARTIST + || seen_names.contains(&name_key(&info.artist, &info.title)) + { + continue; + } + if in_library(client, mbid, info).await? { + continue; + } + + *artist_count += 1; + taken += 1; + seen_names.insert(name_key(&info.artist, &info.title)); + suggestions.push(Suggestion { + mix_id: target.mix_id, + mbid: mbid.clone(), + info: RecordingInfo { + title: info.title.clone(), + artist: info.artist.clone(), + release: info.release.clone(), + cover_url: info.cover_url.clone(), + genres: HashMap::new(), + }, + score, + }); + } + } + + Ok(suggestions) +} + +async fn in_library( + client: &Subsonic, + mbid: &str, + info: &RecordingInfo, +) -> Result> { + if !client.song_search(mbid.to_string()).await?.is_empty() { + return Ok(true); + } + let key = name_key(&info.artist, &info.title); + Ok(client + .song_search(format!("{} {}", info.title, info.artist)) + .await? + .iter() + .any(|s| name_key(&s.artist, &s.title) == key)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fit_prefers_matching_genres() { + let profile: HashMap = + [("mathcore".to_string(), 2.0), ("mathrock".to_string(), 1.0)].into(); + let norm = 5f64.sqrt(); + let math: HashMap = [ + ("Mathcore".to_string(), 1.0), + ("math rock".to_string(), 1.0), + ] + .into(); + let folk: HashMap = [("folk".to_string(), 1.0)].into(); + + assert!(fit(&math, &profile, norm) > 0.9); + assert_eq!(fit(&folk, &profile, norm), 0.0); + assert_eq!(fit(&HashMap::new(), &profile, norm), 0.0); + } +} diff --git a/src/listenbrainz.rs b/src/listenbrainz.rs index 0b0a326..e1cf146 100644 --- a/src/listenbrainz.rs +++ b/src/listenbrainz.rs @@ -239,10 +239,32 @@ pub async fn listens_since(user: impl Display, min_ts: i64) -> Result, + #[serde(default)] + artist: Option, + #[serde(default)] + release: Option, #[serde(default)] tag: Option, } +#[derive(Deserialize, Default)] +struct Named { + #[serde(default)] + name: String, +} + +#[derive(Deserialize, Default)] +struct Release { + #[serde(default)] + name: Option, + #[serde(default)] + caa_id: Option, + #[serde(default)] + caa_release_mbid: Option, +} + #[derive(Deserialize, Default)] struct RecordingTags { #[serde(default)] @@ -263,11 +285,21 @@ struct Tag { genre_mbid: Option, } -/// Weighted MusicBrainz genres for each recording, combining the recording's own genres (most -/// specific) with those of its release group and artists (broadest). Names are lowercased. -pub async fn recording_tags( +pub struct RecordingInfo { + pub title: String, + pub artist: String, + pub release: Option, + /// Front cover from the Cover Art Archive, if there is one + pub cover_url: Option, + /// Weighted MusicBrainz genres, combining the recording's own genres (most specific) with + /// those of its release group and artists (broadest). Names are lowercased. + pub genres: HashMap, +} + +/// Names, cover art and genres of recordings +pub async fn recording_metadata( mbids: &[String], -) -> Result>, reqwest::Error> { +) -> Result, reqwest::Error> { let client = reqwest::Client::new(); let mut out = HashMap::new(); @@ -282,8 +314,8 @@ pub async fn recording_tags( let metadata = send_json::>(request).await?; for (mbid, recording) in metadata { - let mut weights: HashMap = HashMap::new(); - if let Some(tags) = recording.tag { + let mut genres: HashMap = HashMap::new(); + if let Some(tags) = &recording.tag { for (source, weight) in [ (&tags.recording, 3.0), (&tags.release_group, 2.0), @@ -292,15 +324,151 @@ pub async fn recording_tags( for tag in source.iter().filter(|t| t.genre_mbid.is_some()) { let name = tag.tag.trim().to_lowercase(); if !name.is_empty() { - *weights.entry(name).or_default() += + *genres.entry(name).or_default() += weight * (1.0 + tag.count.unwrap_or(1).max(1) as f64).ln(); } } } } - out.insert(mbid, weights); + let release = recording.release.unwrap_or_default(); + let cover_url = match (release.caa_id, &release.caa_release_mbid) { + (Some(id), Some(release_mbid)) => Some(format!( + "https://coverartarchive.org/release/{}/{}-250.jpg", + release_mbid, id + )), + _ => None, + }; + + out.insert( + mbid, + RecordingInfo { + title: recording.recording.unwrap_or_default().name, + artist: recording.artist.unwrap_or_default().name, + release: release.name, + cover_url, + genres, + }, + ); } } Ok(out) } + +/// Weighted MusicBrainz genres for each recording; see [`RecordingInfo::genres`] +pub async fn recording_tags( + mbids: &[String], +) -> Result>, reqwest::Error> { + Ok(recording_metadata(mbids) + .await? + .into_iter() + .map(|(mbid, info)| (mbid, info.genres)) + .collect()) +} + +#[derive(Deserialize)] +struct RecommendationsResponse { + payload: RecommendationsPayload, +} + +#[derive(Deserialize)] +struct RecommendationsPayload { + #[serde(default)] + mbids: Vec, +} + +#[derive(Deserialize, Clone)] +pub struct Recommendation { + pub recording_mbid: String, + /// Set if the user has ever listened to the recording + #[serde(default)] + pub latest_listened_at: Option, +} + +/// Listenbrainz's collaborative filtering recording recommendations for a user +pub async fn recommendations( + user: impl Display, + count: usize, +) -> Result, reqwest::Error> { + let response = reqwest::Client::new() + .get(format!( + "{}/cf/recommendation/user/{}/recording", + BASE, user + )) + .query(&[("count", count)]) + .header(reqwest::header::USER_AGENT, USER_AGENT) + .send() + .await? + .error_for_status()?; + + // 204 when there are no recommendations for the user (yet) + if response.status() == reqwest::StatusCode::NO_CONTENT { + return Ok(vec![]); + } + Ok(response + .json::() + .await? + .payload + .mbids) +} + +/// The user token from the config, needed by some endpoints (e.g. LB Radio) +pub fn token() -> Option { + crate::CONFIG + .get()? + .get::("listenbrainz.token") + .ok() + .filter(|t| !t.is_empty()) +} + +#[derive(Deserialize)] +struct RadioResponse { + payload: RadioPayload, +} + +#[derive(Deserialize)] +struct RadioPayload { + jspf: Jspf, +} + +#[derive(Deserialize)] +struct Jspf { + playlist: JspfPlaylist, +} + +#[derive(Deserialize)] +struct JspfPlaylist { + #[serde(default)] + track: Vec, +} + +#[derive(Deserialize)] +struct JspfTrack { + #[serde(default)] + identifier: Vec, +} + +/// Recording MBIDs from an LB Radio prompt, e.g. `tag:(mathcore, math rock)::or`. +/// `mode` is "easy", "medium" or "hard" (more obscure). Needs a user token. +pub async fn radio(prompt: &str, mode: &str, token: &str) -> Result, reqwest::Error> { + let request = reqwest::Client::new() + .get(format!("{}/explore/lb-radio", BASE)) + .query(&[("prompt", prompt), ("mode", mode)]) + .header(reqwest::header::AUTHORIZATION, format!("Token {}", token)); + + Ok(send_json::(request) + .await? + .payload + .jspf + .playlist + .track + .into_iter() + .flat_map(|t| t.identifier) + .filter_map(|id| { + id.rsplit('/') + .next() + .filter(|m| m.len() == 36) + .map(str::to_string) + }) + .collect()) +} diff --git a/src/main.rs b/src/main.rs index 5985b3c..fce4aa3 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,14 @@ mod cluster; mod daemon; +mod discover; mod listenbrainz; mod mix; mod models; mod playlist; mod subsonic; mod track; +mod web; +mod youtube; use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon}; use crate::models::{ @@ -71,9 +74,19 @@ async fn main() -> Result<(), Box> { }); } - rocket::build() + let youtube = youtube::YouTube::new( + CONFIG + .get() + .unwrap() + .get::("discover.ytdlp") + .unwrap_or_else(|_| "yt-dlp".to_string()), + ); + + let mut server = rocket::build() .manage(media_client) .manage(database) + .manage(youtube) + .mount("/api/discover", web::routes()) .mount( "/api/playlist", routes![ @@ -84,9 +97,14 @@ async fn main() -> Result<(), Box> { create_cluster_mix_rule, all_cluster_mix_rules, ], - ) - .launch() - .await?; + ); + + // the discover UI's built files (discover/dist) + if let Ok(ui) = CONFIG.get().unwrap().get::("discover.ui") { + server = server.mount("/", rocket::fs::FileServer::from(ui)); + } + + server.launch().await?; Ok(()) } diff --git a/src/mix.rs b/src/mix.rs index 7b19363..1743a48 100644 --- a/src/mix.rs +++ b/src/mix.rs @@ -27,7 +27,7 @@ pub struct MixOptions { pub struct Mix { pub label: String, - /// Normalised genres describing the mix, best first + /// Library genres describing the mix, best first pub tags: Vec, pub song_ids: Vec, } @@ -67,10 +67,12 @@ impl RecentlyPlayed { } fn contains(&self, song: &Track) -> bool { - song.music_brainz_id - .as_ref() - .is_some_and(|m| self.mbids.contains(m)) - || self.names.contains(&name_key(&song.artist, &song.title)) + self.contains_recording(song.music_brainz_id.as_deref(), &song.artist, &song.title) + } + + pub fn contains_recording(&self, mbid: Option<&str>, artist: &str, title: &str) -> bool { + mbid.is_some_and(|m| self.mbids.contains(m)) + || self.names.contains(&name_key(artist, title)) } } @@ -249,7 +251,11 @@ pub async fn build_mix( Ok(Some(Mix { label, - tags: matched.iter().take(5).map(|(k, _)| k.clone()).collect(), + tags: matched + .iter() + .take(5) + .map(|(k, _)| library_genres[k].clone()) + .collect(), song_ids: chosen.into_iter().map(|s| s.id).collect(), })) } @@ -260,8 +266,8 @@ pub fn match_mixes(old: &[Vec], new: &[Vec]) -> Vec<(usize, usiz let mut pairs: Vec<(f64, usize, usize)> = vec![]; for (i, a) in old.iter().enumerate() { for (j, b) in new.iter().enumerate() { - let a: HashSet<_> = a.iter().collect(); - let b: HashSet<_> = b.iter().collect(); + let a: HashSet = a.iter().map(|t| normalize(t)).collect(); + let b: HashSet = b.iter().map(|t| normalize(t)).collect(); let union = a.union(&b).count(); let jaccard = if union == 0 { 0.0 diff --git a/src/models.rs b/src/models.rs index f306cba..19380d1 100644 --- a/src/models.rs +++ b/src/models.rs @@ -142,6 +142,7 @@ pub struct PartialClusterMixRule { pub familiar_ratio: Option, pub name_template: Option, pub refresh_hours: Option, + pub discovery_count: Option, } impl PartialClusterMixRule { @@ -154,8 +155,8 @@ impl PartialClusterMixRule { sqlx::query!( r#" INSERT INTO "cluster_mix_rule" - (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours) - VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24)) + (id, tracking_user, months, cluster_count, playlist_size, familiar_ratio, name_template, refresh_hours, discovery_count) + VALUES ($1, $2, COALESCE($3, 3), $4, COALESCE($5, 50), COALESCE($6::FLOAT8, 0.3), COALESCE($7, 'Mix: {label}'), COALESCE($8, 24), COALESCE($9, 15)) "#, uuid, self.tracking_user, @@ -165,6 +166,7 @@ impl PartialClusterMixRule { self.familiar_ratio, self.name_template, self.refresh_hours, + self.discovery_count, ) .execute(pool) .await?; @@ -184,6 +186,7 @@ pub struct ClusterMixRule { pub name_template: String, pub refresh_hours: i32, pub last_run: Option>, + pub discovery_count: i32, } impl ClusterMixRule { @@ -226,4 +229,22 @@ pub struct ClusterMixPlaylist { pub rule_id: Uuid, pub playlist_id: String, pub tags: Vec, + pub name: Option, + pub position: i32, +} + +#[derive(Serialize)] +pub struct MixSuggestion { + pub id: Uuid, + pub rule_id: Uuid, + pub mix_id: Option, + pub recording_mbid: String, + pub title: String, + pub artist: String, + pub release: Option, + pub cover_url: Option, + pub score: f64, + pub status: String, + pub youtube_id: Option, + pub created_at: DateTime, } diff --git a/src/subsonic.rs b/src/subsonic.rs index b1e2a03..25c0ef8 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -266,6 +266,27 @@ impl Subsonic { serde_json::from_value(response).map_err(SubsonicError::Json) } + /// Request a binary endpoint (e.g. `stream`, `getCoverArt`) and hand back the raw response, + /// forwarding an HTTP Range header if given + pub async fn raw( + &self, + endpoint: &str, + params: &[(&'static str, String)], + range: Option<&str>, + ) -> Result { + let mut query = self.base_params(); + query.extend_from_slice(params); + + let mut request = self + .client + .get(format!("{}/{}", self.base, endpoint)) + .query(&query); + if let Some(range) = range { + request = request.header(reqwest::header::RANGE, range); + } + request.send().await.map_err(SubsonicError::Reqwest) + } + /// All genres in the library pub async fn get_genres(&self) -> Result, SubsonicError> { Ok(self diff --git a/src/track.rs b/src/track.rs index 6c6e41c..866a690 100644 --- a/src/track.rs +++ b/src/track.rs @@ -15,6 +15,11 @@ pub struct Track { pub genres: Vec, #[serde(rename = "musicBrainzId", default)] pub music_brainz_id: Option, + /// Seconds + #[serde(default)] + pub duration: Option, + #[serde(rename = "coverArt", default)] + pub cover_art: Option, } #[derive(Serialize, Deserialize, Debug, Clone)] diff --git a/src/web.rs b/src/web.rs new file mode 100644 index 0000000..cde8230 --- /dev/null +++ b/src/web.rs @@ -0,0 +1,375 @@ +//! API for the discover UI: mixes, suggested songs, and audio/cover streaming +//! from Subsonic or YouTube. + +use crate::models::{ClusterMixRule, MixSuggestion}; +use crate::subsonic::Subsonic; +use crate::track::Track; +use crate::youtube::YouTube; +use futures_util::TryStreamExt; +use rocket::http::Status; +use rocket::request::{FromRequest, Outcome}; +use rocket::response::{self, Responder}; +use rocket::serde::json::Json; +use rocket::{get, post, put, routes, Request, Response, Route, State}; +use serde::{Deserialize, Serialize}; +use sqlx::postgres::PgPool; +use std::convert::Infallible; +use std::sync::Arc; +use tokio_util::io::StreamReader; +use uuid::Uuid; + +pub fn routes() -> Vec { + routes![rules, mixes, mix, liked, set_status, rebuild, stream, cover, youtube] +} + +type ApiResult = Result, Status>; + +fn db_error(e: sqlx::Error) -> Status { + match e { + sqlx::Error::RowNotFound => Status::NotFound, + e => { + println!("Database error: {:?}", e); + Status::InternalServerError + } + } +} + +fn parse_id(id: &str) -> Result { + Uuid::parse_str(id).map_err(|_| Status::NotFound) +} + +#[get("/rules")] +async fn rules(pool: &State) -> ApiResult> { + ClusterMixRule::all(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +#[derive(Serialize)] +struct MixSummary { + id: Uuid, + playlist_id: String, + name: Option, + tags: Vec, + position: i32, + new_count: i64, +} + +#[get("/rules//mixes")] +async fn mixes(id: &str, pool: &State) -> ApiResult> { + sqlx::query_as!( + MixSummary, + r#" + SELECT p.id, p.playlist_id, p.name, p.tags, p.position, + COUNT(s.id) FILTER (WHERE s.status = 'new') AS "new_count!" + FROM "cluster_mix_playlist" p + LEFT JOIN "mix_suggestion" s ON s.mix_id = p.id + WHERE p.rule_id = $1 + GROUP BY p.id + ORDER BY p.position + "#, + parse_id(id)? + ) + .fetch_all(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +#[derive(Serialize)] +struct MixDetail { + #[serde(flatten)] + summary: MixSummary, + songs: Vec, + suggestions: Vec, +} + +#[get("/mixes/")] +async fn mix( + id: &str, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + let summary = sqlx::query_as!( + MixSummary, + r#" + SELECT p.id, p.playlist_id, p.name, p.tags, p.position, + COUNT(s.id) FILTER (WHERE s.status = 'new') AS "new_count!" + FROM "cluster_mix_playlist" p + LEFT JOIN "mix_suggestion" s ON s.mix_id = p.id + WHERE p.id = $1 + GROUP BY p.id + "#, + id + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + let songs = media_client + .get_playlist(&summary.playlist_id) + .await + .map_err(|e| { + println!("Could not load playlist {}: {:?}", summary.playlist_id, e); + Status::BadGateway + })? + .entry; + + let suggestions = sqlx::query_as!( + MixSuggestion, + r#" + SELECT * FROM "mix_suggestion" + WHERE mix_id = $1 AND status <> 'dismissed' + ORDER BY score DESC + "#, + id + ) + .fetch_all(pool.inner()) + .await + .map_err(db_error)?; + + Ok(Json(MixDetail { + summary, + songs, + suggestions, + })) +} + +#[get("/rules//liked")] +async fn liked(id: &str, pool: &State) -> ApiResult> { + sqlx::query_as!( + MixSuggestion, + r#" + SELECT * FROM "mix_suggestion" + WHERE rule_id = $1 AND status = 'liked' + ORDER BY created_at DESC + "#, + parse_id(id)? + ) + .fetch_all(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +#[derive(Deserialize)] +struct StatusUpdate { + status: String, +} + +/// Like, dismiss, or reset a suggestion +#[put("/suggestions/", data = "")] +async fn set_status( + id: &str, + update: Json, + pool: &State, +) -> ApiResult { + if !["new", "liked", "dismissed"].contains(&update.status.as_str()) { + return Err(Status::UnprocessableEntity); + } + sqlx::query_as!( + MixSuggestion, + r#"UPDATE "mix_suggestion" SET status = $1 WHERE id = $2 RETURNING *"#, + update.status, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map(Json) + .map_err(db_error) +} + +/// Rebuild a rule's mixes on the next daemon tick +#[post("/rules//rebuild")] +async fn rebuild(id: &str, pool: &State) -> Status { + let Ok(id) = parse_id(id) else { + return Status::NotFound; + }; + match sqlx::query!( + r#"UPDATE "cluster_mix_rule" SET last_run = NULL WHERE id = $1"#, + id + ) + .execute(pool.inner()) + .await + { + Ok(r) if r.rows_affected() > 0 => Status::Accepted, + Ok(_) => Status::NotFound, + Err(e) => db_error(e), + } +} + +/// The request's Range header, so audio can be seeked +pub struct Range(Option); + +#[rocket::async_trait] +impl<'r> FromRequest<'r> for Range { + type Error = Infallible; + + async fn from_request(request: &'r Request<'_>) -> Outcome { + Outcome::Success(Range( + request.headers().get_one("Range").map(str::to_string), + )) + } +} + +/// Stream an upstream response through, keeping the headers a media element needs +pub struct Proxied(reqwest::Response); + +impl<'r> Responder<'r, 'static> for Proxied { + fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> { + let upstream = self.0; + let mut response = Response::build(); + response.status(Status::new(upstream.status().as_u16())); + for name in [ + "content-type", + "content-range", + "accept-ranges", + "cache-control", + "last-modified", + "etag", + ] { + if let Some(value) = upstream.headers().get(name).and_then(|v| v.to_str().ok()) { + response.raw_header(name, value.to_string()); + } + } + let size = upstream.content_length(); + let body = StreamReader::new(upstream.bytes_stream().map_err(std::io::Error::other)); + match size { + // a known length lets browsers show durations and seek + Some(size) => response.sized_body(size as usize, LengthReader(body)), + None => response.streamed_body(body), + }; + response.ok() + } +} + +/// Rocket only accepts a known body length for seekable bodies, but never seeks one whose size +/// is given up front. This satisfies the trait for a plain stream. +struct LengthReader(R); + +impl tokio::io::AsyncRead for LengthReader { + fn poll_read( + mut self: std::pin::Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + buf: &mut tokio::io::ReadBuf<'_>, + ) -> std::task::Poll> { + std::pin::Pin::new(&mut self.0).poll_read(cx, buf) + } +} + +impl tokio::io::AsyncSeek for LengthReader { + fn start_seek(self: std::pin::Pin<&mut Self>, _: std::io::SeekFrom) -> std::io::Result<()> { + Err(std::io::Error::other("streamed body can't be seeked")) + } + + fn poll_complete( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Err(std::io::Error::other("streamed body can't be seeked"))) + } +} + +/// Stream a song from Subsonic +#[get("/stream/")] +async fn stream( + id: &str, + range: Range, + media_client: &State>, +) -> Result { + let format = crate::CONFIG + .get() + .and_then(|c| c.get::("discover.format").ok()) + .unwrap_or_else(|| "raw".to_string()); + media_client + .raw( + "stream", + &[("id", id.to_string()), ("format", format)], + range.0.as_deref(), + ) + .await + .map(Proxied) + .map_err(|_| Status::BadGateway) +} + +/// Cover art from Subsonic +#[get("/cover/?")] +async fn cover( + id: &str, + size: Option, + media_client: &State>, +) -> Result { + media_client + .raw( + "getCoverArt", + &[ + ("id", id.to_string()), + ("size", size.unwrap_or(300).to_string()), + ], + None, + ) + .await + .map(Proxied) + .map_err(|_| Status::BadGateway) +} + +/// Find a suggested song on YouTube and stream its audio +#[get("/youtube/")] +async fn youtube( + id: &str, + range: Range, + pool: &State, + youtube: &State, +) -> Result { + let suggestion = sqlx::query_as!( + MixSuggestion, + r#"SELECT * FROM "mix_suggestion" WHERE id = $1"#, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + let video_id = match suggestion.youtube_id { + Some(video_id) => video_id, + None => { + let video_id = youtube + .search(&suggestion.artist, &suggestion.title) + .await + .map_err(|e| { + println!("YouTube search failed: {}", e); + Status::BadGateway + })? + .ok_or(Status::NotFound)?; + sqlx::query!( + r#"UPDATE "mix_suggestion" SET youtube_id = $1 WHERE id = $2"#, + video_id, + suggestion.id + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + video_id + } + }; + + // a cached URL may have expired; fetch a fresh one once + for refresh in [false, true] { + let url = youtube.audio_url(&video_id, refresh).await.map_err(|e| { + println!("Could not get audio for {}: {}", video_id, e); + Status::BadGateway + })?; + let mut request = youtube.client.get(url); + if let Some(range) = &range.0 { + request = request.header(reqwest::header::RANGE, range); + } + let response = request.send().await.map_err(|_| Status::BadGateway)?; + if !refresh && matches!(response.status().as_u16(), 403 | 404 | 410) { + continue; + } + return Ok(Proxied(response)); + } + Err(Status::BadGateway) +} diff --git a/src/youtube.rs b/src/youtube.rs new file mode 100644 index 0000000..2882048 --- /dev/null +++ b/src/youtube.rs @@ -0,0 +1,133 @@ +//! Find and stream songs from YouTube with yt-dlp. + +use std::collections::HashMap; +use std::process::Stdio; +use std::time::{Duration, Instant}; +use thiserror::Error; +use tokio::process::Command; +use tokio::sync::Mutex; + +/// Search results longer than this are probably full albums or mixes +const MAX_DURATION_SECS: f64 = 15.0 * 60.0; +/// YouTube's media URLs expire after about 6 hours +const URL_TTL: Duration = Duration::from_secs(60 * 60); +const SEARCH_RESULTS: usize = 5; + +#[derive(Debug, Error)] +pub enum YouTubeError { + #[error("couldn't run yt-dlp: {0}")] + Spawn(#[from] std::io::Error), + #[error("yt-dlp failed: {0}")] + Failed(String), + #[error("invalid video id")] + InvalidId, +} + +pub struct YouTube { + binary: String, + urls: Mutex>, + pub client: reqwest::Client, +} + +pub fn valid_video_id(id: &str) -> bool { + id.len() == 11 + && id + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') +} + +impl YouTube { + pub fn new(binary: String) -> Self { + Self { + binary, + urls: Mutex::new(HashMap::new()), + client: reqwest::Client::new(), + } + } + + async fn run(&self, args: &[&str]) -> Result { + let output = Command::new(&self.binary) + .args(["--no-warnings", "--no-playlist", "--ignore-config"]) + .args(args) + .stdin(Stdio::null()) + .kill_on_drop(true) + .output() + .await?; + if !output.status.success() { + return Err(YouTubeError::Failed( + String::from_utf8_lossy(&output.stderr).trim().to_string(), + )); + } + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) + } + + /// The ID of the best matching video for a song, skipping very long videos + pub async fn search(&self, artist: &str, title: &str) -> Result, YouTubeError> { + let query = format!("ytsearch{}:{} - {}", SEARCH_RESULTS, artist, title); + let output = self + .run(&["--flat-playlist", "--print", "%(id)s\t%(duration)s", &query]) + .await?; + + let results: Vec<(&str, Option)> = output + .lines() + .filter_map(|line| { + let (id, duration) = line.split_once('\t')?; + valid_video_id(id).then(|| (id, duration.trim().parse::().ok())) + }) + .collect(); + + Ok(results + .iter() + .find(|(_, d)| d.is_some_and(|d| d <= MAX_DURATION_SECS)) + .or(results.first()) + .map(|(id, _)| id.to_string())) + } + + /// A direct URL to the video's audio, preferring m4a since every browser can play it + pub async fn audio_url(&self, video_id: &str, refresh: bool) -> Result { + if !valid_video_id(video_id) { + return Err(YouTubeError::InvalidId); + } + { + let urls = self.urls.lock().await; + if let Some((url, fetched)) = urls.get(video_id) { + if !refresh && fetched.elapsed() < URL_TTL { + return Ok(url.clone()); + } + } + } + + let output = self + .run(&[ + "-f", + "bestaudio[ext=m4a]/bestaudio", + "--get-url", + &format!("https://www.youtube.com/watch?v={}", video_id), + ]) + .await?; + let url = output + .lines() + .next() + .filter(|l| l.starts_with("http")) + .ok_or_else(|| YouTubeError::Failed("no audio URL".to_string()))? + .to_string(); + + let mut urls = self.urls.lock().await; + urls.retain(|_, (_, fetched)| fetched.elapsed() < URL_TTL); + urls.insert(video_id.to_string(), (url.clone(), Instant::now())); + Ok(url) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn validates_video_ids() { + assert!(valid_video_id("dQw4w9WgXcQ")); + assert!(valid_video_id("a-b_c123456")); + assert!(!valid_video_id("--exec=rm -")); + assert!(!valid_video_id("short")); + } +} -- 2.34.1 From 2dd8621568a7845d47b9915ab5b64c12c13a68f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 17:00:14 +0000 Subject: [PATCH 3/9] Mix known songs into discover mixes at a fixed ratio "Play mix" in the discover UI used to spread new songs through the whole library playlist, so the share of new songs depended on how many there were. It now plays the new songs with songs the user has played mixed in evenly at the rule's familiar_ratio (30% by default), the same ratio that sets how much of the Subsonic playlist is familiar. Which songs in each mix playlist were played recently is now recorded when the mix is built (cluster_mix_playlist.known_song_ids) and returned with the mix; the UI marks them as "Played". Mixes built before this fall back to using the library songs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p --- README.md | 6 ++++- discover/src/App.tsx | 2 +- discover/src/MixView.tsx | 29 +++++++++++++++------ discover/src/api.ts | 9 ++++++- discover/src/queue.ts | 31 +++++++++++++++++------ discover/src/styles.css | 9 +++++++ migrations/20261113200000_known_songs.sql | 3 +++ src/daemon/cluster_mixes.rs | 8 +++--- src/mix.rs | 5 ++++ src/models.rs | 1 + src/web.rs | 11 ++++++++ 11 files changed, 92 insertions(+), 22 deletions(-) create mode 100644 migrations/20261113200000_known_songs.sql diff --git a/README.md b/README.md index 181afce..ab934e8 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ VALUES (gen_random_uuid(), 'jellywx', 3, 50); | `months` | 3 | Months of listening history to cluster | | `cluster_count` | automatic | Number of mixes | | `playlist_size` | 50 | Songs per mix | -| `familiar_ratio` | 0.3 | Share of each mix taken from recently played tracks | +| `familiar_ratio` | 0.3 | Share of each mix made of songs you've played recently (also used by the discover UI's "Play mix") | | `name_template` | `Mix: {label}` | Playlist name; `{label}` becomes the mix's top genres | | `refresh_hours` | 24 | How often to rebuild the mixes | | `discovery_count`| 15 | New songs (not in your library) to suggest per mix | @@ -131,6 +131,10 @@ In the UI, songs from your library stream from Subsonic. New songs are found on installed on the server (keep it up to date: YouTube changes often break older versions). You can like a new song to keep it in "Liked new songs", or hide it so it isn't suggested again. +"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. + Build it with: ```sh diff --git a/discover/src/App.tsx b/discover/src/App.tsx index 5a4e8d7..735b9b0 100644 --- a/discover/src/App.tsx +++ b/discover/src/App.tsx @@ -211,7 +211,7 @@ export function App() { {route.view === "liked" ? ( ) : detail ? ( - + ) : ( mixId &&
    Loading…
    )} diff --git a/discover/src/MixView.tsx b/discover/src/MixView.tsx index 0c50787..f5ae245 100644 --- a/discover/src/MixView.tsx +++ b/discover/src/MixView.tsx @@ -1,6 +1,6 @@ import { useMemo } from "react"; import { MixDetail, mixTitle, Suggestion, SuggestionStatus } from "./api"; -import { fromSong, fromSuggestion, interleave, QueueItem } from "./queue"; +import { fromSong, fromSuggestion, mixAtRatio, QueueItem, shuffled } from "./queue"; import { Player } from "./usePlayer"; import { TrackRow } from "./TrackRow"; import * as Icon from "./icons"; @@ -37,15 +37,24 @@ export function SuggestionActions({ s, onStatus }: { s: Suggestion; onStatus: (s type Props = { mix: MixDetail; + /** Share of "Play mix" made of songs the user already knows */ + knownRatio: number; player: Player; onStatus: (s: Suggestion, status: SuggestionStatus) => void; }; -export function MixView({ mix, player, onStatus }: Props) { +export function MixView({ mix, knownRatio, player, onStatus }: Props) { const fresh = useMemo(() => mix.suggestions.map(fromSuggestion), [mix.suggestions]); const library = useMemo(() => mix.songs.map(fromSong), [mix.songs]); - // clicking a row plays through everything shown, new songs first - const all = useMemo(() => [...fresh, ...library], [fresh, library]); + const knownIds = useMemo(() => new Set(mix.known_song_ids), [mix.known_song_ids]); + // mixes built before songs were marked as known fall back to the whole library + const known = useMemo( + () => (knownIds.size ? library.filter((_, i) => knownIds.has(mix.songs[i].id)) : library), + [library, knownIds, mix.songs], + ); + // clicking a new song plays the new songs in order, with known songs mixed in + const mixed = useMemo(() => mixAtRatio(fresh, known, knownRatio), [fresh, known, knownRatio]); + const percent = Math.round(Math.min(Math.max(knownRatio, 0), 1) * 100); const title = mixTitle(mix); const h = hue(mix.tags.join()); @@ -65,10 +74,13 @@ export function MixView({ mix, player, onStatus }: Props) { {mix.tags.map((t) =>
  • {t}
  • )}

    - {mix.songs.length} from your library · {mix.suggestions.length} new + {mix.suggestions.length} new · {mix.songs.length} from your library + {knownIds.size > 0 && <>, {knownIds.size} you've played}

    - + )} +
    + + {editing === "new-playlist" && ( + setEditing(null)} + onSaved={(p) => { + setPlaylists((ps) => replace(ps, p)); + setEditing(null); + onToast(`Tracking “${p.name}”. Refreshing it now…`); + void refresh(p); + }} + /> + )} + + {playlists === null ? ( +

    Loading…

    + ) : playlists.length === 0 && editing !== "new-playlist" ? ( +

    No tracked playlists yet. Create one to keep, say, your top 50 of the last month in Subsonic.

    + ) : ( +
      + {playlists.map((p) => + editing === p.id ? ( +
    • + setEditing(null)} + onSaved={(updated) => { + setPlaylists((ps) => replace(ps, updated)); + setEditing(null); + onToast("Saved. Refresh to apply the changes now."); + }} + /> +
    • + ) : ( + : } + title={p.name ?? Missing from Subsonic} + subtitle={describe(p)} + aside={ + p.song_count === null ? undefined : p.song_count > 0 && p.song_count < p.playlist_size ? ( + + {p.song_count} of {p.playlist_size} found + + ) : ( + `${p.song_count} songs` + ) + } + actions={ + <> + + + + + } + confirm={ + confirming === p.id && ( + setConfirming(null)} + onRemoved={(deleted) => { + setPlaylists((ps) => ps?.filter((x) => x.id !== p.id) ?? null); + setConfirming(null); + onToast(deleted ? "Playlist deleted" : "Stopped tracking. The playlist stays in Subsonic."); + }} + /> + ) + } + /> + ), + )} +
    + )} + + +
    +
    +
    +

    Recurring playlists

    +

    Start a new tracked playlist whenever the name changes, e.g. each year or month.

    +
    + {editing !== "new-rule" && ( + + )} +
    + + {editing === "new-rule" && ( + setEditing(null)} + onSaved={(r) => { + setRules((rs) => replace(rs, r)); + setEditing(null); + onToast(`“${r.current_name}” will be created within a few minutes`); + // the daemon creates the playlist; show it once it's there + window.setTimeout(load, 15000); + }} + /> + )} + + {rules === null ? ( +

    Loading…

    + ) : rules.length === 0 && editing !== "new-rule" ? ( +

    No recurring playlists. A rule like “%Y - Top 100” makes a new top 100 every year.

    + ) : ( +
      + {rules.map((r) => + editing === r.id ? ( +
    • + setEditing(null)} + onSaved={(updated) => { + setRules((rs) => replace(rs, updated)); + setEditing(null); + onToast("Saved. Applies to playlists the rule makes from now on."); + }} + /> +
    • + ) : ( + } + title={{r.name_template}} + subtitle={describe(r)} + aside={ + r.last_name && r.last_name === r.current_name + ? <>Current: {r.last_name} + : r.current_name ? <>Next: {r.current_name} : undefined + } + actions={ + <> + + + + } + confirm={ + confirming === r.id && ( + setConfirming(null)} + onConfirm={async () => { + await trackedApi.removeRule(r.id); + setRules((rs) => rs?.filter((x) => x.id !== r.id) ?? null); + setConfirming(null); + }} + /> + ) + } + /> + ), + )} +
    + )} +
    + + ); +} + +function Item(props: { icon: ReactNode; title: ReactNode; subtitle: string; aside?: ReactNode; actions: ReactNode; confirm?: ReactNode }) { + return ( +
  • +
    + +
    +
    {props.title}
    +
    {props.subtitle}
    +
    + {props.aside &&
    {props.aside}
    } +
    {props.actions}
    +
    + {props.confirm} +
  • + ); +} + +function Confirm(props: { message: ReactNode; action: string; onCancel: () => void; onConfirm: () => Promise; children?: ReactNode }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + return ( +
    +

    {props.message}

    + {props.children} + {error &&

    {error}

    } +
    + + +
    +
    + ); +} + +function RemovePlaylist(props: { playlist: TrackedPlaylist; onCancel: () => void; onRemoved: (deleted: boolean) => void }) { + const [alsoDelete, setAlsoDelete] = useState(false); + return ( + Stop updating “{props.playlist.name ?? "this playlist"}”?} + action={alsoDelete ? "Delete playlist" : "Stop tracking"} + onCancel={props.onCancel} + onConfirm={async () => { + await trackedApi.remove(props.playlist.id, alsoDelete); + props.onRemoved(alsoDelete); + }} + > + {props.playlist.name && ( + + )} + + ); +} + +/** Fields shared by playlists and rules */ +function TrackingFields({ value, onChange, users }: { value: Tracking; onChange: (t: Tracking) => void; users: string[] }) { + return ( + <> + + + + + ); +} + +function useSubmit(save: () => Promise, onSaved: (t: T) => void) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const submit = async (e: FormEvent) => { + e.preventDefault(); + setBusy(true); + setError(null); + try { + onSaved(await save()); + } catch (err) { + setError((err as Error).message); + setBusy(false); + } + }; + return { busy, error, submit }; +} + +function PlaylistForm(props: { + initial: Tracking & Partial; + users: string[]; + onCancel: () => void; + onSaved: (p: TrackedPlaylist) => void; +}) { + const creating = !props.initial.id; + const [tracking, setTracking] = useState({ + playlist_size: props.initial.playlist_size, + tracking_user: props.initial.tracking_user, + tracking_type: props.initial.tracking_type, + }); + const [mode, setMode] = useState<"new" | "existing">("new"); + const [name, setName] = useState(props.initial.name ?? ""); + const [existingId, setExistingId] = useState(""); + const [subsonic, setSubsonic] = useState(null); + + useEffect(() => { + if (creating && mode === "existing" && subsonic === null) { + trackedApi.subsonicPlaylists().then(setSubsonic, () => setSubsonic([])); + } + }, [creating, mode, subsonic]); + const available = subsonic?.filter((p) => !p.tracked) ?? []; + + const { busy, error, submit } = useSubmit( + () => + creating + ? trackedApi.create(mode === "new" ? { ...tracking, name } : { ...tracking, playlist_id: existingId }) + : trackedApi.update(props.initial.id!, { ...tracking, name: name || undefined }), + props.onSaved, + ); + + return ( +
    + {creating && ( +
    + + +
    + )} +
    + {creating && mode === "existing" ? ( +
    + + + Its songs will be replaced with your top songs. +
    + ) : ( + (creating || props.initial.name) && ( + + ) + )} + +
    + {error &&

    {error}

    } +
    + + +
    +
    + ); +} + +function RuleForm(props: { + initial: Tracking & { name_template: string; id?: string }; + users: string[]; + onCancel: () => void; + onSaved: (r: TrackedRule) => void; +}) { + const creating = !props.initial.id; + const [tracking, setTracking] = useState({ + playlist_size: props.initial.playlist_size, + tracking_user: props.initial.tracking_user, + tracking_type: props.initial.tracking_type, + }); + const [template, setTemplate] = useState(props.initial.name_template); + const [preview, setPreview] = useState<{ name?: string; error?: string }>({}); + + useEffect(() => { + const t = window.setTimeout(() => { + trackedApi.previewName(template).then( + ({ name }) => setPreview({ name }), + (e) => setPreview({ error: e.message }), + ); + }, 250); + return () => window.clearTimeout(t); + }, [template]); + + const { busy, error, submit } = useSubmit( + () => + creating + ? trackedApi.createRule({ ...tracking, name_template: template }) + : trackedApi.updateRule(props.initial.id!, { ...tracking, name_template: template }), + props.onSaved, + ); + + return ( +
    +
    +
    + + setTemplate(e.target.value)} spellCheck={false} + aria-describedby="template-help" className="mono" /> + + {preview.error ? ( + {preview.error} + ) : preview.name ? ( + <>Today this makes {preview.name}. + ) : null} + Use %Y for the year, %B the month, %m its number, %V the week. A new playlist starts whenever the name changes. + +
    + +
    + {error &&

    {error}

    } +
    + + +
    +
    + ); +} diff --git a/discover/src/api.ts b/discover/src/api.ts index c6db338..ccd6270 100644 --- a/discover/src/api.ts +++ b/discover/src/api.ts @@ -49,14 +49,22 @@ export type MixDetail = MixSummary & { suggestions: Suggestion[]; }; -async function request(path: string, init?: RequestInit): Promise { - const response = await fetch(`/api/discover${path}`, init); +async function request(path: string, init?: RequestInit, base = "/api/discover"): Promise { + const response = await fetch(`${base}${path}`, init); if (!response.ok) { - throw new Error(`${response.status} ${response.statusText}`); + // the API explains what went wrong where it can + const body = await response.json().catch(() => null); + throw new Error(body?.error ?? `${response.status} ${response.statusText}`); } - return response.json(); + return response.status === 204 ? (undefined as T) : response.json(); } +const json = (method: string, body: unknown): RequestInit => ({ + method, + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(body), +}); + export const api = { rules: () => request("/rules"), mixes: (ruleId: string) => request(`/rules/${ruleId}/mixes`), @@ -80,3 +88,64 @@ export const youtubeUrl = (suggestionId: string) => `/api/discover/youtube/${sug /** "Mix: Pop Punk / Emo" -> "Pop Punk / Emo" */ export const mixTitle = (mix: MixSummary) => (mix.name ?? mix.tags.join(" / ")).replace(/^mix:\s*/i, ""); + +// ---------- tracked playlists ---------- + +export const PERIODS: [string, string][] = [ + ["this_week", "This week so far"], + ["this_month", "This month so far"], + ["this_year", "This year so far"], + ["week", "Last week"], + ["month", "Last month"], + ["quarter", "Last quarter"], + ["half_yearly", "Last six months"], + ["year", "Last year"], + ["all_time", "All time"], +]; + +export const periodLabel = (period: string) => + PERIODS.find(([value]) => value === period)?.[1] ?? period; + +export type Tracking = { + playlist_size: number; + tracking_user: string; + tracking_type: string; +}; + +export type TrackedPlaylist = Tracking & { + id: string; + playlist_id: string | null; + /** null when the playlist no longer exists in Subsonic */ + name: string | null; + song_count: number | null; +}; + +export type TrackedRule = Tracking & { + id: string; + name_template: string; + last_name: string | null; + current_name: string | null; +}; + +export type SubsonicPlaylist = { id: string; name: string; song_count: number; tracked: boolean }; + +const tracked = (path: string, init?: RequestInit) => request(path, init, "/api/tracked"); + +export const trackedApi = { + playlists: () => tracked("/playlists"), + create: (body: Tracking & { name?: string; playlist_id?: string }) => + tracked("/playlists", json("POST", body)), + update: (id: string, body: Tracking & { name?: string }) => + tracked(`/playlists/${id}`, json("PUT", body)), + remove: (id: string, deletePlaylist: boolean) => + tracked(`/playlists/${id}?delete_playlist=${deletePlaylist}`, { method: "DELETE" }), + refresh: (id: string) => tracked(`/playlists/${id}/refresh`, { method: "POST" }), + subsonicPlaylists: () => tracked("/subsonic-playlists"), + rules: () => tracked("/rules"), + createRule: (body: Tracking & { name_template: string }) => tracked("/rules", json("POST", body)), + updateRule: (id: string, body: Tracking & { name_template: string }) => + tracked(`/rules/${id}`, json("PUT", body)), + removeRule: (id: string) => tracked(`/rules/${id}`, { method: "DELETE" }), + previewName: (template: string) => + tracked<{ name: string }>(`/preview-name?template=${encodeURIComponent(template)}`), +}; diff --git a/discover/src/icons.tsx b/discover/src/icons.tsx index 72ae65e..03a0756 100644 --- a/discover/src/icons.tsx +++ b/discover/src/icons.tsx @@ -14,3 +14,9 @@ export const Refresh = ({ size }: P) => svg(<> svg(, size); export const Library = ({ size }: P) => svg(<>, size); export const Shuffle = ({ size }: P) => svg(<>, size); +export const Plus = ({ size }: P) => svg(, size); +export const Pencil = ({ size }: P) => svg(<>, size); +export const Trash = ({ size }: P) => svg(<>, size); +export const ListMusic = ({ size }: P) => svg(<>, size); +export const Calendar = ({ size }: P) => svg(<>, size); +export const Warning = ({ size }: P) => svg(<>, size); diff --git a/discover/src/styles.css b/discover/src/styles.css index 739fd6d..0f53006 100644 --- a/discover/src/styles.css +++ b/discover/src/styles.css @@ -729,6 +729,282 @@ h2 { cursor: pointer; } +/* ---------- tracked playlists ---------- */ + +.manage { + max-width: 980px; +} + +.manage-header { + margin-bottom: 24px; +} + +.manage-link { + margin-top: 2px; +} + +.manage-link .mix-dot { + color: var(--muted); +} + +.panel { + padding: 18px 20px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); +} + +.panel + .panel { + margin-top: 20px; +} + +.panel-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; +} + +.panel-header h2 { + margin: 0 0 2px; +} + +.hint { + margin: 0; + color: var(--muted); + font-size: 0.85rem; +} + +.hint code, +.template { + padding: 1px 5px; + border-radius: 4px; + background: var(--surface-2); + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; + font-size: 0.85em; +} + +.template { + font-size: 0.95em; +} + +.items { + margin: 0; + padding: 0; + list-style: none; +} + +.item { + border-top: 1px solid var(--border); +} + +.item-row { + display: grid; + grid-template-columns: 40px minmax(0, 1fr) auto auto; + align-items: center; + gap: 14px; + padding: 12px 0; +} + +.item-icon { + display: grid; + place-items: center; + width: 40px; + height: 40px; + border-radius: 10px; + background: var(--surface-2); + color: var(--muted); +} + +.item-title { + overflow: hidden; + font-weight: 600; + text-overflow: ellipsis; + white-space: nowrap; +} + +.item-sub, +.item-aside { + color: var(--muted); + font-size: 0.88rem; +} + +.item-aside { + white-space: nowrap; +} + +.item-actions { + display: flex; + gap: 6px; +} + +.warning-text { + color: var(--youtube); +} + +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + min-height: 34px; + padding: 6px 12px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); + font-size: 0.88rem; + font-weight: 600; + white-space: nowrap; + cursor: pointer; +} + +.btn:hover:not(:disabled) { + background: var(--surface-2); +} + +.btn:disabled { + opacity: 0.55; + cursor: default; +} + +.btn.icon-only { + width: 34px; + padding: 0; + color: var(--muted); +} + +.btn.primary { + border-color: transparent; + background: var(--accent); + color: var(--accent-text); +} + +.btn.primary:hover:not(:disabled) { + background: color-mix(in srgb, var(--accent) 88%, var(--text)); +} + +.btn.danger { + border-color: transparent; + background: var(--youtube); + color: #fff; +} + +.btn .spinner { + width: 14px; + height: 14px; +} + +.form, +.confirm { + display: flex; + flex-direction: column; + gap: 14px; + margin: 4px 0 16px; + padding: 16px; + border-radius: 10px; + background: var(--surface-2); +} + +.item.editing .form { + margin: 12px 0; +} + +.confirm { + margin-top: 0; +} + +.confirm p { + margin: 0; +} + +.form-grid { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1.2fr) 100px; + gap: 12px; +} + +.field { + display: flex; + flex-direction: column; + gap: 5px; + min-width: 0; +} + +.field.wide { + grid-column: 1 / -1; +} + +.field > span, +.field > label { + font-size: 0.82rem; + font-weight: 600; +} + +.field input, +.field select { + width: 100%; + min-height: 38px; + padding: 7px 10px; + border: 1px solid var(--border); + border-radius: 8px; + background: var(--surface); +} + +.field input.mono { + font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; +} + +.checkbox { + display: flex; + align-items: center; + gap: 8px; + font-size: 0.92rem; +} + +.checkbox input { + width: 16px; + height: 16px; + accent-color: var(--youtube); +} + +.form-error { + margin: 0; + color: var(--youtube); + font-size: 0.9rem; +} + +.form-actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} + +.segmented { + display: inline-flex; + align-self: flex-start; + padding: 3px; + border-radius: 9px; + background: var(--surface); + border: 1px solid var(--border); +} + +.segmented button { + padding: 5px 12px; + border: 0; + border-radius: 6px; + background: none; + color: var(--muted); + font-size: 0.88rem; + font-weight: 600; + cursor: pointer; +} + +.segmented button[aria-checked="true"] { + background: var(--accent); + color: var(--accent-text); +} + /* ---------- small screens ---------- */ @media (max-width: 800px) { @@ -805,6 +1081,42 @@ h2 { display: none; } + .panel { + padding: 14px; + } + + .panel-header { + flex-direction: column; + } + + .item-row { + grid-template-columns: 36px minmax(0, 1fr); + gap: 4px 12px; + } + + .item-icon { + width: 36px; + height: 36px; + } + + .item-aside, + .item-actions { + grid-column: 2; + } + + .item-actions { + flex-wrap: wrap; + margin-top: 6px; + } + + .form-grid { + grid-template-columns: minmax(0, 1fr) 90px; + } + + .form-grid .field:not(.wide):not(.narrow) { + grid-column: 1 / -1; + } + .player { grid-template-columns: minmax(0, 1fr) auto; height: auto; diff --git a/src/daemon/update_playlists.rs b/src/daemon/update_playlists.rs index c4f052c..0ec32dc 100644 --- a/src/daemon/update_playlists.rs +++ b/src/daemon/update_playlists.rs @@ -59,7 +59,7 @@ pub async fn update_playlists_daemon( } } -async fn update_playlist( +pub async fn update_playlist( media_client: impl AsRef, playlist: TrackedPlaylist, ) -> Result<(), Box> { diff --git a/src/main.rs b/src/main.rs index fce4aa3..8237cd2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,6 +7,7 @@ mod models; mod playlist; mod subsonic; mod track; +mod tracked; mod web; mod youtube; @@ -87,6 +88,7 @@ async fn main() -> Result<(), Box> { .manage(database) .manage(youtube) .mount("/api/discover", web::routes()) + .mount("/api/tracked", tracked::routes()) .mount( "/api/playlist", routes![ diff --git a/src/subsonic.rs b/src/subsonic.rs index 25c0ef8..cf0d070 100644 --- a/src/subsonic.rs +++ b/src/subsonic.rs @@ -43,6 +43,17 @@ struct GetPlaylistResponse { type CreatePlaylistResponse = GetPlaylistResponse; +#[derive(Deserialize)] +struct GetPlaylistsResponse { + playlists: PlaylistList, +} + +#[derive(Deserialize)] +struct PlaylistList { + #[serde(default)] + playlist: Vec, +} + #[derive(Deserialize)] struct GetGenresResponse { genres: GenreList, @@ -287,6 +298,15 @@ impl Subsonic { request.send().await.map_err(SubsonicError::Reqwest) } + /// All of the user's playlists, without their songs + pub async fn get_playlists(&self) -> Result, SubsonicError> { + Ok(self + .request::("getPlaylists", &[]) + .await? + .playlists + .playlist) + } + /// All genres in the library pub async fn get_genres(&self) -> Result, SubsonicError> { Ok(self diff --git a/src/tracked.rs b/src/tracked.rs new file mode 100644 index 0000000..662840b --- /dev/null +++ b/src/tracked.rs @@ -0,0 +1,569 @@ +//! API for managing tracked playlists (Subsonic playlists kept up to date with a Listenbrainz +//! user's top songs) and the rules that create them on a schedule. + +use crate::daemon::update_playlists::update_playlist; +use crate::listenbrainz::StatsRange; +use crate::models::{CreateTrackedPlaylist, TrackedPlaylist}; +use crate::subsonic::Subsonic; +use chrono::format::{Item, StrftimeItems}; +use chrono::Local; +use rocket::http::Status; +use rocket::response::status::Custom; +use rocket::serde::json::Json; +use rocket::{delete, get, post, put, routes, Route, State}; +use serde::{Deserialize, Serialize}; +use sqlx::postgres::PgPool; +use std::collections::HashMap; +use std::sync::Arc; +use uuid::Uuid; + +pub fn routes() -> Vec { + routes![ + playlists, + create_playlist, + update_tracked_playlist, + delete_tracked_playlist, + refresh, + subsonic_playlists, + rules, + create_rule, + update_rule, + delete_rule, + preview_name + ] +} + +#[derive(Serialize)] +pub struct ApiError { + error: String, +} + +type ApiResult = Result, Custom>>; + +fn fail(status: Status, message: impl Into) -> Custom> { + Custom( + status, + Json(ApiError { + error: message.into(), + }), + ) +} + +fn db_error(e: sqlx::Error) -> Custom> { + match e { + sqlx::Error::RowNotFound => fail(Status::NotFound, "Not found"), + e => { + println!("Database error: {:?}", e); + fail(Status::InternalServerError, "Database error") + } + } +} + +fn subsonic_error(e: impl std::fmt::Debug) -> Custom> { + println!("Subsonic error: {:?}", e); + fail(Status::BadGateway, "Couldn't reach Subsonic") +} + +fn parse_id(id: &str) -> Result>> { + Uuid::parse_str(id).map_err(|_| fail(Status::NotFound, "Not found")) +} + +/// Settings shared by tracked playlists and rules +#[derive(Deserialize)] +struct Tracking { + playlist_size: i32, + tracking_user: String, + tracking_type: String, +} + +impl Tracking { + fn validate(&self) -> Result<(), Custom>> { + if !(1..=1000).contains(&self.playlist_size) { + return Err(fail( + Status::UnprocessableEntity, + "Size must be between 1 and 1000", + )); + } + if self.tracking_user.trim().is_empty() { + return Err(fail( + Status::UnprocessableEntity, + "Enter a Listenbrainz user", + )); + } + if StatsRange::from_param(&self.tracking_type).is_none() { + return Err(fail(Status::UnprocessableEntity, "Unknown time period")); + } + Ok(()) + } +} + +/// Format a playlist name template, or explain why it's invalid +fn format_template(template: &str) -> Result>> { + if template.trim().is_empty() { + return Err(fail(Status::UnprocessableEntity, "Enter a name")); + } + // chrono panics when displaying a format with invalid specifiers + if StrftimeItems::new(template).any(|item| matches!(item, Item::Error)) { + return Err(fail( + Status::UnprocessableEntity, + "The name has an invalid % code (use %% for a literal %)", + )); + } + Ok(Local::now().format(template).to_string()) +} + +// --------------------------------------------------------------------------- +// Tracked playlists +// --------------------------------------------------------------------------- + +#[derive(Serialize)] +struct TrackedPlaylistView { + id: Uuid, + playlist_id: Option, + /// Name in Subsonic; None if the playlist no longer exists there + name: Option, + song_count: Option, + playlist_size: i32, + tracking_user: String, + tracking_type: String, +} + +async fn view( + media_client: &Subsonic, + rows: Vec, +) -> Result, Custom>> { + let subsonic: HashMap = media_client + .get_playlists() + .await + .map_err(subsonic_error)? + .into_iter() + .map(|p| (p.id, (p.name, p.song_count))) + .collect(); + + Ok(rows + .into_iter() + .map(|row| { + let found = row.playlist_id.as_ref().and_then(|id| subsonic.get(id)); + TrackedPlaylistView { + id: row.id, + name: found.map(|(name, _)| name.clone()), + song_count: found.map(|(_, count)| *count), + playlist_id: row.playlist_id, + playlist_size: row.playlist_size, + tracking_user: row.tracking_user, + tracking_type: row.tracking_type, + } + }) + .collect()) +} + +#[get("/playlists")] +async fn playlists( + pool: &State, + media_client: &State>, +) -> ApiResult> { + let mut rows = TrackedPlaylist::all(pool.inner()).await.map_err(db_error)?; + rows.sort_by(|a, b| a.tracking_user.cmp(&b.tracking_user)); + let mut out = view(media_client, rows).await?; + out.sort_by(|a, b| { + a.name + .as_deref() + .unwrap_or("") + .to_lowercase() + .cmp(&b.name.as_deref().unwrap_or("").to_lowercase()) + }); + Ok(Json(out)) +} + +#[derive(Deserialize)] +struct NewTrackedPlaylist { + /// Track this existing Subsonic playlist... + playlist_id: Option, + /// ...or create a new one with this name + name: Option, + #[serde(flatten)] + tracking: Tracking, +} + +#[post("/playlists", data = "")] +async fn create_playlist( + body: Json, + pool: &State, + media_client: &State>, +) -> ApiResult { + body.tracking.validate()?; + + let playlist_id = match (&body.playlist_id, body.name.as_deref().map(str::trim)) { + (Some(id), _) => { + media_client + .get_playlist(id) + .await + .map_err(|_| fail(Status::UnprocessableEntity, "That playlist doesn't exist"))?; + let tracked = sqlx::query_scalar!( + r#"SELECT COUNT(*) AS "count!" FROM "tracked_playlist" WHERE playlist_id = $1"#, + id + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + if tracked > 0 { + return Err(fail( + Status::Conflict, + "That playlist is already being tracked", + )); + } + if mix_playlist_ids(pool.inner()).await?.contains(id) { + return Err(fail( + Status::Conflict, + "That's a genre mix, which playlistd already keeps up to date", + )); + } + id.clone() + } + (None, Some(name)) if !name.is_empty() => { + media_client + .create_playlist(name) + .await + .map_err(subsonic_error)? + .id + } + _ => { + return Err(fail( + Status::UnprocessableEntity, + "Choose a playlist or enter a name", + )) + } + }; + + let id = Uuid::new_v4(); + sqlx::query!( + r#" + INSERT INTO "tracked_playlist" (id, playlist_id, playlist_size, tracking_user, tracking_type) + VALUES ($1, $2, $3, $4, $5) + "#, + id, + playlist_id, + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +#[derive(Deserialize)] +struct TrackedPlaylistUpdate { + /// Rename the playlist in Subsonic + name: Option, + #[serde(flatten)] + tracking: Tracking, +} + +#[put("/playlists/", data = "")] +async fn update_tracked_playlist( + id: &str, + body: Json, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + body.tracking.validate()?; + + let row = sqlx::query_as!( + TrackedPlaylist, + r#" + UPDATE "tracked_playlist" SET playlist_size = $1, tracking_user = $2, tracking_type = $3 + WHERE id = $4 + RETURNING * + "#, + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + id, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + if let (Some(name), Some(playlist_id)) = (body.name.as_deref().map(str::trim), &row.playlist_id) + { + if !name.is_empty() { + media_client + .rename_playlist(playlist_id, name) + .await + .map_err(subsonic_error)?; + } + } + + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +/// Stop tracking a playlist, optionally deleting it from Subsonic too +#[delete("/playlists/?")] +async fn delete_tracked_playlist( + id: &str, + delete_playlist: Option, + pool: &State, + media_client: &State>, +) -> Result>> { + let row = sqlx::query_as!( + TrackedPlaylist, + r#"DELETE FROM "tracked_playlist" WHERE id = $1 RETURNING *"#, + parse_id(id)? + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + + if delete_playlist.unwrap_or(false) { + if let Some(playlist_id) = row.playlist_id { + // it may already be gone from Subsonic + if let Err(e) = media_client.delete_playlist(&playlist_id).await { + println!("Could not delete playlist {}: {:?}", playlist_id, e); + } + } + } + Ok(Status::NoContent) +} + +/// Update a tracked playlist's songs now, rather than on the next daemon tick +#[post("/playlists//refresh")] +async fn refresh( + id: &str, + pool: &State, + media_client: &State>, +) -> ApiResult { + let id = parse_id(id)?; + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + + let result = update_playlist(media_client.inner().clone(), row) + .await + .map_err(|e| e.to_string()); + if let Err(e) = result { + return Err(fail( + Status::BadGateway, + format!("Couldn't update the playlist: {}", e), + )); + } + + let row = TrackedPlaylist::rule(pool.inner(), id) + .await + .map_err(db_error)?; + Ok(Json(view(media_client, vec![row]).await?.remove(0))) +} + +#[derive(Serialize)] +struct SubsonicPlaylist { + id: String, + name: String, + song_count: usize, + tracked: bool, +} + +/// Playlists maintained as genre mixes, which mustn't also be tracked +async fn mix_playlist_ids(pool: &PgPool) -> Result, Custom>> { + sqlx::query_scalar!(r#"SELECT playlist_id FROM "cluster_mix_playlist""#) + .fetch_all(pool) + .await + .map_err(db_error) +} + +/// Subsonic playlists that could be tracked (genre mixes are left out) +#[get("/subsonic-playlists")] +async fn subsonic_playlists( + pool: &State, + media_client: &State>, +) -> ApiResult> { + let tracked: Vec = TrackedPlaylist::all(pool.inner()) + .await + .map_err(db_error)? + .into_iter() + .filter_map(|p| p.playlist_id) + .collect(); + let mixes = mix_playlist_ids(pool.inner()).await?; + let mut out: Vec = media_client + .get_playlists() + .await + .map_err(subsonic_error)? + .into_iter() + .filter(|p| !mixes.contains(&p.id)) + .map(|p| SubsonicPlaylist { + tracked: tracked.contains(&p.id), + id: p.id, + name: p.name, + song_count: p.song_count, + }) + .collect(); + out.sort_by_key(|p| p.name.to_lowercase()); + Ok(Json(out)) +} + +// --------------------------------------------------------------------------- +// Rules +// --------------------------------------------------------------------------- + +#[derive(Serialize)] +struct RuleView { + #[serde(flatten)] + rule: CreateTrackedPlaylist, + /// The name the rule's next playlist will have, if it differs from the last one + current_name: Option, +} + +fn rule_view(rule: CreateTrackedPlaylist) -> RuleView { + RuleView { + current_name: format_template(&rule.name_template).ok(), + rule, + } +} + +#[get("/rules")] +async fn rules(pool: &State) -> ApiResult> { + let mut rules = CreateTrackedPlaylist::all(pool.inner()) + .await + .map_err(db_error)?; + rules.sort_by(|a, b| a.name_template.cmp(&b.name_template)); + Ok(Json(rules.into_iter().map(rule_view).collect())) +} + +#[derive(Deserialize)] +struct RuleBody { + name_template: String, + #[serde(flatten)] + tracking: Tracking, +} + +#[post("/rules", data = "")] +async fn create_rule(body: Json, pool: &State) -> ApiResult { + body.tracking.validate()?; + format_template(&body.name_template)?; + + let rule = sqlx::query_as!( + CreateTrackedPlaylist, + r#" + INSERT INTO "create_tracked_playlist" (id, name_template, playlist_size, tracking_user, tracking_type) + VALUES ($1, $2, $3, $4, $5) + RETURNING * + "#, + Uuid::new_v4(), + body.name_template.trim(), + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + Ok(Json(rule_view(rule))) +} + +/// Changes apply to playlists the rule creates from now on +#[put("/rules/", data = "")] +async fn update_rule(id: &str, body: Json, pool: &State) -> ApiResult { + body.tracking.validate()?; + format_template(&body.name_template)?; + + let rule = sqlx::query_as!( + CreateTrackedPlaylist, + r#" + UPDATE "create_tracked_playlist" + SET name_template = $1, playlist_size = $2, tracking_user = $3, tracking_type = $4 + WHERE id = $5 + RETURNING * + "#, + body.name_template.trim(), + body.tracking.playlist_size, + body.tracking.tracking_user.trim(), + body.tracking.tracking_type, + parse_id(id)?, + ) + .fetch_one(pool.inner()) + .await + .map_err(db_error)?; + Ok(Json(rule_view(rule))) +} + +/// Delete a rule. Playlists it already created keep being tracked. +#[delete("/rules/")] +async fn delete_rule(id: &str, pool: &State) -> Result>> { + let result = sqlx::query!( + r#"DELETE FROM "create_tracked_playlist" WHERE id = $1"#, + parse_id(id)? + ) + .execute(pool.inner()) + .await + .map_err(db_error)?; + if result.rows_affected() == 0 { + return Err(fail(Status::NotFound, "Not found")); + } + Ok(Status::NoContent) +} + +#[derive(Serialize)] +struct NamePreview { + name: String, +} + +/// What a name template produces today +#[get("/preview-name?