Compare commits

..

13 Commits

41 changed files with 1460 additions and 2632 deletions

2097
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -8,16 +8,27 @@ build = "src/build.rs"
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
actix-files = { version = "0.6", optional = true }
actix-web = { version = "4", optional = true, features = ["macros"] }
console_error_panic_hook = "0.1" console_error_panic_hook = "0.1"
cfg-if = "1" cfg-if = "1"
http = "1.0" http = { version = "0.2", optional = true }
leptos = { version = "0.6", features = ["nightly"] } leptos = { version = "0.5", features = ["nightly"] }
leptos_meta = { version = "0.6", features = ["nightly"] } leptos_meta = { version = "0.5", features = ["nightly"] }
leptos_axum = { version = "0.6", optional = true } leptos_actix = { version = "0.5", optional = true }
leptos_router = { version = "0.6", features = ["nightly"] } leptos_router = { version = "0.5", features = ["nightly"] }
wasm-bindgen = "=0.2.92" wasm-bindgen = "=0.2.92"
leptos_icons = { version = "0.3.0" } leptos_icons = { version = "0.1.0", default_features = false, features = [
icondata = { version = "0.3.0" } "BsPlayFill",
"BsPauseFill",
"BsSkipStartFill",
"BsSkipEndFill",
"RiPlayListMediaFill",
"CgTrash",
"IoReturnUpBackSharp",
"AiEyeFilled",
"AiEyeInvisibleFilled"
] }
dotenv = { version = "0.15.0", optional = true } dotenv = { version = "0.15.0", optional = true }
diesel = { version = "2.1.4", features = ["postgres", "r2d2", "time"], optional = true } diesel = { version = "2.1.4", features = ["postgres", "r2d2", "time"], optional = true }
lazy_static = { version = "1.4.0", optional = true } lazy_static = { version = "1.4.0", optional = true }
@ -25,26 +36,18 @@ serde = { versions = "1.0.195", features = ["derive"] }
openssl = { version = "0.10.63", optional = true } openssl = { version = "0.10.63", optional = true }
time = { version = "0.3.34", features = ["serde"] } time = { version = "0.3.34", features = ["serde"] }
diesel_migrations = { version = "2.1.0", optional = true } diesel_migrations = { version = "2.1.0", optional = true }
actix-identity = { version = "0.7.0", optional = true }
actix-session = { version = "0.9.0", features = ["redis-rs-session"], optional = true }
pbkdf2 = { version = "0.12.2", features = ["simple"], optional = true } pbkdf2 = { version = "0.12.2", features = ["simple"], optional = true }
futures = { version = "0.3.30", default-features = false, optional = true } futures = { version = "0.3.30", default-features = false, optional = true }
tokio = { version = "1", optional = true, features = ["rt-multi-thread"] }
axum = { version = "0.7.5", optional = true }
tower = { veresion = "0.4.13", optional = true }
tower-http = { version = "0.5", optional = true, features = ["fs"] }
thiserror = "1.0.57"
tower-sessions = { version = "0.11", default-features = false }
tower-sessions-redis-store = { version = "0.11", optional = true }
async-trait = "0.1.79"
axum-login = { version = "0.14.0", optional = true }
[patch.crates-io]
gloo-net = { git = "https://github.com/rustwasm/gloo.git", rev = "a823fab7ecc4068e9a28bd669da5eaf3f0a56380" }
[features] [features]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"] csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"] hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
ssr = [ ssr = [
"dep:leptos_axum", "dep:actix-files",
"dep:actix-web",
"dep:leptos_actix",
"leptos/ssr", "leptos/ssr",
"leptos_meta/ssr", "leptos_meta/ssr",
"leptos_router/ssr", "leptos_router/ssr",
@ -53,14 +56,10 @@ ssr = [
"lazy_static", "lazy_static",
"openssl", "openssl",
"diesel_migrations", "diesel_migrations",
"actix-identity",
"actix-session",
"pbkdf2", "pbkdf2",
"futures", "futures",
"tokio",
"axum",
"tower",
"tower-http",
"tower-sessions-redis-store",
"axum-login",
] ]
# Defines a size-optimized profile for the WASM bundle in release mode # Defines a size-optimized profile for the WASM bundle in release mode

View File

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

View File

@ -1,13 +0,0 @@
-- 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)
);

36
src/api/albums.rs Normal file
View File

@ -0,0 +1,36 @@
use leptos::*;
use crate::models::Album;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::database::get_db_conn;
use diesel::prelude::*;
}
}
/// Gets the Album associated with an album id
///
/// # Arguments
/// `album_id_arg` The id of the Album to get the album for
///
/// # Returns
/// A Result containing an Album if the operation was successful, or an error if the operation failed
#[server(endpoint = "albums/get-album")]
pub async fn get_album(album_id_arg: Option<i32>) -> Result<Album, ServerFnError> {
use crate::schema::albums::dsl::*;
let my_id = album_id_arg.ok_or(ServerFnError::ServerError("Album id must be present (Some) to get Album".to_string()))?;
let mut my_album_vec: Vec<Album> = albums
.filter(id.eq(my_id))
.limit(1)
.load(&mut get_db_conn())?;
let my_album = my_album_vec.pop().ok_or(ServerFnError::ServerError("Album not found".to_string()))?;
Ok(my_album)
}

View File

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

View File

@ -1,157 +0,0 @@
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(())
}

View File

@ -1,5 +1,6 @@
use leptos::*; use leptos::*;
use crate::models::Artist; use crate::models::Artist;
use crate::models::Song;
use cfg_if::cfg_if; use cfg_if::cfg_if;
@ -22,16 +23,37 @@ if #[cfg(feature = "ssr")] {
pub async fn get_artists(song_id_arg: Option<i32>) -> Result<Vec<Artist>, ServerFnError> { pub async fn get_artists(song_id_arg: Option<i32>) -> Result<Vec<Artist>, ServerFnError> {
use crate::schema::artists::dsl::*; use crate::schema::artists::dsl::*;
use crate::schema::song_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_id = song_id_arg.ok_or(ServerFnError::ServerError("Song id must be present (Some) to get artists".to_string()))?;
let my_artists = artists let my_artists = artists
.inner_join(song_artists) .inner_join(song_artists)
.filter(song_id.eq(other_song_id)) .filter(song_id.eq(my_id))
.select(artists::all_columns()) .select(artists::all_columns())
.load(&mut get_db_conn())?; .load(&mut get_db_conn())?;
Ok(my_artists) Ok(my_artists)
} }
/// Gets the song associated with a song id
///
/// # Arguments
/// `song_id_arg` - The id of the Song to get the song for
///
/// # Returns
/// A Result containing a Song if the operation was successful, or an error if the operation failed
#[server(endpoint = "songs/get-song")]
pub async fn get_song(song_id_arg: Option<i32>) -> Result<Song, ServerFnError> {
use crate::schema::songs::dsl::*;
let my_id = song_id_arg.ok_or(ServerFnError::ServerError("Song id must be present (Some) to get Song".to_string()))?;
let mut my_song_vec: Vec<Song> = songs
.filter(id.eq(my_id))
.limit(1)
.load(&mut get_db_conn())?;
let my_song = my_song_vec.pop().ok_or(ServerFnError::ServerError("Song not found".to_string()))?;
Ok(my_song)
}

View File

@ -1,13 +1,11 @@
use crate::error_template::{AppError, ErrorTemplate};
use crate::pages::login::*;
use crate::pages::signup::*;
use crate::playbar::PlayBar; use crate::playbar::PlayBar;
use crate::playstatus::PlayStatus; use crate::playstatus::PlayStatus;
use crate::queue::Queue; use crate::queue::Queue;
use leptos::*; use leptos::*;
use leptos_meta::*; use leptos_meta::*;
use leptos_router::*; use leptos_router::*;
use leptos::leptos_dom::*; use crate::pages::login::*;
use crate::pages::signup::*;
#[component] #[component]
pub fn App() -> impl IntoView { pub fn App() -> impl IntoView {
@ -23,17 +21,11 @@ pub fn App() -> impl IntoView {
<Title text="LibreTunes"/> <Title text="LibreTunes"/>
// content for this welcome page // content for this welcome page
<Router fallback=|| { <Router>
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main> <main>
<Routes> <Routes>
<Route path="" view=HomePage/> <Route path="" view=HomePage/>
<Route path="/*any" view=NotFound/>
<Route path="/login" view=Login /> <Route path="/login" view=Login />
<Route path="/signup" view=Signup /> <Route path="/signup" view=Signup />
</Routes> </Routes>
@ -42,52 +34,15 @@ pub fn App() -> impl IntoView {
} }
} }
use crate::components::dashboard::*;
use crate::components::personal::*;
use crate::components::search::*;
use crate::components::sidebar::*;
/// Renders the home page of your application. /// Renders the home page of your application.
#[component] #[component]
fn HomePage() -> impl IntoView { fn HomePage() -> impl IntoView {
use crate::auth::check_auth;
let play_status = PlayStatus::default(); let play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status); 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! { view! {
<div class="home-container">
<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 logged_in=logged_in/>
<PlayBar status=play_status/> <PlayBar status=play_status/>
<Queue status=play_status/> <Queue status=play_status/>
</div>
} }
} }
@ -104,8 +59,8 @@ fn NotFound() -> impl IntoView {
{ {
// this can be done inline because it's synchronous // this can be done inline because it's synchronous
// if it were async, we'd use a server function // if it were async, we'd use a server function
let resp = expect_context::<leptos_axum::ResponseOptions>(); let resp = expect_context::<leptos_actix::ResponseOptions>();
resp.set_status(axum::http::StatusCode::NOT_FOUND); resp.set_status(actix_web::http::StatusCode::NOT_FOUND);
} }
view! { view! {

View File

@ -1,18 +1,5 @@
use leptos::*; use leptos::*;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use leptos::server_fn::error::NoCustomError;
use leptos_axum::extract;
use axum_login::AuthSession;
use crate::auth_backend::AuthBackend;
}
}
use crate::models::User; use crate::models::User;
use crate::users::UserCredentials;
/// Create a new user and log them in /// Create a new user and log them in
/// Takes in a NewUser struct, with the password in plaintext /// Takes in a NewUser struct, with the password in plaintext
@ -21,6 +8,10 @@ use crate::users::UserCredentials;
pub async fn signup(new_user: User) -> Result<(), ServerFnError> { pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
use crate::users::create_user; use crate::users::create_user;
use leptos_actix::extract;
use actix_web::{HttpMessage, HttpRequest};
use actix_identity::Identity;
// Ensure the user has no id // Ensure the user has no id
let new_user = User { let new_user = User {
id: None, id: None,
@ -28,95 +19,53 @@ pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
}; };
create_user(&new_user).await create_user(&new_user).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error creating user: {}", e)))?; .map_err(|e| ServerFnError::ServerError(format!("Error creating user: {}", e)))?;
let mut auth_session = extract::<AuthSession<AuthBackend>>().await extract(|request: HttpRequest| async move {
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?; Identity::login(&request.extensions(), new_user.username.clone())
}).await??;
let credentials = UserCredentials { Ok(())
username_or_email: new_user.username.clone(),
password: new_user.password.clone().unwrap()
};
match auth_session.authenticate(credentials).await {
Ok(Some(user)) => {
auth_session.login(&user).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error logging in user: {}", e)))
},
Ok(None) => {
Err(ServerFnError::<NoCustomError>::ServerError("Error authenticating user: User not found".to_string()))
},
Err(e) => {
Err(ServerFnError::<NoCustomError>::ServerError(format!("Error authenticating user: {}", e)))
}
}
} }
/// Log a user in /// Log a user in
/// Takes in a username or email and a password in plaintext /// Takes in a username or email and a password in plaintext
/// Returns a Result with a boolean indicating if the login was successful /// Returns a Result with a boolean indicating if the login was successful
#[server(endpoint = "login")] #[server(endpoint = "login")]
pub async fn login(credentials: UserCredentials) -> Result<bool, ServerFnError> { pub async fn login(username_or_email: String, password: String) -> Result<bool, ServerFnError> {
use crate::users::validate_user; use crate::users::validate_user;
use actix_web::{HttpMessage, HttpRequest};
use actix_identity::Identity;
use leptos_actix::extract;
let mut auth_session = extract::<AuthSession<AuthBackend>>().await let possible_user = validate_user(username_or_email, password).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?; .map_err(|e| ServerFnError::ServerError(format!("Error validating user: {}", e)))?;
let user = validate_user(credentials).await let user = match possible_user {
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error validating user: {}", e)))?; Some(user) => user,
None => return Ok(false)
};
extract(|request: HttpRequest| async move {
Identity::login(&request.extensions(), user.username.clone())
}).await??;
if let Some(user) = user {
auth_session.login(&user).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error logging in user: {}", e)))?;
Ok(true) Ok(true)
} else {
Ok(false)
}
} }
/// Log a user out /// Log a user out
/// Returns a Result with the error message if the user could not be logged out /// Returns a Result with the error message if the user could not be logged out
#[server(endpoint = "logout")] #[server(endpoint = "logout")]
pub async fn logout() -> Result<(), ServerFnError> { pub async fn logout() -> Result<(), ServerFnError> {
let mut auth_session = extract::<AuthSession<AuthBackend>>().await use leptos_actix::extract;
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?; use actix_identity::Identity;
auth_session.logout().await extract(|user: Option<Identity>| async move {
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?; if let Some(user) = user {
user.logout();
}
}).await?;
Ok(()) Ok(())
} }
/// Check if a user is logged in
/// Returns a Result with a boolean indicating if the user is logged in
#[server(endpoint = "check_auth")]
pub async fn check_auth() -> Result<bool, ServerFnError> {
let auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
Ok(auth_session.user.is_some())
}
/// Require that a user is logged in
/// Returns a Result with the error message if the user is not logged in
/// Intended to be used at the start of a protected route, to ensure the user is logged in:
/// ```rust
/// use leptos::*;
/// use libretunes::auth::require_auth;
/// #[server(endpoint = "protected_route")]
/// pub async fn protected_route() -> Result<(), ServerFnError> {
/// require_auth().await?;
/// // Continue with protected route
/// Ok(())
/// }
/// ```
#[cfg(feature = "ssr")]
pub async fn require_auth() -> Result<(), ServerFnError> {
check_auth().await.and_then(|logged_in| {
if logged_in {
Ok(())
} else {
Err(ServerFnError::<NoCustomError>::ServerError(format!("Unauthorized")))
}
})
}

View File

@ -1,41 +0,0 @@
use async_trait::async_trait;
use axum_login::{AuthnBackend, AuthUser, UserId};
use crate::users::UserCredentials;
use leptos::server_fn::error::ServerFnErrorErr;
use crate::models::User;
impl AuthUser for User {
type Id = i32;
// TODO: Ideally, we shouldn't have to unwrap here
fn id(&self) -> Self::Id {
self.id.unwrap()
}
fn session_auth_hash(&self) -> &[u8] {
self.password.as_ref().unwrap().as_bytes()
}
}
#[derive(Clone)]
pub struct AuthBackend;
#[cfg(feature = "ssr")]
#[async_trait]
impl AuthnBackend for AuthBackend {
type User = User;
type Credentials = UserCredentials;
type Error = ServerFnErrorErr;
async fn authenticate(&self, creds: Self::Credentials) -> Result<Option<Self::User>, Self::Error> {
crate::users::validate_user(creds).await
.map_err(|e| ServerFnErrorErr::ServerError(format!("Error validating user: {}", e)))
}
async fn get_user(&self, user_id: &UserId<Self>) -> Result<Option<Self::User>, Self::Error> {
crate::users::find_user_by_id(*user_id).await
.map_err(|e| ServerFnErrorErr::ServerError(format!("Error getting user: {}", e)))
}
}

View File

@ -1,7 +0,0 @@
pub mod sidebar;
pub mod dashboard;
pub mod search;
pub mod personal;
pub mod playlist;
pub mod create_playlist;
pub mod playlists;

View File

@ -1,53 +0,0 @@
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

@ -1,10 +0,0 @@
use leptos::*;
#[component]
pub fn Dashboard() -> impl IntoView {
view! {
<div class="dashboard-container home-component">
<h1 class="dashboard-header">Dashboard</h1>
</div>
}
}

View File

@ -1,72 +0,0 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
#[component]
pub fn Personal(logged_in: ReadSignal<bool>) -> impl IntoView {
view! {
<div class=" personal-container">
<Profile logged_in=logged_in/>
</div>
}
}
#[component]
pub fn Profile(logged_in: ReadSignal<bool>) -> impl IntoView {
let (dropdown_open, set_dropdown_open) = create_signal(false);
let open_dropdown = move |_| {
set_dropdown_open.update(|value| *value = !*value);
log!("opened dropdown");
};
view! {
<div class="profile-container">
<div class="profile-icon" on:click=open_dropdown>
<Icon icon=icondata::CgProfile />
</div>
<div class="dropdown-container" style={move || if dropdown_open() {"display: flex"} else {"display: none"}}>
<Show
when=move || {logged_in() == true}
fallback=move || view!{<DropDownNotLoggedIn />}
>
<DropDownLoggedIn/>
</Show>
</div>
</div>
}
}
#[component]
pub fn DropDownNotLoggedIn() -> impl IntoView {
view! {
<div class="dropdown-not-logged">
<h1>Not Logged in!</h1>
<a href="/login"><button class="auth-button">Log In</button></a>
<a href="/signup"><button class="auth-button">Sign up</button></a>
</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>
}
}

View File

@ -1,162 +0,0 @@
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

@ -1,56 +0,0 @@
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,10 +0,0 @@
use leptos::*;
#[component]
pub fn Search() -> impl IntoView {
view! {
<div class="search-container home-component">
<h1>Searching...</h1>
</div>
}
}

View File

@ -1,42 +0,0 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::components::playlists::Playlists;
#[component]
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");
};
let open_search = move |_| {
setter.update(|value| *value = false);
log!("open search");
};
view! {
<div class="sidebar-container">
<div class="sidebar-top-container">
<h2 class="header">LibreTunes</h2>
<div class="buttons" on:click=open_dashboard style={move || if active() {"color: #e1e3e1"} else {""}} >
<Icon icon=icondata::OcHomeFillLg />
<h1>Dashboard</h1>
</div>
<div class="buttons" on:click=open_search style={move || if !active() {"color: #e1e3e1"} else {""}}>
<Icon icon=icondata::BiSearchRegular />
<h1>Search</h1>
</div>
</div>
<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

@ -1,73 +0,0 @@
use http::status::StatusCode;
use leptos::*;
use thiserror::Error;
#[cfg(feature = "ssr")]
use leptos_axum::ResponseOptions;
#[derive(Clone, Debug, Error)]
pub enum AppError {
#[error("Not Found")]
NotFound,
}
impl AppError {
pub fn status_code(&self) -> StatusCode {
match self {
AppError::NotFound => StatusCode::NOT_FOUND,
}
}
}
// A basic function to display errors served by the error boundaries.
// Feel free to do more complicated things here than just displaying the error.
#[component]
pub fn ErrorTemplate(
#[prop(optional)] outside_errors: Option<Errors>,
#[prop(optional)] errors: Option<RwSignal<Errors>>,
) -> impl IntoView {
let errors = match outside_errors {
Some(e) => create_rw_signal(e),
None => match errors {
Some(e) => e,
None => panic!("No Errors found and we expected errors!"),
},
};
// Get Errors from Signal
let errors = errors.get_untracked();
// Downcast lets us take a type that implements `std::error::Error`
let errors: Vec<AppError> = errors
.into_iter()
.filter_map(|(_k, v)| v.downcast_ref::<AppError>().cloned())
.collect();
// Only the response code for the first error is actually sent from the server
// this may be customized by the specific application
#[cfg(feature = "ssr")]
{
let response = use_context::<ResponseOptions>();
if let Some(response) = response {
response.set_status(errors[0].status_code());
}
}
view! {
<h1>{if errors.len() > 1 {"Errors"} else {"Error"}}</h1>
<For
// a function that returns the items we're iterating over; a signal is fine
each= move || {errors.clone().into_iter().enumerate()}
// a unique key for each item as a reference
key=|(index, _error)| *index
// renders each item to a view
children=move |error| {
let error_string = error.1.to_string();
let error_code= error.1.status_code();
view! {
<h2>{error_code.to_string()}</h2>
<p>"Error: " {error_string}</p>
}
}
/>
}
}

View File

@ -1,40 +0,0 @@
use cfg_if::cfg_if;
cfg_if! { if #[cfg(feature = "ssr")] {
use axum::{
body::Body,
extract::State,
response::IntoResponse,
http::{Request, Response, StatusCode, Uri},
};
use axum::response::Response as AxumResponse;
use tower::ServiceExt;
use tower_http::services::ServeDir;
use leptos::*;
use crate::app::App;
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
let root = options.site_root.clone();
let res = get_static_file(uri.clone(), &root).await.unwrap();
if res.status() == StatusCode::OK {
res.into_response()
} else {
let handler = leptos_axum::render_app_to_stream(options.to_owned(), App);
handler(req).await.into_response()
}
}
pub async fn get_static_file(uri: Uri, root: &str) -> Result<Response<Body>, (StatusCode, String)> {
let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap();
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
// This path is relative to the cargo root
match ServeDir::new(root).oneshot(req).await {
Ok(res) => Ok(res.into_response()),
Err(err) => Err((
StatusCode::INTERNAL_SERVER_ERROR,
format!("Something went wrong: {err}"),
)),
}
}
}}

View File

@ -1,6 +1,5 @@
pub mod app; pub mod app;
pub mod auth; pub mod auth;
pub mod songdata;
pub mod playstatus; pub mod playstatus;
pub mod playbar; pub mod playbar;
pub mod database; pub mod database;
@ -8,17 +7,13 @@ pub mod queue;
pub mod song; pub mod song;
pub mod models; pub mod models;
pub mod pages; pub mod pages;
pub mod components; pub mod api;
pub mod users; pub mod users;
pub mod search; pub mod search;
pub mod fileserv;
pub mod error_template;
pub mod api;
use cfg_if::cfg_if; use cfg_if::cfg_if;
cfg_if! { cfg_if! {
if #[cfg(feature = "ssr")] { if #[cfg(feature = "ssr")] {
pub mod auth_backend;
pub mod schema; pub mod schema;
} }
} }

View File

@ -12,17 +12,12 @@ extern crate diesel;
extern crate diesel_migrations; extern crate diesel_migrations;
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
#[tokio::main] #[actix_web::main]
async fn main() { async fn main() -> std::io::Result<()> {
use axum::{routing::get, Router}; use actix_identity::IdentityMiddleware;
use leptos::*; use actix_session::storage::RedisSessionStore;
use leptos_axum::{generate_route_list, LeptosRoutes}; use actix_session::SessionMiddleware;
use libretunes::app::*; use actix_web::cookie::Key;
use libretunes::fileserv::{file_and_error_handler, get_static_file};
use tower_sessions::SessionManagerLayer;
use tower_sessions_redis_store::{fred::prelude::*, RedisStore};
use axum_login::AuthManagerLayerBuilder;
use libretunes::auth_backend::AuthBackend;
use dotenv::dotenv; use dotenv::dotenv;
dotenv().ok(); dotenv().ok();
@ -30,35 +25,60 @@ async fn main() {
// Bring the database up to date // Bring the database up to date
libretunes::database::migrate(); libretunes::database::migrate();
let session_secret_key = if let Ok(key) = std::env::var("SESSION_SECRET_KEY") {
Key::from(key.as_bytes())
} else {
Key::generate()
};
let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL must be set"); let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL must be set");
let redis_config = RedisConfig::from_url(&redis_url).expect(&format!("Unable to parse Redis URL: {}", redis_url)); let redis_store = RedisSessionStore::new(redis_url).await.unwrap();
let redis_pool = RedisPool::new(redis_config, None, None, None, 1).expect("Unable to create Redis pool");
redis_pool.connect();
redis_pool.wait_for_connect().await.expect("Unable to connect to Redis");
let session_store = RedisStore::new(redis_pool); use actix_files::Files;
let session_layer = SessionManagerLayer::new(session_store); use actix_web::*;
use leptos::*;
let auth_backend = AuthBackend; use leptos_actix::{generate_route_list, LeptosRoutes};
let auth_layer = AuthManagerLayerBuilder::new(auth_backend, session_layer).build(); use libretunes::app::*;
let conf = get_configuration(None).await.unwrap(); let conf = get_configuration(None).await.unwrap();
let leptos_options = conf.leptos_options; let addr = conf.leptos_options.site_addr;
let addr = leptos_options.site_addr;
// Generate the list of routes in your Leptos App // Generate the list of routes in your Leptos App
let routes = generate_route_list(App); let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes(&leptos_options, routes, App)
.route("/assets/*uri", get(|uri| get_static_file(uri, "")))
.layer(auth_layer)
.fallback(file_and_error_handler)
.with_state(leptos_options);
println!("listening on http://{}", &addr); println!("listening on http://{}", &addr);
let listener = tokio::net::TcpListener::bind(&addr).await.expect(&format!("Could not bind to {}", &addr)); HttpServer::new(move || {
axum::serve(listener, app.into_make_service()).await.expect("Server failed"); let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
App::new()
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
// serve JS/WASM/CSS from `pkg`
.service(Files::new("/pkg", format!("{site_root}/pkg")))
// serve other assets from the `assets` directory
.service(Files::new("/assets", site_root))
// serve the favicon from /favicon.ico
.service(favicon)
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), App)
.app_data(web::Data::new(leptos_options.to_owned()))
.wrap(IdentityMiddleware::default())
.wrap(SessionMiddleware::new(redis_store.clone(), session_secret_key.clone()))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?
.run()
.await
}
#[cfg(feature = "ssr")]
#[actix_web::get("favicon.ico")]
async fn favicon(
leptos_options: actix_web::web::Data<leptos::LeptosOptions>,
) -> actix_web::Result<actix_files::NamedFile> {
let leptos_options = leptos_options.into_inner();
let site_root = &leptos_options.site_root;
Ok(actix_files::NamedFile::open(format!(
"{site_root}/favicon.ico"
))?)
} }
#[cfg(not(any(feature = "ssr", feature = "csr")))] #[cfg(not(any(feature = "ssr", feature = "csr")))]

View File

@ -47,7 +47,7 @@ pub struct User {
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))] #[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::artists))] #[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::artists))]
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))] #[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize)]
pub struct Artist { pub struct Artist {
/// A unique id for the artist /// A unique id for the artist
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))] #[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", derive(Queryable, Selectable, Insertable))]
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::songs))] #[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::songs))]
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))] #[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize, Debug, Clone)] #[derive(Serialize, Deserialize, Clone)]
pub struct Song { pub struct Song {
/// A unique id for the song /// A unique id for the song
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))] #[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
@ -290,101 +290,3 @@ impl Song {
Ok(my_artists) 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

@ -1,8 +1,9 @@
use crate::auth::login; use crate::auth::login;
use leptos::leptos_dom::*; use leptos::leptos_dom::*;
use leptos::*; use leptos::*;
use leptos_icons::AiIcon::*;
use leptos_icons::IoIcon::*;
use leptos_icons::*; use leptos_icons::*;
use crate::users::UserCredentials;
#[component] #[component]
pub fn Login() -> impl IntoView { pub fn Login() -> impl IntoView {
@ -23,12 +24,7 @@ pub fn Login() -> impl IntoView {
let password1 = password.get(); let password1 = password.get();
spawn_local(async move { spawn_local(async move {
let user_credentials = UserCredentials { let login_result = login(username_or_email1, password1).await;
username_or_email: username_or_email1,
password: password1
};
let login_result = login(user_credentials).await;
if let Err(err) = login_result { if let Err(err) = login_result {
// Handle the error here, e.g., log it or display to the user // Handle the error here, e.g., log it or display to the user
log!("Error logging in: {:?}", err); log!("Error logging in: {:?}", err);
@ -46,7 +42,7 @@ pub fn Login() -> impl IntoView {
view! { view! {
<div class="auth-page-container"> <div class="auth-page-container">
<div class="login-container"> <div class="login-container">
<a class="return" href="/"><Icon icon=icondata::IoReturnUpBackSharp /></a> <a class="return" href="/"><Icon icon=Icon::from(IoReturnUpBackSharp) /></a>
<div class="header"> <div class="header">
<h1>LibreTunes</h1> <h1>LibreTunes</h1>
</div> </div>
@ -73,10 +69,12 @@ pub fn Login() -> impl IntoView {
<i></i> <i></i>
<Show <Show
when=move || {show_password() == false} 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=Icon::from(AiEyeInvisibleFilled) />
</button> /> }
> >
<button on:click=toggle_password class="login-password-visibility"> <button on:click=toggle_password class="login-password-visibility">
<Icon icon=icondata::AiEyeFilled /> <Icon icon=Icon::from(AiEyeFilled) />
</button> </button>
</Show> </Show>

View File

@ -2,6 +2,8 @@ use crate::auth::signup;
use crate::models::User; use crate::models::User;
use leptos::leptos_dom::*; use leptos::leptos_dom::*;
use leptos::*; use leptos::*;
use leptos_icons::AiIcon::*;
use leptos_icons::IoIcon::*;
use leptos_icons::*; use leptos_icons::*;
#[component] #[component]
@ -44,7 +46,7 @@ pub fn Signup() -> impl IntoView {
view! { view! {
<div class="auth-page-container"> <div class="auth-page-container">
<div class="signup-container"> <div class="signup-container">
<a class="return" href="/"><Icon icon=icondata::IoReturnUpBackSharp /></a> <a class="return" href="/"><Icon icon=Icon::from(IoReturnUpBackSharp) /></a>
<div class="header"> <div class="header">
<h1>LibreTunes</h1> <h1>LibreTunes</h1>
</div> </div>
@ -81,10 +83,10 @@ pub fn Signup() -> impl IntoView {
<i></i> <i></i>
<Show <Show
when=move || {show_password() == false} when=move || {show_password() == false}
fallback=move || view!{ <button on:click=toggle_password class="password-visibility"> <Icon icon=icondata::AiEyeInvisibleFilled /></button> /> } fallback=move || view!{ <button on:click=toggle_password class="password-visibility"> <Icon icon=Icon::from(AiEyeInvisibleFilled) /></button> /> }
> >
<button on:click=toggle_password class="password-visibility"> <button on:click=toggle_password class="password-visibility">
<Icon icon=icondata::AiEyeFilled /> <Icon icon=Icon::from(AiEyeFilled) />
</button> </button>
</Show> </Show>
</div> </div>

View File

@ -1,8 +1,12 @@
use crate::playstatus::PlayStatus; use crate::playstatus::PlayStatus;
use crate::api::songs::get_artists;
use crate::api::albums::get_album;
use leptos::ev::MouseEvent; use leptos::ev::MouseEvent;
use leptos::html::{Audio, Div}; use leptos::html::{Audio, Div};
use leptos::leptos_dom::*; use leptos::leptos_dom::*;
use leptos::*; use leptos::*;
use leptos_icons::BsIcon::*;
use leptos_icons::RiIcon::*;
use leptos_icons::*; use leptos_icons::*;
/// Width and height of the forward/backward skip buttons /// Width and height of the forward/backward skip buttons
@ -109,26 +113,6 @@ fn toggle_queue(status: impl SignalUpdate<Value = PlayStatus>) {
} }
/// Set the source of the audio player
///
/// Logs an error if the audio element is not available
///
///
/// # Arguments
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
/// * `src` - The source to set the audio player to
///
fn set_play_src(status: impl SignalUpdate<Value = PlayStatus>, src: String) {
status.update(|status| {
if let Some(audio) = status.get_audio() {
audio.set_src(&src);
log!("Player set src to: {}", src);
} else {
error!("Unable to set src: Audio element not available");
}
});
}
/// The play, pause, and skip buttons /// The play, pause, and skip buttons
#[component] #[component]
fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView { fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
@ -149,10 +133,8 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
status.update(|status| last_played_song = status.history.pop_back()); status.update(|status| last_played_song = status.history.pop_back());
if let Some(last_played_song) = last_played_song { if let Some(last_played_song) = last_played_song {
// Push the popped song to the front of the queue, and play it // Push the popped song to the front of the queue, and set status to playing
let next_src = last_played_song.song_path.clone();
status.update(|status| status.queue.push_front(last_played_song)); status.update(|status| status.queue.push_front(last_played_song));
set_play_src(status, next_src);
set_playing(status, true); set_playing(status, true);
} else { } else {
warn!("Unable to skip back: No previous song"); warn!("Unable to skip back: No previous song");
@ -191,9 +173,9 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
let icon = Signal::derive(move || { let icon = Signal::derive(move || {
status.with(|status| { status.with(|status| {
if status.playing { if status.playing {
icondata::BsPauseFill Icon::from(BsPauseFill)
} else { } else {
icondata::BsPlayFill Icon::from(BsPlayFill)
} }
}) })
}); });
@ -202,7 +184,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
<div class="playcontrols" align="center"> <div class="playcontrols" align="center">
<button on:click=skip_back on:mousedown=prevent_focus> <button on:click=skip_back on:mousedown=prevent_focus>
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=icondata::BsSkipStartFill /> <Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=Icon::from(BsSkipStartFill) />
</button> </button>
<button on:click=toggle_play on:mousedown=prevent_focus> <button on:click=toggle_play on:mousedown=prevent_focus>
@ -210,7 +192,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
</button> </button>
<button on:click=skip_forward on:mousedown=prevent_focus> <button on:click=skip_forward on:mousedown=prevent_focus>
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=icondata::BsSkipEndFill /> <Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=Icon::from(BsSkipEndFill) />
</button> </button>
</div> </div>
@ -243,26 +225,46 @@ fn PlayDuration(elapsed_secs: MaybeSignal<i64>, total_secs: MaybeSignal<i64>) ->
fn MediaInfo(status: RwSignal<PlayStatus>) -> impl IntoView { fn MediaInfo(status: RwSignal<PlayStatus>) -> impl IntoView {
let name = Signal::derive(move || { let name = Signal::derive(move || {
status.with(|status| { status.with(|status| {
status.queue.front().map_or("No media playing".into(), |song| song.name.clone()) status.queue.front().map_or("No media playing".into(), |song| song.title.clone())
}) })
}); });
let artist = Signal::derive(move || { let song_id = Signal::derive(move || {
status.with(|status| { status.with(|status| {
status.queue.front().map_or("".into(), |song| song.artist.clone()) status.queue.front().map_or(None, |song| song.id)
}) })
}); });
let album = Signal::derive(move || { let song_artists_resource = create_resource(song_id, move |song_id| async move {
if let Some(song_id) = song_id {
let artists_vec = get_artists(Some(song_id)).await.map_or(Vec::new(), |artists| artists);
// convert the vec of artists to a string of artists separated by commas
let artists_string = artists_vec.iter().map(|artist| artist.name.clone()).collect::<Vec<String>>().join(", ");
artists_string
} else {
"".into()
}
});
let album_id = Signal::derive(move || {
status.with(|status| { status.with(|status| {
status.queue.front().map_or("".into(), |song| song.album.clone()) status.queue.front().map_or(None, |song| song.album_id)
}) })
}); });
let album_resource = create_resource(album_id, move |album_id| async move {
// get the album name attribute or return ""
if let Some(album_id) = album_id {
get_album(Some(album_id)).await.map_or("".into(), |album| album.title)
} else {
"".into()
}
});
let image = Signal::derive(move || { let image = Signal::derive(move || {
status.with(|status| { status.with(|status| {
// TODO Use some default / unknown image? // TODO Use some default / unknown image?
status.queue.front().map_or("".into(), |song| song.image_path.clone()) status.queue.front().map_or("".into(), |song| song.image_path.clone().unwrap_or("".into()))
}) })
}); });
@ -272,7 +274,28 @@ fn MediaInfo(status: RwSignal<PlayStatus>) -> impl IntoView {
<div class="media-info-text"> <div class="media-info-text">
{name} {name}
<br/> <br/>
{artist} - {album} <Suspense
fallback=move || {
view! {}
}
>
{move || {
song_artists_resource.get().map_or(view!{{}""}, |artists_string| view! {
{artists_string}" - "
})
}}
</Suspense>
<Suspense
fallback=move || {
view! {}
}
>
{move || {
album_resource.get().map_or(view!{{}""}, |album_name| view! {
""{album_name}
})
}}
</Suspense>
</div> </div>
</div> </div>
} }
@ -335,7 +358,7 @@ fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
view! { view! {
<div class="queue-toggle"> <div class="queue-toggle">
<button on:click=update_queue on:mousedown=prevent_focus> <button on:click=update_queue on:mousedown=prevent_focus>
<Icon class="controlbtn" width=QUEUE_BTN_SIZE height=QUEUE_BTN_SIZE icon=icondata::RiPlayListMediaFill /> <Icon class="controlbtn" width=QUEUE_BTN_SIZE height=QUEUE_BTN_SIZE icon=Icon::from(RiPlayListMediaFill) />
</button> </button>
</div> </div>
} }
@ -344,6 +367,33 @@ fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
/// The main play bar component, containing the progress bar, media info, play controls, and play duration /// The main play bar component, containing the progress bar, media info, play controls, and play duration
#[component] #[component]
pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView { pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// Set the source of the audio player to the first song in the queue
let current_song_path = create_memo(
move |_| {
status.with(|status| {
status.queue.front().map(|song| song.storage_path.clone())
})
}
);
create_effect(move |_| {
current_song_path.with(|current_song_path| {
status.with_untracked(|status| {
if let Some(audio) = status.get_audio() {
if let Some(song_path) = current_song_path {
audio.set_src(&song_path);
log!("Player set src to: {}", song_path);
} else {
// We are treating this as a non-fatal error because the queue could be empty or finished
warn!("Unable to set src: No song in queue");
}
} else {
error!("Unable to set src: Audio element not available");
}
});
});
});
// Listen for key down events -- arrow keys don't seem to trigger key press events // Listen for key down events -- arrow keys don't seem to trigger key press events
let _arrow_key_handle = window_event_listener(ev::keydown, move |e: ev::KeyboardEvent| { let _arrow_key_handle = window_event_listener(ev::keydown, move |e: ev::KeyboardEvent| {
if e.key() == "ArrowRight" { if e.key() == "ArrowRight" {
@ -400,11 +450,11 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
status.with_untracked(|status| { status.with_untracked(|status| {
// Start playing the first song in the queue, if available // Start playing the first song in the queue, if available
if let Some(song) = status.queue.front() { if let Some(song) = status.queue.front() {
log!("Starting playing with song: {}", song.name); log!("Starting playing with song: {}", song.title);
// Don't use the set_play_src / set_playing helper function // Don't use the set_play_src / set_playing helper function
// here because we already have access to the audio element // here because we already have access to the audio element
audio.set_src(&song.song_path); audio.set_src(&song.storage_path);
if let Err(e) = audio.play() { if let Err(e) = audio.play() {
error!("Error playing audio on load: {:?}", e); error!("Error playing audio on load: {:?}", e);
@ -453,7 +503,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
let prev_song = status.queue.pop_front(); let prev_song = status.queue.pop_front();
if let Some(prev_song) = prev_song { if let Some(prev_song) = prev_song {
log!("Adding song to history: {}", prev_song.name); log!("Adding song to history: {}", prev_song.title);
status.history.push_back(prev_song); status.history.push_back(prev_song);
} else { } else {
log!("Queue empty, no previous song to add to history"); log!("Queue empty, no previous song to add to history");
@ -462,7 +512,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// Get the next song to play, if available // Get the next song to play, if available
let next_src = status.with_untracked(|status| { let next_src = status.with_untracked(|status| {
status.queue.front().map(|song| song.song_path.clone()) status.queue.front().map(|song| song.storage_path.clone())
}); });
if let Some(audio) = audio_ref.get() { if let Some(audio) = audio_ref.get() {

View File

@ -3,7 +3,7 @@ use leptos::NodeRef;
use leptos::html::Audio; use leptos::html::Audio;
use std::collections::VecDeque; use std::collections::VecDeque;
use crate::songdata::SongData; use crate::models::Song;
/// Represents the global state of the audio player feature of LibreTunes /// Represents the global state of the audio player feature of LibreTunes
pub struct PlayStatus { pub struct PlayStatus {
@ -14,9 +14,9 @@ pub struct PlayStatus {
/// A reference to the HTML audio element /// A reference to the HTML audio element
pub audio_player: Option<NodeRef<Audio>>, pub audio_player: Option<NodeRef<Audio>>,
/// A queue of songs that have been played, ordered from oldest to newest /// A queue of songs that have been played, ordered from oldest to newest
pub history: VecDeque<SongData>, pub history: VecDeque<Song>,
/// A queue of songs that have yet to be played, ordered from next up to last /// A queue of songs that have yet to be played, ordered from next up to last
pub queue: VecDeque<SongData>, pub queue: VecDeque<Song>,
} }
impl PlayStatus { impl PlayStatus {

View File

@ -4,6 +4,7 @@ use leptos::ev::MouseEvent;
use leptos::leptos_dom::*; use leptos::leptos_dom::*;
use leptos::*; use leptos::*;
use leptos_icons::*; use leptos_icons::*;
use leptos_icons::CgIcon::*;
use leptos::ev::DragEvent; use leptos::ev::DragEvent;
const RM_BTN_SIZE: &str = "2.5rem"; const RM_BTN_SIZE: &str = "2.5rem";
@ -98,14 +99,14 @@ pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
on:dragenter=move |e: DragEvent| on_drag_enter(e, index) on:dragenter=move |e: DragEvent| on_drag_enter(e, index)
on:dragover=on_drag_over on:dragover=on_drag_over
> >
<Song song_image_path=song.image_path.clone() song_title=song.name.clone() song_artist=song.artist.clone() /> <Song song_id_arg=song.id song_image_path=song.image_path.clone().unwrap_or("".to_string()) song_title=song.title.clone() />
<Show <Show
when=move || index != 0 when=move || index != 0
fallback=|| view!{ fallback=|| view!{
<p>Playing</p> <p>Playing</p>
}> }>
<button on:click=move |_| remove_song(index) on:mousedown=prevent_focus> <button on:click=move |_| remove_song(index) on:mousedown=prevent_focus>
<Icon class="remove-song" width=RM_BTN_SIZE height=RM_BTN_SIZE icon=icondata::CgTrash /> <Icon class="remove-song" width=RM_BTN_SIZE height=RM_BTN_SIZE icon=Icon::from(CgTrash) />
</button> </button>
</Show> </Show>
</div> </div>

View File

@ -22,22 +22,6 @@ 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! { diesel::table! {
song_artists (song_id, artist_id) { song_artists (song_id, artist_id) {
song_id -> Int4, song_id -> Int4,
@ -70,9 +54,6 @@ diesel::table! {
diesel::joinable!(album_artists -> albums (album_id)); diesel::joinable!(album_artists -> albums (album_id));
diesel::joinable!(album_artists -> artists (artist_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 -> artists (artist_id));
diesel::joinable!(song_artists -> songs (song_id)); diesel::joinable!(song_artists -> songs (song_id));
diesel::joinable!(songs -> albums (album_id)); diesel::joinable!(songs -> albums (album_id));
@ -81,8 +62,6 @@ diesel::allow_tables_to_appear_in_same_query!(
album_artists, album_artists,
albums, albums,
artists, artists,
playlist_songs,
playlists,
song_artists, song_artists,
songs, songs,
users, users,

View File

@ -1,13 +1,41 @@
use leptos::*; use leptos::*;
use leptos::logging::*;
use crate::api::songs::get_artists;
#[component] #[component]
pub fn Song(song_image_path: String, song_title: String, song_artist: String) -> impl IntoView { pub fn Song(song_id_arg: Option<i32>, song_image_path: String, song_title: String) -> impl IntoView {
let song_id = Signal::derive(move || song_id_arg);
let song_artists_resource = create_resource(song_id, move |song_id| async move {
let artists_vec = get_artists(song_id).await.unwrap_or_else(|_| {
warn!("Error when searching for artists for song");
Vec::new()
});
// convert the vec of artists to a string of artists separated by commas
let artists_string = artists_vec.iter().map(|artist| artist.name.clone()).collect::<Vec<String>>().join(", ");
artists_string
});
view!{ view!{
<div class="queue-song"> <div class="queue-song">
<img src={song_image_path} alt={song_title.clone()} /> <img src={song_image_path} alt={song_title.clone()} />
<div class="queue-song-info"> <div class="queue-song-info">
<h3>{song_title}</h3> <h3>{song_title}</h3>
<p>{song_artist}</p> <Suspense
fallback=move || view! {<p class="fallback-artists">""</p>}
>
{move || {
song_artists_resource.get().map(|artists_string| {
if artists_string.is_empty() {
view! {<p class="fallback-artists">""</p>}
}
else {
view! {<p class="artists">{artists_string}</p>}
}
})
}}
</Suspense>
</div> </div>
</div> </div>
} }

View File

@ -1,16 +0,0 @@
/// Holds information about a song
#[derive(Debug, Clone)]
pub struct SongData {
/// Song name
pub name: String,
/// Song artist
pub artist: String,
/// Song album
pub album: String,
/// Path to song file, relative to the root of the web server.
/// For example, `"/assets/audio/Song.mp3"`
pub song_path: String,
/// Path to song image, relative to the root of the web server.
/// For example, `"/assets/images/Song.jpg"`
pub image_path: String,
}

View File

@ -14,42 +14,19 @@ cfg_if::cfg_if! {
} }
use leptos::*; use leptos::*;
use serde::{Serialize, Deserialize};
use crate::models::User; use crate::models::User;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct UserCredentials {
pub username_or_email: String,
pub password: String
}
/// Get a user from the database by username or email /// Get a user from the database by username or email
/// Returns a Result with the user if found, None if not found, or an error if there was a problem /// Returns a Result with the user if found, None if not found, or an error if there was a problem
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub async fn find_user(username_or_email: String) -> Result<Option<User>, ServerFnError> { pub async fn find_user(username_or_email: String) -> Result<Option<User>, ServerFnError> {
use crate::schema::users::dsl::*; use crate::schema::users::dsl::*;
use leptos::server_fn::error::NoCustomError;
// Look for either a username or email that matches the input, and return an option with None if no user is found // Look for either a username or email that matches the input, and return an option with None if no user is found
let db_con = &mut get_db_conn(); let db_con = &mut get_db_conn();
let user = users.filter(username.eq(username_or_email.clone())).or_filter(email.eq(username_or_email)) let user = users.filter(username.eq(username_or_email.clone())).or_filter(email.eq(username_or_email))
.first::<User>(db_con).optional() .first::<User>(db_con).optional()
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user from database: {}", e)))?; .map_err(|e| ServerFnError::ServerError(format!("Error getting user from database: {}", e)))?;
Ok(user)
}
/// Get a user from the database by ID
/// Returns a Result with the user if found, None if not found, or an error if there was a problem
#[cfg(feature = "ssr")]
pub async fn find_user_by_id(user_id: i32) -> Result<Option<User>, ServerFnError> {
use crate::schema::users::dsl::*;
use leptos::server_fn::error::NoCustomError;
let db_con = &mut get_db_conn();
let user = users.filter(id.eq(user_id))
.first::<User>(db_con).optional()
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user from database: {}", e)))?;
Ok(user) Ok(user)
} }
@ -59,14 +36,13 @@ pub async fn find_user_by_id(user_id: i32) -> Result<Option<User>, ServerFnError
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> { pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> {
use crate::schema::users::dsl::*; use crate::schema::users::dsl::*;
use leptos::server_fn::error::NoCustomError;
let new_password = new_user.password.clone() let new_password = new_user.password.clone()
.ok_or(ServerFnError::<NoCustomError>::ServerError(format!("No password provided for user {}", new_user.username)))?; .ok_or(ServerFnError::ServerError(format!("No password provided for user {}", new_user.username)))?;
let salt = SaltString::generate(&mut OsRng); let salt = SaltString::generate(&mut OsRng);
let password_hash = Pbkdf2.hash_password(new_password.as_bytes(), &salt) let password_hash = Pbkdf2.hash_password(new_password.as_bytes(), &salt)
.map_err(|_| ServerFnError::<NoCustomError>::ServerError("Error hashing password".to_string()))?.to_string(); .map_err(|_| ServerFnError::ServerError("Error hashing password".to_string()))?.to_string();
let new_user = User { let new_user = User {
password: Some(password_hash), password: Some(password_hash),
@ -76,7 +52,7 @@ pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> {
let db_con = &mut get_db_conn(); let db_con = &mut get_db_conn();
diesel::insert_into(users).values(&new_user).execute(db_con) diesel::insert_into(users).values(&new_user).execute(db_con)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error creating user: {}", e)))?; .map_err(|e| ServerFnError::ServerError(format!("Error creating user: {}", e)))?;
Ok(()) Ok(())
} }
@ -84,11 +60,9 @@ pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> {
/// Validate a user's credentials /// Validate a user's credentials
/// Returns a Result with the user if the credentials are valid, None if not valid, or an error if there was a problem /// Returns a Result with the user if the credentials are valid, None if not valid, or an error if there was a problem
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub async fn validate_user(credentials: UserCredentials) -> Result<Option<User>, ServerFnError> { pub async fn validate_user(username_or_email: String, password: String) -> Result<Option<User>, ServerFnError> {
use leptos::server_fn::error::NoCustomError; let db_user = find_user(username_or_email.clone()).await
.map_err(|e| ServerFnError::ServerError(format!("Error getting user from database: {}", e)))?;
let db_user = find_user(credentials.username_or_email.clone()).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user from database: {}", e)))?;
// If the user is not found, return None // If the user is not found, return None
let db_user = match db_user { let db_user = match db_user {
@ -97,18 +71,18 @@ pub async fn validate_user(credentials: UserCredentials) -> Result<Option<User>,
}; };
let db_password = db_user.password.clone() let db_password = db_user.password.clone()
.ok_or(ServerFnError::<NoCustomError>::ServerError(format!("No password found for user {}", db_user.username)))?; .ok_or(ServerFnError::ServerError(format!("No password found for user {}", db_user.username)))?;
let password_hash = PasswordHash::new(&db_password) let password_hash = PasswordHash::new(&db_password)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error hashing supplied password: {}", e)))?; .map_err(|e| ServerFnError::ServerError(format!("Error hashing supplied password: {}", e)))?;
match Pbkdf2.verify_password(credentials.password.as_bytes(), &password_hash) { match Pbkdf2.verify_password(password.as_bytes(), &password_hash) {
Ok(()) => {}, Ok(()) => {},
Err(Error::Password) => { Err(Error::Password) => {
return Ok(None); return Ok(None);
}, },
Err(e) => { Err(e) => {
return Err(ServerFnError::<NoCustomError>::ServerError(format!("Error verifying password: {}", e))); return Err(ServerFnError::ServerError(format!("Error verifying password: {}", e)));
} }
} }

View File

@ -1,10 +0,0 @@
@import "theme.scss";
.dashboard-container {
width: calc(100% - 22rem - 16rem);
.dashboard-header {
font-size: 1.2rem;
font-weight: 300;
border-bottom: 2px solid white;
}
}

View File

@ -1,16 +0,0 @@
@import "theme.scss";
.home-container {
margin-top: 0;
width: 100%;
height: 100vh;
display: flex;
flex-direction: row;
}
.home-component {
background: #1c1c1c;
height: 100vh;
margin: 2px;
padding: 0.2rem 1.5rem 1.5rem 1rem;
border-radius: 0.5rem;
}

View File

@ -1,13 +1,8 @@
@import "playbar.scss"; @import 'playbar.scss';
@import "theme.scss"; @import 'theme.scss';
@import "queue.scss"; @import 'queue.scss';
@import "login.scss"; @import 'login.scss';
@import "signup.scss"; @import 'signup.scss';
@import "sidebar.scss";
@import "dashboard.scss";
@import 'home.scss';
@import 'search.scss';
@import 'personal.scss';
body { body {
font-family: sans-serif; font-family: sans-serif;

View File

@ -1,74 +0,0 @@
@import "theme.scss";
.personal-container {
width: 16rem;
background: #1c1c1c;
height: 100vh;
margin: 2px;
border-radius: 0.5rem;
.profile-container {
display: flex;
border-radius: 0.4rem;
margin: 0.2rem;
min-height: 6rem;
border: 2px solid rgba(89, 89, 89, 0.199);
padding: 0.5rem;
.profile-icon {
display: inline-flex;
padding: 0.2rem;
cursor: pointer;
font-size: 2rem;
border-radius: 50%;
transition: all 0.3s;
height: max-content;
margin-left: auto;
}
.profile-icon:hover {
transform: scale(1.1);
background-color: rgba(255, 255, 255, 0.1);
}
.profile-icon:active {
transform: scale(0.8);
}
.dropdown-container {
position: absolute;
top: 3.8rem;
right: 0.8rem;
background: #1c1c1c;
border-radius: 0.5rem;
width: 10rem;
z-index: 1;
background-color: red;
border: 1px solid grey;
.dropdown-not-logged {
display: flex;
flex-direction: column;
width: 100%;
align-items: center;
justify-content: center;
h1 {
font-size: 1.2rem;
}
.auth-button {
}
}
}
.dropdown-container:before {
content: "";
position: absolute;
top: -0.4rem;
right: 0.92rem;
width: 10px;
height: 10px;
transform: rotate(45deg);
background-color: red;
border-left: 1px solid grey;
border-top: 1px solid grey;
}
}
}

View File

@ -48,7 +48,12 @@
color: #fff; /* Adjust text color for song */ color: #fff; /* Adjust text color for song */
} }
p { .fallback-artists {
margin: 14px 0 0 0; /* Adjust margin for blank space to align text */
}
.artists {
font-size: 14px;
margin: 0; /* Remove default margin for paragraph */ margin: 0; /* Remove default margin for paragraph */
color: #aaa; /* Adjust text color for artist */ color: #aaa; /* Adjust text color for artist */
} }

View File

@ -1,6 +0,0 @@
@import "theme.scss";
.search-container {
width: calc(100% - 22rem - 16rem);
}

View File

@ -1,343 +0,0 @@
@import "theme.scss";
.sidebar-container {
background-color: transparent;
width: 22rem;
height: calc(100% - 75px);
}
.sidebar-top-container {
border-radius: 1rem;
background-color: #1c1c1c;
height: 9rem;
margin: 3px;
padding: 0.1rem 1rem 1rem 1rem;
}
.sidebar-top-container .header {
font-size: 1.2rem;
}
.sidebar-top-container .buttons {
display: flex;
flex-direction: row;
font-size: 1.8rem;
align-items: center;
transition: all 0.5s;
cursor: pointer;
color: grey;
}
.sidebar-top-container .buttons:hover {
color: white;
}
.sidebar-top-container .buttons:last-child {
margin-left: 0.02rem;
margin-top: 0.5rem;
}
.sidebar-top-container h1 {
font-size: 0.95rem;
margin-left: 0.9rem;
font-weight: 400;
font-style: $standard-font;
letter-spacing: 0.5px;
}
.sidebar-bottom-container {
border-radius: 1rem;
background-color: #1c1c1c;
margin: 3px;
margin-top: 6px;
padding: 0.2rem 1rem 1rem 1rem;
height: calc(100% - 9rem);
.sidebar-playlists-container {
width: 100%;
height: 100%;
.heading {
display: flex;
flex-direction: row;
display: flex;
flex-direction: row;
justify-content: space-between;
align-items: center;
.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;
}
}
.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;
}
}
}
}

View File

@ -1,7 +1,3 @@
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300..800;1,300..800&display=swap');
$standard-font: 'Open Sans', sans-serif;
$background-color: #030303; $background-color: #030303;
$accent-color: #4032a8; $accent-color: #4032a8;
$text-controls-color: #e0e0e0; $text-controls-color: #e0e0e0;