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
394 lines
10 KiB
Rust
394 lines
10 KiB
Rust
use crate::playlist::Playlist;
|
|
use crate::track::Track;
|
|
use reqwest::Client;
|
|
use serde::{Deserialize, Serialize};
|
|
use std::fmt::{Display, Formatter};
|
|
use thiserror::Error;
|
|
use uuid::Uuid;
|
|
|
|
fn default_vec() -> Vec<Track> {
|
|
Vec::new()
|
|
}
|
|
|
|
#[derive(Clone)]
|
|
pub struct Subsonic {
|
|
username: String,
|
|
password: String,
|
|
base: String,
|
|
client: Client,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
pub struct SubsonicResponse<T> {
|
|
#[serde(rename = "subsonic-response")]
|
|
subsonic_response: T,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct SearchResponse {
|
|
#[serde(rename = "searchResult3")]
|
|
search_results: SearchResponseSongs,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct SearchResponseSongs {
|
|
#[serde(default = "default_vec")]
|
|
song: Vec<Track>,
|
|
}
|
|
|
|
#[derive(Serialize, Deserialize)]
|
|
struct GetPlaylistResponse {
|
|
playlist: Playlist,
|
|
}
|
|
|
|
type CreatePlaylistResponse = GetPlaylistResponse;
|
|
|
|
#[derive(Deserialize)]
|
|
struct GetGenresResponse {
|
|
genres: GenreList,
|
|
}
|
|
|
|
#[derive(Deserialize)]
|
|
struct GenreList {
|
|
#[serde(default)]
|
|
genre: Vec<Genre>,
|
|
}
|
|
|
|
#[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,
|
|
}
|
|
|
|
#[derive(Debug, Error)]
|
|
pub enum SubsonicError {
|
|
Reqwest(reqwest::Error),
|
|
Api(String),
|
|
Json(serde_json::Error),
|
|
}
|
|
|
|
impl Display for SubsonicError {
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
write!(f, "{:?}", self)
|
|
}
|
|
}
|
|
|
|
impl Subsonic {
|
|
fn auth_params(&self) -> AuthParams {
|
|
let salt = Uuid::new_v4().simple().to_string();
|
|
let hash = format!(
|
|
"{:?}",
|
|
md5::compute(format!("{}{}", self.password, salt).into_bytes())
|
|
);
|
|
|
|
AuthParams { salt, hash }
|
|
}
|
|
|
|
pub async fn song_search(&self, query: String) -> Result<Vec<Track>, SubsonicError> {
|
|
let auth_params = self.auth_params();
|
|
let query_params = [
|
|
("query", query.as_str()),
|
|
("artistCount", "0"),
|
|
("albumCount", "0"),
|
|
("u", self.username.as_str()),
|
|
("s", auth_params.salt.as_str()),
|
|
("t", auth_params.hash.as_str()),
|
|
("v", "16"),
|
|
("c", "playlistd"),
|
|
("f", "json"),
|
|
];
|
|
|
|
Ok(self
|
|
.client
|
|
.get(format!("{}/search3", self.base))
|
|
.query(&query_params)
|
|
.send()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?
|
|
.json::<SubsonicResponse<SearchResponse>>()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?
|
|
.subsonic_response
|
|
.search_results
|
|
.song)
|
|
}
|
|
|
|
pub async fn get_playlist(
|
|
&self,
|
|
playlist_id: impl ToString,
|
|
) -> Result<Playlist, SubsonicError> {
|
|
let auth_params = self.auth_params();
|
|
|
|
let get_params = [
|
|
("u", self.username.to_string()),
|
|
("s", auth_params.salt.to_string()),
|
|
("t", auth_params.hash.to_string()),
|
|
("v", String::from("16")),
|
|
("c", String::from("playlistd")),
|
|
("f", String::from("json")),
|
|
("id", playlist_id.to_string()),
|
|
];
|
|
|
|
Ok(self
|
|
.client
|
|
.get(format!("{}/getPlaylist", self.base))
|
|
.query(&get_params)
|
|
.send()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?
|
|
.json::<SubsonicResponse<GetPlaylistResponse>>()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?
|
|
.subsonic_response
|
|
.playlist)
|
|
}
|
|
|
|
pub async fn create_playlist(
|
|
&self,
|
|
playlist_name: impl ToString,
|
|
) -> Result<Playlist, SubsonicError> {
|
|
let auth_params = self.auth_params();
|
|
|
|
let get_params = [
|
|
("u", self.username.to_string()),
|
|
("s", auth_params.salt.to_string()),
|
|
("t", auth_params.hash.to_string()),
|
|
("v", String::from("16")),
|
|
("c", String::from("playlistd")),
|
|
("f", String::from("json")),
|
|
("name", playlist_name.to_string()),
|
|
];
|
|
|
|
Ok(self
|
|
.client
|
|
.get(format!("{}/createPlaylist", self.base))
|
|
.query(&get_params)
|
|
.send()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?
|
|
.json::<SubsonicResponse<CreatePlaylistResponse>>()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?
|
|
.subsonic_response
|
|
.playlist)
|
|
}
|
|
|
|
pub async fn update_playlist(
|
|
&self,
|
|
playlist_id: String,
|
|
add: Vec<String>,
|
|
remove: Vec<usize>,
|
|
) -> Result<Playlist, SubsonicError> {
|
|
let auth_params = self.auth_params();
|
|
|
|
let mut update_query = vec![
|
|
("u", self.username.to_string()),
|
|
("s", auth_params.salt.to_string()),
|
|
("t", auth_params.hash.to_string()),
|
|
("v", String::from("16")),
|
|
("c", String::from("playlistd")),
|
|
("f", String::from("json")),
|
|
("playlistId", playlist_id.clone()),
|
|
];
|
|
|
|
for id in add {
|
|
update_query.push(("songIdToAdd", id));
|
|
}
|
|
|
|
for index in remove {
|
|
update_query.push(("songIndexToRemove", index.to_string()));
|
|
}
|
|
|
|
self.client
|
|
.get(format!("{}/updatePlaylist", self.base))
|
|
.query(&update_query)
|
|
.send()
|
|
.await
|
|
.map_err(|e| SubsonicError::Reqwest(e))?;
|
|
|
|
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<T: serde::de::DeserializeOwned>(
|
|
&self,
|
|
endpoint: &str,
|
|
params: &[(&'static str, String)],
|
|
) -> Result<T, SubsonicError> {
|
|
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::<SubsonicResponse<serde_json::Value>>()
|
|
.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<Vec<Genre>, SubsonicError> {
|
|
Ok(self
|
|
.request::<GetGenresResponse>("getGenres", &[])
|
|
.await?
|
|
.genres
|
|
.genre)
|
|
}
|
|
|
|
/// Up to `limit` songs with the given genre
|
|
pub async fn songs_by_genre(
|
|
&self,
|
|
genre: &str,
|
|
limit: usize,
|
|
) -> Result<Vec<Track>, 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::<SongsByGenreResponse>(
|
|
"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::<serde_json::Value>(
|
|
"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<String>,
|
|
) -> Result<Playlist, SubsonicError> {
|
|
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::<serde_json::Value>("deletePlaylist", &[("id", playlist_id.to_string())])
|
|
.await?;
|
|
Ok(())
|
|
}
|
|
}
|
|
|
|
#[derive(Default)]
|
|
pub struct SubsonicBuilder {
|
|
username: Option<String>,
|
|
password: Option<String>,
|
|
base: Option<String>,
|
|
}
|
|
|
|
#[derive(Debug, Error)]
|
|
enum SubsonicBuilderError {
|
|
#[error("Field not provided")]
|
|
MissingField,
|
|
}
|
|
|
|
impl SubsonicBuilder {
|
|
pub fn new() -> Self {
|
|
Self {
|
|
..Default::default()
|
|
}
|
|
}
|
|
|
|
pub fn username(mut self, username: String) -> Self {
|
|
self.username = Some(username);
|
|
self
|
|
}
|
|
|
|
pub fn password(mut self, password: String) -> Self {
|
|
self.password = Some(password);
|
|
self
|
|
}
|
|
|
|
pub fn base(mut self, base: String) -> Self {
|
|
self.base = Some(base);
|
|
self
|
|
}
|
|
|
|
pub fn build(self) -> Result<Subsonic, Box<dyn std::error::Error>> {
|
|
Ok(Subsonic {
|
|
username: self.username.ok_or(SubsonicBuilderError::MissingField)?,
|
|
password: self.password.ok_or(SubsonicBuilderError::MissingField)?,
|
|
base: self.base.ok_or(SubsonicBuilderError::MissingField)?,
|
|
client: Default::default(),
|
|
})
|
|
}
|
|
}
|