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 { Vec::new() } #[derive(Clone)] pub struct Subsonic { username: String, password: String, base: String, client: Client, } #[derive(Serialize, Deserialize)] pub struct SubsonicResponse { #[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, } #[derive(Serialize, Deserialize)] struct GetPlaylistResponse { playlist: Playlist, } 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, } #[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, 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::>() .await .map_err(|e| SubsonicError::Reqwest(e))? .subsonic_response .search_results .song) } pub async fn get_playlist( &self, playlist_id: impl ToString, ) -> Result { 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::>() .await .map_err(|e| SubsonicError::Reqwest(e))? .subsonic_response .playlist) } pub async fn create_playlist( &self, playlist_name: impl ToString, ) -> Result { 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::>() .await .map_err(|e| SubsonicError::Reqwest(e))? .subsonic_response .playlist) } pub async fn update_playlist( &self, playlist_id: String, add: Vec, remove: Vec, ) -> Result { 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( &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)] pub struct SubsonicBuilder { username: Option, password: Option, base: Option, } #[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> { 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(), }) } }