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 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018opPJMJjLWr4RqdG6vuK6p
213 lines
5.9 KiB
Rust
213 lines
5.9 KiB
Rust
mod cluster;
|
|
mod daemon;
|
|
mod listenbrainz;
|
|
mod mix;
|
|
mod models;
|
|
mod playlist;
|
|
mod subsonic;
|
|
mod track;
|
|
|
|
use crate::daemon::{cluster_mixes_daemon, create_playlists_daemon, update_playlists_daemon};
|
|
use crate::models::{
|
|
ClusterMixRule, CreateTrackedPlaylist, PartialClusterMixRule, PartialCreateTrackedPlaylist,
|
|
PartialTrackedPlaylist, TrackedPlaylist,
|
|
};
|
|
use crate::subsonic::{Subsonic, SubsonicBuilder};
|
|
use config::Config;
|
|
use rocket::serde::json::{json, Json};
|
|
use rocket::{get, post, routes, serde::json::Value as JsonValue, State};
|
|
use serde::{Deserialize, Serialize};
|
|
use sqlx::postgres::PgPool;
|
|
use std::sync::{Arc, OnceLock};
|
|
|
|
pub static CONFIG: OnceLock<Config> = OnceLock::new();
|
|
|
|
#[tokio::main]
|
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|
CONFIG
|
|
.set(
|
|
Config::builder()
|
|
.add_source(config::File::with_name("playlistd").required(false))
|
|
.add_source(config::Environment::default().separator("_"))
|
|
.build()
|
|
.unwrap(),
|
|
)
|
|
.unwrap();
|
|
|
|
let database = PgPool::connect(
|
|
CONFIG
|
|
.get()
|
|
.unwrap()
|
|
.get::<String>("database.url")?
|
|
.as_str(),
|
|
)
|
|
.await?;
|
|
sqlx::migrate!().run(&database).await?;
|
|
|
|
let media_client = Arc::new(
|
|
SubsonicBuilder::new()
|
|
.base(CONFIG.get().unwrap().get::<String>("subsonic.base")?)
|
|
.username(CONFIG.get().unwrap().get::<String>("subsonic.username")?)
|
|
.password(CONFIG.get().unwrap().get::<String>("subsonic.password")?)
|
|
.build()?,
|
|
);
|
|
|
|
{
|
|
let _media_client = media_client.clone();
|
|
tokio::spawn(async move {
|
|
update_playlists_daemon(_media_client).await.unwrap();
|
|
});
|
|
}
|
|
{
|
|
let _media_client = media_client.clone();
|
|
tokio::spawn(async move {
|
|
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)
|
|
.manage(database)
|
|
.mount(
|
|
"/api/playlist",
|
|
routes![
|
|
create_tracking_playlist,
|
|
add_tracking_playlist,
|
|
all_playlists,
|
|
create_tracking_playlist_rule,
|
|
create_cluster_mix_rule,
|
|
all_cluster_mix_rules,
|
|
],
|
|
)
|
|
.launch()
|
|
.await?;
|
|
|
|
Ok(())
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct JsonError {
|
|
error: String,
|
|
}
|
|
|
|
impl From<sqlx::Error> for JsonError {
|
|
fn from(value: sqlx::Error) -> Self {
|
|
Self {
|
|
error: value.to_string(),
|
|
}
|
|
}
|
|
}
|
|
|
|
impl From<uuid::Error> for JsonError {
|
|
fn from(value: uuid::Error) -> Self {
|
|
Self {
|
|
error: value.to_string(),
|
|
}
|
|
}
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
enum Response<T> {
|
|
Success(T),
|
|
Error(JsonError),
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
pub struct CreatePlaylist {
|
|
pub playlist_name: String,
|
|
pub playlist_size: i32,
|
|
pub tracking_user: Option<String>,
|
|
pub tracking_type: Option<String>,
|
|
}
|
|
|
|
/// Create a new playlist and attach a tracker
|
|
#[post("/rule", data = "<create_playlist_rule>")]
|
|
async fn create_tracking_playlist_rule(
|
|
pool: &State<PgPool>,
|
|
create_playlist_rule: Json<PartialCreateTrackedPlaylist>,
|
|
) -> Json<Response<CreateTrackedPlaylist>> {
|
|
match create_playlist_rule.record(pool.inner()).await {
|
|
Ok(playlist) => Json(Response::Success(playlist)),
|
|
Err(e) => Json(Response::Error(e.into())),
|
|
}
|
|
}
|
|
|
|
/// Create a new playlist and attach a tracker
|
|
#[post("/create", data = "<create_playlist>")]
|
|
async fn create_tracking_playlist(
|
|
media_client: &State<Arc<Subsonic>>,
|
|
pool: &State<PgPool>,
|
|
create_playlist: Json<CreatePlaylist>,
|
|
) -> Json<Response<TrackedPlaylist>> {
|
|
match media_client
|
|
.create_playlist(create_playlist.playlist_name.clone())
|
|
.await
|
|
{
|
|
Ok(created_playlist) => {
|
|
let partial = PartialTrackedPlaylist {
|
|
playlist_id: created_playlist.id,
|
|
playlist_size: create_playlist.playlist_size,
|
|
tracking_user: create_playlist.tracking_user.clone(),
|
|
tracking_type: create_playlist.tracking_type.clone(),
|
|
};
|
|
|
|
match partial.record(pool.inner()).await {
|
|
Ok(playlist) => Json(Response::Success(playlist)),
|
|
Err(e) => Json(Response::Error(e.into())),
|
|
}
|
|
}
|
|
|
|
Err(_) => Json(Response::Error(JsonError {
|
|
error: "Couldn't create Subsonic playlist".to_string(),
|
|
})),
|
|
}
|
|
}
|
|
|
|
/// Add tracking to an existing playlist
|
|
#[post("/track", data = "<playlist>")]
|
|
async fn add_tracking_playlist(
|
|
pool: &State<PgPool>,
|
|
playlist: Json<PartialTrackedPlaylist>,
|
|
) -> Json<Response<TrackedPlaylist>> {
|
|
match playlist.record(pool.inner()).await {
|
|
Ok(playlist) => Json(Response::Success(playlist)),
|
|
Err(e) => Json(Response::Error(e.into())),
|
|
}
|
|
}
|
|
|
|
/// Get all tracked playlists
|
|
#[get("/")]
|
|
async fn all_playlists(pool: &State<PgPool>) -> JsonValue {
|
|
match TrackedPlaylist::all(pool.inner()).await {
|
|
Ok(playlists) => json!(playlists),
|
|
Err(_) => json!([]),
|
|
}
|
|
}
|
|
|
|
/// Create a rule that maintains genre mixes built from clustering a user's recent listens
|
|
#[post("/mix", data = "<rule>")]
|
|
async fn create_cluster_mix_rule(
|
|
pool: &State<PgPool>,
|
|
rule: Json<PartialClusterMixRule>,
|
|
) -> Json<Response<ClusterMixRule>> {
|
|
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<PgPool>) -> JsonValue {
|
|
match ClusterMixRule::all(pool.inner()).await {
|
|
Ok(rules) => json!(rules),
|
|
Err(_) => json!([]),
|
|
}
|
|
}
|