Compare commits

...

15 Commits

17 changed files with 966 additions and 69 deletions

View File

@ -0,0 +1,2 @@
-- This file should undo anything in `up.sql`
DROP TABLE playlists;

View File

@ -0,0 +1,13 @@
-- Your SQL goes here
CREATE TABLE playlists (
id SERIAL PRIMARY KEY UNIQUE NOT NULL,
name VARCHAR NOT NULL,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL
);
CREATE TABLE playlist_songs (
playlist_id INTEGER REFERENCES playlists(id) ON DELETE CASCADE NOT NULL,
song_id INTEGER REFERENCES songs(id) ON DELETE CASCADE NOT NULL,
position INTEGER NOT NULL,
PRIMARY KEY (playlist_id, song_id)
);

2
src/api/mod.rs Normal file
View File

@ -0,0 +1,2 @@
pub mod playlists;
pub mod songs;

157
src/api/playlists.rs Normal file
View File

@ -0,0 +1,157 @@
use leptos::*;
use crate::models::Playlist;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::database::get_db_conn;
use diesel::prelude::*;
use leptos_axum::extract;
use axum_login::AuthSession;
use crate::auth_backend::AuthBackend;
}
}
/// Create a new, empty playlist in the database
///
/// # Arguments
///
/// * `new_playlist` - The new playlist
/// * `conn` - A mutable reference to a database connection
///
/// # Returns
///
/// * `Result<(), Box<dyn Error>>` - A empty result if successful, or an error
///
#[server(endpoint = "playlists/create-playlist")]
pub async fn create_playlist(playlist_name: String)->Result<(), ServerFnError> {
use crate::schema::playlists::dsl::*;
use leptos::server_fn::error::NoCustomError;
let auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
//Ensure the playlist has no id
let new_playlist = Playlist {
id: None,
name: playlist_name,
user_id: auth_session.user.unwrap().id.expect("User has no id"),
};
let db_con = &mut get_db_conn();
diesel::insert_into(playlists)
.values(&new_playlist)
.execute(db_con)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error creating playlist: {}", e)))?;
Ok(())
}
/// Get all playlists for the current user
///
/// # Returns
///
/// * `Result<Vec<Playlist>, ServerFnError>` - A vector of playlists if successful, or an error
///
#[server(endpoint = "playlists/get-playlists")]
pub async fn get_playlists() -> Result<Vec<Playlist>, ServerFnError> {
use crate::schema::playlists::dsl::*;
use leptos::server_fn::error::NoCustomError;
let auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
let other_user_id = auth_session.user.unwrap().id.expect("User has no id");
let db_con = &mut get_db_conn();
let results = playlists
.filter(user_id.eq(other_user_id))
.load::<Playlist>(db_con)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting playlists: {}", e)))?;
Ok(results)
}
/// Add a song to a playlist
///
/// # Arguments
///
/// * `playlist_id` - The id of the playlist
/// * `song_id` - The id of the song
///
/// # Returns
///
/// * `Result<(), ServerFnError>` - An empty result if successful, or an error
///
#[server(endpoint = "playlists/add-song")]
pub async fn add_song(new_playlist_id: Option<i32>, new_song_id: Option<i32>) -> Result<(), ServerFnError> {
use crate::schema::playlist_songs::dsl::*;
use leptos::server_fn::error::NoCustomError;
let other_playlist_id = new_playlist_id.ok_or(ServerFnError::<NoCustomError>::ServerError("Playlist id must be present (Some) to add song".to_string()))?;
let other_song_id = new_song_id.ok_or(ServerFnError::<NoCustomError>::ServerError("Song id must be present (Some) to add song".to_string()))?;
let db_con = &mut get_db_conn();
diesel::insert_into(playlist_songs)
.values((playlist_id.eq(other_playlist_id), song_id.eq(other_song_id)))
.execute(db_con)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error adding song to playlist: {}", e)))?;
Ok(())
}
/// Get songs from a playlist
///
/// # Arguments
///
/// * `playlist_id` - The id of the playlist
///
/// # Returns
///
/// * `Result<Vec<Song>, ServerFnError>` - A vector of songs if successful, or an error
///
#[server(endpoint = "playlists/get-songs")]
pub async fn get_songs(new_playlist_id: Option<i32>) -> Result<Vec<crate::models::Song>, ServerFnError> {
use crate::schema::playlist_songs::dsl::*;
use crate::schema::songs::dsl::*;
use leptos::server_fn::error::NoCustomError;
let other_playlist_id = new_playlist_id.ok_or(ServerFnError::<NoCustomError>::ServerError("Playlist id must be present (Some) to get songs".to_string()))?;
let db_con = &mut get_db_conn();
let results = playlist_songs
.inner_join(songs)
.filter(playlist_id.eq(other_playlist_id))
.select(songs::all_columns())
.order_by(position)
.load(db_con)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting songs from playlist: {}", e)))?;
Ok(results)
}
/// Remove a song from a playlist
///
/// # Arguments
///
/// * `playlist_id` - The id of the playlist
/// * `song_id` - The id of the song
///
/// # Returns
///
/// * `Result<(), ServerFnError>` - An empty result if successful, or an error
///
#[server(endpoint = "playlists/remove-song")]
pub async fn remove_song(new_playlist_id: Option<i32>, new_song_id: Option<i32>) -> Result<(), ServerFnError> {
use crate::schema::playlist_songs::dsl::*;
use leptos::server_fn::error::NoCustomError;
let other_playlist_id = new_playlist_id.ok_or(ServerFnError::<NoCustomError>::ServerError("Playlist id must be present (Some) to remove song".to_string()))?;
let other_song_id = new_song_id.ok_or(ServerFnError::<NoCustomError>::ServerError("Song id must be present (Some) to remove song".to_string()))?;
let db_con = &mut get_db_conn();
diesel::delete(playlist_songs.filter(playlist_id.eq(other_playlist_id).and(song_id.eq(other_song_id))))
.execute(db_con)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error removing song from playlist: {}", e)))?;
Ok(())
}

37
src/api/songs.rs Normal file
View File

@ -0,0 +1,37 @@
use leptos::*;
use crate::models::Artist;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::database::get_db_conn;
use diesel::prelude::*;
}
}
/// Gets a Vector of Artists associated with a Song
///
/// # Arguments
/// `song_id_arg` - The id of the Song to get the Artists for
///
/// # Returns
/// A Result containing a Vector of Artists if the operation was successful, or an error if the operation failed
#[server(endpoint = "songs/get-artists")]
pub async fn get_artists(song_id_arg: Option<i32>) -> Result<Vec<Artist>, ServerFnError> {
use crate::schema::artists::dsl::*;
use crate::schema::song_artists::dsl::*;
use leptos::server_fn::error::NoCustomError;
let other_song_id = song_id_arg.ok_or(ServerFnError::<NoCustomError>::ServerError("Song id must be present (Some) to get artists".to_string()))?;
let my_artists = artists
.inner_join(song_artists)
.filter(song_id.eq(other_song_id))
.select(artists::all_columns())
.load(&mut get_db_conn())?;
Ok(my_artists)
}

View File

@ -1,13 +1,13 @@
use crate::error_template::{AppError, ErrorTemplate};
use crate::pages::login::*;
use crate::pages::signup::*;
use crate::playbar::PlayBar;
use crate::playstatus::PlayStatus;
use crate::queue::Queue;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use crate::pages::login::*;
use crate::pages::signup::*;
use crate::error_template::{AppError, ErrorTemplate};
use leptos::leptos_dom::*;
#[component]
pub fn App() -> impl IntoView {
@ -42,29 +42,49 @@ pub fn App() -> impl IntoView {
}
}
use crate::components::sidebar::*;
use crate::components::dashboard::*;
use crate::components::search::*;
use crate::components::personal::*;
use crate::components::search::*;
use crate::components::sidebar::*;
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
use crate::auth::check_auth;
let play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status);
let (logged_in, set_logged_in) = create_signal(false);
let (dashboard_open, set_dashboard_open) = create_signal(true);
create_effect(move |_| {
spawn_local(async move {
let auth_result = check_auth().await;
if let Err(err) = auth_result {
log!("Error checking auth: {:?}", err);
} else if let Ok(true) = auth_result {
log!("User is logged in");
set_logged_in.update(|value| *value = true);
} else if let Ok(false) = auth_result {
log!("User is not logged in");
set_logged_in.update(|value| *value = false);
}
});
});
view! {
<div class="home-container">
<Sidebar setter=set_dashboard_open active=dashboard_open />
<Sidebar setter=set_dashboard_open active=dashboard_open logged_in=logged_in/>
<Show
when=move || {dashboard_open() == true}
fallback=move || view! { <Search /> }
>
<Dashboard />
</Show>
<Personal />
<Personal logged_in=logged_in/>
<PlayBar status=play_status/>
<Queue status=play_status/>
</div>

View File

@ -2,3 +2,6 @@ pub mod sidebar;
pub mod dashboard;
pub mod search;
pub mod personal;
pub mod playlist;
pub mod create_playlist;
pub mod playlists;

View File

@ -0,0 +1,53 @@
use leptos::*;
use leptos_icons::*;
use leptos::leptos_dom::*;
use crate::api::playlists::create_playlist;
use crate::api::playlists::get_playlists;
use crate::models::Playlist;
#[component]
pub fn CreatePlayList(closer: WriteSignal<bool>, set_playlists: WriteSignal<Vec<Playlist>>) -> impl IntoView {
let (playlist_name, set_playlist_name) = create_signal("".to_string());
let on_submit = move |ev: leptos::ev::SubmitEvent| {
ev.prevent_default();
let new_playlist_name = playlist_name.get();
spawn_local(async move {
let create_result = create_playlist(new_playlist_name).await;
if let Err(err) = create_result {
// Handle the error here, e.g., log it or display to the user
log!("Error creating playlist: {:?}", err);
} else {
log!("Playlist created successfully!");
closer.update(|value| *value = false);
}
let playlists = get_playlists().await;
if let Err(err) = playlists {
// Handle the error here, e.g., log it or display to the user
log!("Error getting playlists: {:?}", err);
} else {
set_playlists.update(|value| *value = playlists.unwrap());
}
})
};
view! {
<div class="create-playlist-popup-container">
<div class="close-button" on:click=move |_| closer.update(|value| *value = false)>
<Icon icon=icondata::IoCloseSharp />
</div>
<h1 class="header">Create Playlist</h1>
<form class="create-playlist-form" action="POST" on:submit=on_submit>
<input class="name-input" type="text" placeholder="Playlist Name"
on:input=move |ev| {
set_playlist_name(event_target_value(&ev));
log!("playlist name changed to: {}", playlist_name.get());
}
prop:value=playlist_name
/>
<button class="create-button" type="submit">Create</button>
</form>
</div>
}
}

View File

@ -3,16 +3,17 @@ use leptos::*;
use leptos_icons::*;
#[component]
pub fn Personal() -> impl IntoView {
pub fn Personal(logged_in: ReadSignal<bool>) -> impl IntoView {
view! {
<div class=" personal-container">
<Profile />
<Profile logged_in=logged_in/>
</div>
}
}
#[component]
pub fn Profile() -> impl IntoView {
pub fn Profile(logged_in: ReadSignal<bool>) -> impl IntoView {
let (dropdown_open, set_dropdown_open) = create_signal(false);
let open_dropdown = move |_| {
@ -25,7 +26,13 @@ pub fn Profile() -> impl IntoView {
<Icon icon=icondata::CgProfile />
</div>
<div class="dropdown-container" style={move || if dropdown_open() {"display: flex"} else {"display: none"}}>
<DropDownNotLoggedIn />
<Show
when=move || {logged_in() == true}
fallback=move || view!{<DropDownNotLoggedIn />}
>
<DropDownLoggedIn/>
</Show>
</div>
</div>
}
@ -40,3 +47,26 @@ pub fn DropDownNotLoggedIn() -> impl IntoView {
</div>
}
}
#[component]
pub fn DropDownLoggedIn() -> impl IntoView {
use crate::auth::logout;
let logout = move |_ev: leptos::ev::MouseEvent| {
spawn_local(async move {
let _logout_result = logout().await;
if let Err(err) = _logout_result {
log!("Error logging out: {:?}", err);
} else {
log!("Logged out Successfully!");
leptos_router::use_navigate()("/login", Default::default());
}
});
};
view! {
<div class="dropdown-logged-in">
<h1>Logged in!</h1>
<button on:click=logout class="auth-button">Log Out</button>
</div>
}
}

162
src/components/playlist.rs Normal file
View File

@ -0,0 +1,162 @@
use leptos::*;
use leptos_icons::*;
use leptos::leptos_dom::*;
use crate::models::Playlist;
use crate::models::Song;
use crate::api::playlists::get_songs;
use crate::api::songs::get_artists;
use crate::api::playlists::remove_song;
fn total_duration(songs: ReadSignal<Vec<Song>>) -> i32 {
let mut total_duration = 0;
for song in songs.get() {
total_duration += song.duration;
}
total_duration
}
fn convert_seconds(seconds: i32) -> String {
let minutes = seconds / 60;
let seconds = seconds % 60;
let seconds_string = if seconds < 10 {
format!("0{}", seconds)
} else {
format!("{}", seconds)
};
format!("{}:{}", minutes, seconds_string)
}
fn convert_to_text_time(seconds: i32) -> String {
let hours = seconds / 3600;
let minutes = (seconds % 3600) / 60;
format!("{} hour{}, {} minute{}", hours, if hours > 1 { "s" } else { "" }, minutes, if minutes > 1 { "s" } else { "" })
}
#[component]
pub fn Playlist(playlist: Playlist) -> impl IntoView {
let (show_playlist, set_show_playlist) = create_signal(false);
view! {
<div class="playlist" on:click=move|_| set_show_playlist.update(|value| *value=true) >
<h1 class="name">{playlist.name.clone()}</h1>
<Show
when=move || show_playlist()
fallback=move || view! {<div></div>}
>
<div class="screen-darkener"></div>
</Show>
<Show
when=move || show_playlist()
fallback=move || view! {<div></div>}
>
<PlayListPopUp playlist=playlist.clone() set_show_playlist=set_show_playlist />
</Show>
</div>
}
}
#[component]
pub fn PlayListPopUp(playlist: Playlist, set_show_playlist: WriteSignal<bool>) -> impl IntoView {
let (songs, set_songs) = create_signal(vec![]);
create_effect(move |_| {
spawn_local(async move {
let playlist_songs = get_songs(playlist.id.clone()).await;
if let Err(err) = playlist_songs {
// Handle the error here, e.g., log it or display to the user
log!("Error getting songs: {:?}", err);
} else {
log!("Songs: {:?}", playlist_songs);
log!("number of songs: {:?}", playlist_songs.clone().expect("REASON").len());
set_songs.update(|value| *value = playlist_songs.unwrap());
}
})
});
view! {
<div class="playlist-container">
<div class="close-button" on:click=move |_| set_show_playlist.update(|value| *value = false)>
<Icon icon=icondata::IoCloseSharp />
</div>
<div class="info">
<h1>{playlist.name.clone()}</h1>
<p>{move || songs.get().len()} songs {move || convert_to_text_time(total_duration(songs))}</p>
</div>
<div class="options">
<button><Icon class="button-icons" icon=icondata::BsPlayFill />Play</button>
<button><Icon class="button-icons" icon=icondata::IoShuffle />Shuffle</button>
</div>
<ul class="songs">
{
move || songs.get().iter().enumerate().map(|(_index,song)| view! {
<PlaylistSong song=song.clone() playlist_id=playlist.id.clone() set_songs=set_songs />
}).collect::<Vec<_>>()
}
</ul>
</div>
}
}
#[component]
pub fn PlaylistSong(song: Song, playlist_id: Option<i32>, set_songs: WriteSignal<Vec<Song>>) -> impl IntoView {
let (artists, set_artists) = create_signal("".to_string());
let (is_hovered, set_is_hovered) = create_signal(false);
let delete_song = move |_| {
spawn_local(async move {
let delete_result = remove_song(playlist_id,song.id.clone()).await;
if let Err(err) = delete_result {
// Handle the error here, e.g., log it or display to the user
log!("Error deleting song: {:?}", err);
} else {
log!("Song deleted successfully!");
set_songs.update(|value| *value = value.iter().filter(|s| s.id != song.id).cloned().collect());
}
})
};
create_effect(move |_| {
spawn_local(async move {
let song_artists = get_artists(song.id.clone()).await;
if let Err(err) = song_artists {
// Handle the error here, e.g., log it or display to the user
log!("Error getting artist: {:?}", err);
} else {
log!("Artist: {:?}", song_artists);
let mut artist_string = "".to_string();
let song_artists = song_artists.unwrap();
for i in 0..song_artists.len() {
if i == song_artists.len() - 1 {
artist_string.push_str(&song_artists[i].name);
} else {
artist_string.push_str(&song_artists[i].name);
artist_string.push_str(" & ");
}
}
set_artists.update(|value| *value = artist_string);
}
})
});
view! {
<div class="song" on:mouseenter=move |_| set_is_hovered.update(|value| *value=true) on:mouseleave=move |_| set_is_hovered.update(|value| *value=false)>
<img src={song.image_path.clone()} alt={song.title.clone()} />
<div class="song-info">
<h3>{song.title.clone()}</h3>
<p>{move || artists.get()}</p>
</div>
<div class="right">
<Show
when=move || is_hovered()
fallback=move || view! {<p class="duration">{convert_seconds(song.duration)}</p>}
>
<div class="delete-song" on:click=delete_song>
<Icon icon=icondata::FaTrashCanRegular />
</div>
</Show>
</div>
</div>
}
}

View File

@ -0,0 +1,56 @@
use leptos::*;
use leptos::leptos_dom::*;
use leptos_icons::*;
use crate::components::create_playlist::CreatePlayList;
use crate::components::playlist::Playlist;
use crate::api::playlists::get_playlists;
#[component]
pub fn Playlists() -> impl IntoView {
let (create_playlist_open, set_create_playlist_open) = create_signal(false);
let (playlists, set_playlists) = create_signal(vec![]);
create_effect(move |_| {
spawn_local(async move {
let playlists2 = get_playlists().await;
if let Err(err) = playlists2 {
// Handle the error here, e.g., log it or display to the user
log!("Error getting playlists: {:?}", err);
} else {
set_playlists.update(|value| *value = playlists2.unwrap());
}
});
});
view! {
<div class="sidebar-playlists-container">
<div class="heading">
<h1 class="header">Playlists</h1>
<button on:click=move|_| set_create_playlist_open.update(|value|*value = true) class="add-playlist">
<div class="add-sign">
<Icon icon=icondata::IoAddSharp />
</div>
New Playlist
</button>
</div>
<Show
when=move || create_playlist_open()
fallback=move || view! {<div></div>}
>
<CreatePlayList closer=set_create_playlist_open set_playlists=set_playlists/>
</Show>
<ul class="playlists">
{
move || playlists.get().iter().enumerate().map(|(_index,playlist)| view! {
<Playlist playlist=playlist.clone() />
}).collect::<Vec<_>>()
}
</ul>
</div>
}
}

View File

@ -1,9 +1,11 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::components::playlists::Playlists;
#[component]
pub fn Sidebar(setter: WriteSignal<bool>, active: ReadSignal<bool>) -> impl IntoView {
pub fn Sidebar(setter: WriteSignal<bool>, active: ReadSignal<bool>, logged_in:ReadSignal<bool>) -> impl IntoView {
let open_dashboard = move |_| {
setter.update(|value| *value = true);
log!("open dashboard");
@ -26,25 +28,15 @@ pub fn Sidebar(setter: WriteSignal<bool>, active: ReadSignal<bool>) -> impl Into
<h1>Search</h1>
</div>
</div>
<Bottom />
</div>
}
}
#[component]
pub fn Bottom() -> impl IntoView {
view! {
<div class="sidebar-bottom-container">
<div class="heading">
<h1 class="header">Playlists</h1>
<button class="add-playlist">
<div class="add-sign">
<Icon icon=icondata::IoAddSharp />
</div>
New Playlist
</button>
<div class="sidebar-bottom-container">
<Show
when=move || {logged_in() == true}
fallback=move|| view!{<h1>LOG IN PLEASE</h1>}
>
<Playlists />
</Show>
</div>
</div>
}
}

View File

@ -13,6 +13,7 @@ pub mod users;
pub mod search;
pub mod fileserv;
pub mod error_template;
pub mod api;
use cfg_if::cfg_if;
cfg_if! {

View File

@ -47,7 +47,7 @@ pub struct User {
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::artists))]
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Artist {
/// A unique id for the artist
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
@ -239,7 +239,7 @@ impl Album {
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::songs))]
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Song {
/// A unique id for the song
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
@ -290,3 +290,101 @@ impl Song {
Ok(my_artists)
}
}
/// Model for an playlist
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::playlists))]
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Playlist {
/// A unique id for the playlist
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
pub id: Option<i32>,
/// The playlist's name
pub name: String,
/// The user who created the playlist
pub user_id: i32,
}
impl Playlist {
/// Create a new, empty playlist in the database
///
/// # Arguments
///
/// * `new_playlist` - The new playlist
/// * `conn` - A mutable reference to a database connection
///
/// # Returns
///
/// * `Result<(), Box<dyn Error>>` - A result indicating success with the new playlist, or an error
///
#[cfg(feature = "ssr")]
pub fn create_playlist(new_playlist: Playlist, conn: &mut PgPooledConn) -> Result<(), Box<dyn Error>> {
use crate::schema::playlists::dsl::*;
let new_playlist = Playlist {
..new_playlist
};
diesel::insert_into(playlists)
.values(&new_playlist)
.execute(conn)?;
Ok(())
}
/// Add a song to this playlist in the database
///
/// The 'id' field of this playlist must be present (Some) to add a song
///
/// # Arguments
///
/// * `new_song_id` - The id of the song to add to this playlist
/// * `conn` - A mutable reference to a database connection
///
/// # Returns
///
/// * `Result<(), Box<dyn Error>>` - A result indicating success with an empty value, or an error
///
#[cfg(feature = "ssr")]
pub fn add_song(self: &Self, new_song_id: i32, conn: &mut PgPooledConn) -> Result<(), Box<dyn Error>> {
use crate::schema::playlist_songs::dsl::*;
let my_id = self.id.ok_or("Playlist id must be present (Some) to add a song")?;
diesel::insert_into(playlist_songs)
.values((playlist_id.eq(my_id), song_id.eq(new_song_id)))
.execute(conn)?;
Ok(())
}
/// Get songs by this playlist from the database
///
/// The 'id' field of this playlist must be present (Some) to get songs
///
/// # Arguments
///
/// * `conn` - A mutable reference to a database connection
///
/// # Returns
///
/// * `Result<Vec<Song>, Box<dyn Error>>` - A result indicating success with a vector of songs, or an error
///
#[cfg(feature = "ssr")]
pub fn get_songs(self: &Self, conn: &mut PgPooledConn) -> Result<Vec<Song>, Box<dyn Error>> {
use crate::schema::songs::dsl::*;
use crate::schema::playlist_songs::dsl::*;
let my_id = self.id.ok_or("Playlist id must be present (Some) to get songs")?;
let my_songs = songs
.inner_join(playlist_songs)
.filter(playlist_id.eq(my_id))
.select(songs::all_columns())
.load(conn)?;
Ok(my_songs)
}
}

View File

@ -73,9 +73,7 @@ pub fn Login() -> impl IntoView {
<i></i>
<Show
when=move || {show_password() == false}
fallback=move || view!{ <button on:click=toggle_password class="login-password-visibility">
<Icon icon=icondata::AiEyeInvisibleFilled />
</button> /> }
fallback=move || view!{ <button on:click=toggle_password class="login-password-visibility"><Icon icon=icondata::AiEyeInvisibleFilled /></button> /> }
>
<button on:click=toggle_password class="login-password-visibility">
<Icon icon=icondata::AiEyeFilled />

View File

@ -22,6 +22,22 @@ diesel::table! {
}
}
diesel::table! {
playlist_songs (playlist_id, song_id) {
playlist_id -> Int4,
song_id -> Int4,
position -> Int4,
}
}
diesel::table! {
playlists (id) {
id -> Int4,
name -> Varchar,
user_id -> Int4,
}
}
diesel::table! {
song_artists (song_id, artist_id) {
song_id -> Int4,
@ -54,6 +70,9 @@ diesel::table! {
diesel::joinable!(album_artists -> albums (album_id));
diesel::joinable!(album_artists -> artists (artist_id));
diesel::joinable!(playlist_songs -> playlists (playlist_id));
diesel::joinable!(playlist_songs -> songs (song_id));
diesel::joinable!(playlists -> users (user_id));
diesel::joinable!(song_artists -> artists (artist_id));
diesel::joinable!(song_artists -> songs (song_id));
diesel::joinable!(songs -> albums (album_id));
@ -62,6 +81,8 @@ diesel::allow_tables_to_appear_in_same_query!(
album_artists,
albums,
artists,
playlist_songs,
playlists,
song_artists,
songs,
users,

View File

@ -51,41 +51,293 @@
padding: 0.2rem 1rem 1rem 1rem;
height: calc(100% - 9rem);
.heading {
display: flex;
flex-direction: row;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
.sidebar-playlists-container {
width: 100%;
height: 100%;
.header {
font-size: 1.2rem;
font-weight: 200;
}
.add-playlist {
.heading {
display: flex;
flex-direction: row;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
justify-content: center;
font-size: 0.9rem;
border-radius: 50px;
border: none;
height: 2.2rem;
padding-right: 2rem;
padding-left: 2rem;
cursor: pointer;
transition: background-color 0.3s ease;
.add-sign {
font-size: 1.5rem;
margin-top: auto;
margin-right: 5px;
color: white;
.header {
font-size: 1.2rem;
font-weight: 200;
}
.add-playlist {
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
font-size: 0.9rem;
border-radius: 50px;
border: none;
height: 2.2rem;
padding-right: 2rem;
padding-left: 2rem;
cursor: pointer;
transition: background-color 0.3s ease;
.add-sign {
font-size: 1.5rem;
margin-top: auto;
margin-right: 5px;
color: white;
}
}
.add-playlist:hover {
background-color: #9e9e9e;
}
}
.add-playlist:hover {
background-color: #9e9e9e;
.create-playlist-popup-container {
display: flex;
position: relative;
flex-direction: column;
// background-color: #1c1c1c;
height: 12rem;
width: 20rem;
border-radius: 2px;
padding: 1rem;
padding-top: 0.1rem;
border: 1px solid grey;
position: fixed;
top: 40%;
left: 50%;
transform: translate(-50%, -50%);
.close-button {
position: absolute;
top: 5px;
right: 5px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
border-radius: 50%;
font-size: 1.6rem;
transition: all 0.3s;
}
.close-button:hover {
transform: scale(1.1);
background-color: rgba(255, 255, 255, 0.1);
}
.close-button:active {
transform: scale(0.8);
}
.header {
font-size: 1.2rem;
font-weight: 200;
margin-bottom: 0.5rem;
}
.create-playlist-form {
display: flex;
flex-direction: column;
position: relative;
height: 100%;
.name-input {
background: transparent;
border: none;
border-bottom: 1px solid grey;
font-size: 1.1rem;
color: white;
margin-top: 2rem;
}
.name-input:focus {
outline: none;
}
.create-button {
position: absolute;
bottom: 0px;
width: 5rem;
padding: 0.4rem;
border-radius: 0.5rem;
cursor: pointer;
}
}
}
.playlists {
list-style: none;
padding: 0;
margin: 0;
margin-top: 5px;
height: 100%;
.playlist {
padding: 0;
margin: 0;
margin-top: 5px;
display: flex;
flex-direction: row;
border: 1px solid grey;
height: 3rem;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
.screen-darkener {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1;
}
.name {
font-size: 1rem;
margin-left: 1rem;
margin-top: 0.5rem;
color: white;
}
.playlist-container {
background-color: #1c1c1c;
width: 40rem;
height: 40rem;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
border: 1px solid white;
border-radius: 5px;
padding: 1rem;
padding-top: 0;
z-index: 2;
display: flex;
flex-direction: column;
.close-button {
position: absolute;
top: 5px;
right: 5px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
border-radius: 50%;
font-size: 1.6rem;
transition: all 0.3s;
}
.close-button:hover {
transform: scale(1.1);
background-color: rgba(255, 255, 255, 0.1);
}
.close-button:active {
transform: scale(0.8);
}
h1 {
font-size: 2rem;
font-weight: bolder;
margin-bottom: 0.5rem;
}
.info {
display:flex;
flex-direction: row;
align-items: end;
h1 {
font-weight: bold;
font-size: 2rem;
margin-left: .5rem;
margin-right:2rem;
}
p {
color: #aaa;
}
}
.options {
display: flex;
button {
background-color: white;
border: none;
color: black;
font-size: 1rem;
padding: .6rem;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease;
display: flex;
flex-direction: row;
align-items: center;
margin-right: 10px;
margin-top: 1rem;
margin-left: 5px;
.button-icons {
margin-right: 7px;
font-size: 1.3rem;
}
}
}
.songs {
list-style: none;
padding: 0;
margin: 0;
margin-top: 2rem;
.song {
display: flex;
align-items: center;
padding: 7px 10px 7px 10px;
border-bottom: 1px solid #ccc; /* Separator line color */
img {
max-width: 40px; /* Adjust maximum width for images */
margin-right: 10px; /* Add spacing between image and text */
border-radius: 5px; /* Add border radius to image */
}
.song-info {
h3 {
margin: 0; /* Remove default margin for heading */
color: #fff; /* Adjust text color for song */
font-size: 1rem;
font-weight: 200;
}
p {
margin: 0; /* Remove default margin for paragraph */
color: #aaa; /* Adjust text color for artist */
font-size: 0.9rem;
}
}
.right {
position: fixed;
right: 25px;
transition: all 0.3s ease;
.duration {
}
.delete-song {
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
.delete-song:hover {
transform: scale(1.1);
}
.delete-song:active {
transform: scale(0.8);
}
}
}
.song:first-child {
border-top: 1px solid #ccc;
}
}
}
}
.playlist:hover {
background-color: #adadad36;
}
}
}
}