Add API endpoint to get liked songs
This commit is contained in:
@ -16,6 +16,7 @@ cfg_if! {
|
||||
use diesel::prelude::*;
|
||||
use diesel::dsl::count;
|
||||
use crate::models::backend::{Album, Artist, Song, HistoryEntry};
|
||||
use crate::models::backend;
|
||||
use crate::schema::*;
|
||||
|
||||
use std::collections::HashMap;
|
||||
@ -373,3 +374,73 @@ pub async fn top_artists(
|
||||
|
||||
Ok(artist_data)
|
||||
}
|
||||
|
||||
#[server(endpoint = "/profile/liked_songs", client = Client)]
|
||||
pub async fn get_liked_songs() -> Result<Vec<frontend::Song>, ServerFnError> {
|
||||
let user_id = get_user()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ServerFnError::<NoCustomError>::ServerError(format!("Error getting user: {e}"))
|
||||
})?
|
||||
.id;
|
||||
|
||||
let mut db_conn = get_db_conn();
|
||||
|
||||
let songs: Vec<(
|
||||
backend::Song,
|
||||
Option<backend::Album>,
|
||||
Option<backend::Artist>,
|
||||
)> = crate::schema::song_likes::table
|
||||
.filter(crate::schema::song_likes::user_id.eq(user_id))
|
||||
.inner_join(
|
||||
crate::schema::songs::table
|
||||
.on(crate::schema::song_likes::song_id.eq(crate::schema::songs::id)),
|
||||
)
|
||||
.left_join(albums::table.on(songs::album_id.eq(albums::id.nullable())))
|
||||
.left_join(
|
||||
song_artists::table
|
||||
.inner_join(artists::table)
|
||||
.on(songs::id.eq(song_artists::song_id)),
|
||||
)
|
||||
.select((
|
||||
songs::all_columns,
|
||||
albums::all_columns.nullable(),
|
||||
artists::all_columns.nullable(),
|
||||
))
|
||||
.load(&mut db_conn)?;
|
||||
|
||||
let mut liked_songs: HashMap<i32, frontend::Song> = HashMap::new();
|
||||
|
||||
for (song, album, artist) in songs {
|
||||
if let Some(stored_songdata) = liked_songs.get_mut(&song.id) {
|
||||
if let Some(artist) = artist {
|
||||
stored_songdata.artists.push(artist);
|
||||
}
|
||||
} else {
|
||||
let image_path = song.image_path.unwrap_or(
|
||||
album
|
||||
.as_ref()
|
||||
.and_then(|album| album.image_path.clone())
|
||||
.unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string()),
|
||||
);
|
||||
|
||||
let songdata = frontend::Song {
|
||||
id: song.id,
|
||||
title: song.title,
|
||||
artists: artist.map(|artist| vec![artist]).unwrap_or_default(),
|
||||
album,
|
||||
track: song.track,
|
||||
duration: song.duration,
|
||||
release_date: song.release_date,
|
||||
song_path: song.storage_path,
|
||||
image_path,
|
||||
like_dislike: Some((true, false)),
|
||||
added_date: song.added_date,
|
||||
};
|
||||
|
||||
liked_songs.insert(song.id, songdata);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(liked_songs.into_values().collect())
|
||||
}
|
||||
|
Reference in New Issue
Block a user