Compare commits

..

27 Commits

Author SHA1 Message Date
b800e4ee47 Merge pull request 'Fix time not implemented on wasm on profile page' (#135) from 134-fix-time-not-implemented-on-wasm into main
Reviewed-on: LibreTunes/LibreTunes#135
2024-11-04 23:40:11 +00:00
6dcbba2588 Switch to chrono instead of time 2024-11-04 18:23:25 -05:00
820a1d816a Merge pull request 'Create profile page' (#133) from 42-create-profile-page into main
Reviewed-on: LibreTunes/LibreTunes#133
2024-11-04 22:40:14 +00:00
f23430af73 Remove unnecessary Artist import 2024-11-04 17:16:09 -05:00
ef5576ab3f Create profile page 2024-11-04 17:15:55 -05:00
833393cb3a Add generic Error component 2024-11-04 17:11:26 -05:00
39dd8099cd Make ServerError a component instead of a page 2024-11-04 17:03:45 -05:00
5011cda8fa Allow home-component to scroll 2024-11-04 17:01:42 -05:00
89433df8b6 Add function to get user by id 2024-11-04 16:34:17 -05:00
ddcb4a5be7 Add loading indicator 2024-11-04 16:34:13 -05:00
414489d1be Return ArtistData from top_artists 2024-11-04 00:29:53 -05:00
186c622e6f Merge pull request 'Create global logged in user resource' (#128) from 126-create-global-logged-in-user-resource into main
Reviewed-on: LibreTunes/LibreTunes#128
2024-11-03 22:23:32 +00:00
35abbe19ee Merge branch '126-create-global-logged-in-user-resource' into 42-create-profile-page 2024-11-03 17:18:43 -05:00
2b380d7787 Refetch logged in user on login/signup 2024-11-03 17:13:40 -05:00
8ac3a87c58 Add global logged in user Resource 2024-11-03 16:59:46 -05:00
43a5b519fd Add API endpoint to get logged in user 2024-11-03 16:59:23 -05:00
251d567863 Return logged in user from login endpoint 2024-11-03 16:52:15 -05:00
1f70da1747 Merge pull request 'Added webp files' (#125) from 121-add-webp-files-to-gitignore into main
Reviewed-on: LibreTunes/LibreTunes#125
2024-11-02 02:58:41 +00:00
a70de76c4d Added webp files 2024-11-02 02:37:50 +00:00
e66b5e4976 Add component to display SongList with additional data 2024-11-01 14:36:38 -04:00
0453aef37d Fix incorrect placeholder image path 2024-11-01 14:26:38 -04:00
4e4c94a189 Merge branch '106-create-song-list-component' into 42-create-profile-page 2024-11-01 13:22:37 -04:00
23bfb510c1 Add functions to get top/recent songs and artists from history 2024-11-01 13:05:47 -04:00
f299254d55 Merge pull request 'Fix Docker compose missing libretunes-images volume' (#120) from 119-fix-docker-compose-missing-libretunesimages-volume into main
Reviewed-on: LibreTunes/LibreTunes#120
2024-10-25 19:40:10 +00:00
14aa4d236e Add libretunes-images to volumes 2024-10-25 18:28:45 +00:00
f1e177c7b0 Add page for displaying error 2024-10-21 22:57:27 -04:00
88e2a229a4 Move home component width to .home-component selector 2024-10-21 22:54:26 -04:00
34 changed files with 900 additions and 54 deletions

1
.gitignore vendored
View File

@ -24,6 +24,7 @@ playwright/.cache/
*.jpeg
*.png
*.gif
*.webp
# Environment variables
.env

11
Cargo.lock generated
View File

@ -378,13 +378,16 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "chrono"
version = "0.4.37"
version = "0.4.38"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a0d04d43504c61aa6c7531f1871dd0d418d91130162063b789da00fd7057a5e"
checksum = "a21f936df1771bf62b77f047b726c4625ff2e8aa607c01ec06e5a05bd8463401"
dependencies = [
"android-tzdata",
"iana-time-zone",
"js-sys",
"num-traits",
"serde",
"wasm-bindgen",
"windows-targets 0.52.4",
]
@ -690,11 +693,11 @@ checksum = "03fc05c17098f21b89bc7d98fe1dd3cce2c11c2ad8e145f2a44fe08ed28eb559"
dependencies = [
"bitflags 2.5.0",
"byteorder",
"chrono",
"diesel_derives",
"itoa",
"pq-sys",
"r2d2",
"time",
]
[[package]]
@ -1834,6 +1837,7 @@ dependencies = [
"axum",
"axum-login",
"cfg-if",
"chrono",
"console_error_panic_hook",
"diesel",
"diesel_migrations",
@ -1857,7 +1861,6 @@ dependencies = [
"server_fn",
"symphonia",
"thiserror",
"time",
"tokio",
"tower 0.5.1",
"tower-http",

View File

@ -19,11 +19,10 @@ wasm-bindgen = { version = "=0.2.93", default-features = false, optional = true
leptos_icons = { version = "0.3.0" }
icondata = { version = "0.3.0" }
dotenv = { version = "0.15.0", optional = true }
diesel = { version = "2.1.4", features = ["postgres", "r2d2", "time"], default-features = false, optional = true }
diesel = { version = "2.1.4", features = ["postgres", "r2d2", "chrono"], default-features = false, optional = true }
lazy_static = { version = "1.4.0", optional = true }
serde = { version = "1.0.195", features = ["derive"], default-features = false }
openssl = { version = "0.10.63", optional = true }
time = { version = "0.3.34", features = ["serde"], default-features = false }
diesel_migrations = { version = "2.1.0", optional = true }
pbkdf2 = { version = "0.12.2", features = ["simple"], optional = true }
tokio = { version = "1", optional = true, features = ["rt-multi-thread"] }
@ -42,6 +41,7 @@ flexi_logger = { version = "0.28.0", optional = true, default-features = false }
web-sys = "0.3.69"
leptos-use = "0.13.5"
image-convert = { version = "0.18.0", optional = true, default-features = false }
chrono = { version = "0.4.38", default-features = false, features = ["serde", "clock"] }
[features]
hydrate = [
@ -50,6 +50,7 @@ hydrate = [
"leptos_router/hydrate",
"console_error_panic_hook",
"wasm-bindgen",
"chrono/wasmbind",
]
ssr = [
"dep:leptos_axum",

View File

@ -53,5 +53,6 @@ services:
volumes:
libretunes-audio:
libretunes-images:
libretunes-redis:
libretunes-postgres:

View File

@ -1,2 +0,0 @@
ALTER TABLE songs
DROP COLUMN added_date;

View File

@ -1,2 +0,0 @@
ALTER TABLE songs
ADD COLUMN added_date DATE DEFAULT CURRENT_DATE;

View File

@ -1,7 +1,7 @@
use crate::models::Artist;
use crate::components::dashboard_tile::DashboardTile;
use time::Date;
use chrono::NaiveDate;
/// Holds information about an album
///
@ -14,7 +14,7 @@ pub struct AlbumData {
/// Album artists
pub artists: Vec<Artist>,
/// Album release date
pub release_date: Option<Date>,
pub release_date: Option<NaiveDate>,
/// Path to album image, relative to the root of the web server.
/// For example, `"/assets/images/Album.jpg"`
pub image_path: String,

View File

@ -1,4 +1,4 @@
use std::time::SystemTime;
use chrono::NaiveDateTime;
use leptos::*;
use crate::models::HistoryEntry;
use crate::models::Song;
@ -25,7 +25,7 @@ pub async fn get_history(limit: Option<i64>) -> Result<Vec<HistoryEntry>, Server
/// Get the listen dates and songs of the current user.
#[server(endpoint = "history/get_songs")]
pub async fn get_history_songs(limit: Option<i64>) -> Result<Vec<(SystemTime, Song)>, ServerFnError> {
pub async fn get_history_songs(limit: Option<i64>) -> Result<Vec<(NaiveDateTime, Song)>, ServerFnError> {
let user = get_user().await?;
let db_con = &mut get_db_conn();
let songs = user.get_history_songs(limit, db_con)

View File

@ -3,10 +3,23 @@ use server_fn::codec::{MultipartData, MultipartFormData};
use cfg_if::cfg_if;
use crate::songdata::SongData;
use crate::artistdata::ArtistData;
use chrono::NaiveDateTime;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::auth::get_user;
use server_fn::error::NoCustomError;
use crate::database::get_db_conn;
use diesel::prelude::*;
use diesel::dsl::count;
use crate::models::*;
use crate::schema::*;
use std::collections::HashMap;
}
}
@ -47,3 +60,241 @@ pub async fn upload_picture(data: MultipartData) -> Result<(), ServerFnError> {
Ok(())
}
/// Get a user's recent songs listened to
/// Optionally takes a limit parameter to limit the number of songs returned.
/// If not provided, all songs ever listend to are returned.
/// Returns a list of tuples with the date the song was listened to
/// and the song data, sorted by date (most recent first).
#[server(endpoint = "/profile/recent_songs")]
pub async fn recent_songs(for_user_id: i32, limit: Option<i64>) -> Result<Vec<(NaiveDateTime, SongData)>, ServerFnError> {
let mut db_con = get_db_conn();
// Get the ids of the most recent songs listened to
let history_items: Vec<i32> =
if let Some(limit) = limit {
song_history::table
.filter(song_history::user_id.eq(for_user_id))
.order(song_history::date.desc())
.limit(limit)
.select(song_history::id)
.load(&mut db_con)?
} else {
song_history::table
.filter(song_history::user_id.eq(for_user_id))
.order(song_history::date.desc())
.select(song_history::id)
.load(&mut db_con)?
};
// Take the history ids and get the song data for them
let history: Vec<(HistoryEntry, Song, Option<Album>, Option<Artist>, Option<(i32, i32)>, Option<(i32, i32)>)>
= song_history::table
.filter(song_history::id.eq_any(history_items))
.inner_join(songs::table)
.left_join(albums::table.on(songs::album_id.eq(albums::id.nullable())))
.left_join(song_artists::table.inner_join(artists::table).on(songs::id.eq(song_artists::song_id)))
.left_join(song_likes::table.on(songs::id.eq(song_likes::song_id).and(song_likes::user_id.eq(for_user_id))))
.left_join(song_dislikes::table.on(
songs::id.eq(song_dislikes::song_id).and(song_dislikes::user_id.eq(for_user_id))))
.select((
song_history::all_columns,
songs::all_columns,
albums::all_columns.nullable(),
artists::all_columns.nullable(),
song_likes::all_columns.nullable(),
song_dislikes::all_columns.nullable(),
))
.load(&mut db_con)?;
// Process the history data into a map of song ids to song data
let mut history_songs: HashMap<i32, (NaiveDateTime, SongData)> = HashMap::with_capacity(history.len());
for (history, song, album, artist, like, dislike) in history {
let song_id = history.song_id;
if let Some((_, stored_songdata)) = history_songs.get_mut(&song_id) {
// If the song is already in the map, update the artists
if let Some(artist) = artist {
stored_songdata.artists.push(artist);
}
} else {
let like_dislike = match (like, dislike) {
(Some(_), Some(_)) => Some((true, true)),
(Some(_), None) => Some((true, false)),
(None, Some(_)) => Some((false, true)),
_ => None,
};
let image_path = song.image_path.unwrap_or(
album.as_ref().map(|album| album.image_path.clone()).flatten()
.unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string()));
let songdata = SongData {
id: song_id,
title: song.title,
artists: artist.map(|artist| vec![artist]).unwrap_or_default(),
album: album,
track: song.track,
duration: song.duration,
release_date: song.release_date,
song_path: song.storage_path,
image_path: image_path,
like_dislike: like_dislike,
};
history_songs.insert(song_id, (history.date, songdata));
}
}
// Sort the songs by date
let mut history_songs: Vec<(NaiveDateTime, SongData)> = history_songs.into_values().collect();
history_songs.sort_by(|a, b| b.0.cmp(&a.0));
Ok(history_songs)
}
/// Get a user's top songs by play count from a date range
/// Optionally takes a limit parameter to limit the number of songs returned.
/// If not provided, all songs listened to in the date range are returned.
/// Returns a list of tuples with the play count and the song data, sorted by play count (most played first).
#[server(endpoint = "/profile/top_songs")]
pub async fn top_songs(for_user_id: i32, start_date: NaiveDateTime, end_date: NaiveDateTime, limit: Option<i64>)
-> Result<Vec<(i64, SongData)>, ServerFnError>
{
let mut db_con = get_db_conn();
// Get the play count and ids of the songs listened to in the date range
let history_counts: Vec<(i32, i64)> =
if let Some(limit) = limit {
song_history::table
.filter(song_history::date.between(start_date, end_date))
.filter(song_history::user_id.eq(for_user_id))
.group_by(song_history::song_id)
.select((song_history::song_id, count(song_history::song_id)))
.order(count(song_history::song_id).desc())
.limit(limit)
.load(&mut db_con)?
} else {
song_history::table
.filter(song_history::date.between(start_date, end_date))
.filter(song_history::user_id.eq(for_user_id))
.group_by(song_history::song_id)
.select((song_history::song_id, count(song_history::song_id)))
.load(&mut db_con)?
};
let history_counts: HashMap<i32, i64> = history_counts.into_iter().collect();
let history_song_ids = history_counts.iter().map(|(song_id, _)| *song_id).collect::<Vec<i32>>();
// Get the song data for the songs listened to in the date range
let history_songs: Vec<(Song, Option<Album>, Option<Artist>, Option<(i32, i32)>, Option<(i32, i32)>)>
= songs::table
.filter(songs::id.eq_any(history_song_ids))
.left_join(albums::table.on(songs::album_id.eq(albums::id.nullable())))
.left_join(song_artists::table.inner_join(artists::table).on(songs::id.eq(song_artists::song_id)))
.left_join(song_likes::table.on(songs::id.eq(song_likes::song_id).and(song_likes::user_id.eq(for_user_id))))
.left_join(song_dislikes::table.on(
songs::id.eq(song_dislikes::song_id).and(song_dislikes::user_id.eq(for_user_id))))
.select((
songs::all_columns,
albums::all_columns.nullable(),
artists::all_columns.nullable(),
song_likes::all_columns.nullable(),
song_dislikes::all_columns.nullable(),
))
.load(&mut db_con)?;
// Process the history data into a map of song ids to song data
let mut history_songs_map: HashMap<i32, (i64, SongData)> = HashMap::with_capacity(history_counts.len());
for (song, album, artist, like, dislike) in history_songs {
let song_id = song.id
.ok_or(ServerFnError::ServerError::<NoCustomError>("Song id not found in database".to_string()))?;
if let Some((_, stored_songdata)) = history_songs_map.get_mut(&song_id) {
// If the song is already in the map, update the artists
if let Some(artist) = artist {
stored_songdata.artists.push(artist);
}
} else {
let like_dislike = match (like, dislike) {
(Some(_), Some(_)) => Some((true, true)),
(Some(_), None) => Some((true, false)),
(None, Some(_)) => Some((false, true)),
_ => None,
};
let image_path = song.image_path.unwrap_or(
album.as_ref().map(|album| album.image_path.clone()).flatten()
.unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string()));
let songdata = SongData {
id: song_id,
title: song.title,
artists: artist.map(|artist| vec![artist]).unwrap_or_default(),
album: album,
track: song.track,
duration: song.duration,
release_date: song.release_date,
song_path: song.storage_path,
image_path: image_path,
like_dislike: like_dislike,
};
let plays = history_counts.get(&song_id)
.ok_or(ServerFnError::ServerError::<NoCustomError>("Song id not found in history counts".to_string()))?;
history_songs_map.insert(song_id, (*plays, songdata));
}
}
// Sort the songs by play count
let mut history_songs: Vec<(i64, SongData)> = history_songs_map.into_values().collect();
history_songs.sort_by(|a, b| b.0.cmp(&a.0));
Ok(history_songs)
}
/// Get a user's top artists by play count from a date range
/// Optionally takes a limit parameter to limit the number of artists returned.
/// If not provided, all artists listened to in the date range are returned.
/// Returns a list of tuples with the play count and the artist data, sorted by play count (most played first).
#[server(endpoint = "/profile/top_artists")]
pub async fn top_artists(for_user_id: i32, start_date: NaiveDateTime, end_date: NaiveDateTime, limit: Option<i64>)
-> Result<Vec<(i64, ArtistData)>, ServerFnError>
{
let mut db_con = get_db_conn();
let artist_counts: Vec<(i64, Artist)> =
if let Some(limit) = limit {
song_history::table
.filter(song_history::date.between(start_date, end_date))
.filter(song_history::user_id.eq(for_user_id))
.inner_join(song_artists::table.on(song_history::song_id.eq(song_artists::song_id)))
.inner_join(artists::table.on(song_artists::artist_id.eq(artists::id)))
.group_by(artists::id)
.select((count(artists::id), artists::all_columns))
.order(count(artists::id).desc())
.limit(limit)
.load(&mut db_con)?
} else {
song_history::table
.filter(song_history::date.between(start_date, end_date))
.filter(song_history::user_id.eq(for_user_id))
.inner_join(song_artists::table.on(song_history::song_id.eq(song_artists::song_id)))
.inner_join(artists::table.on(song_artists::artist_id.eq(artists::id)))
.group_by(artists::id)
.select((count(artists::id), artists::all_columns))
.order(count(artists::id).desc())
.load(&mut db_con)?
};
let artist_data: Vec<(i64, ArtistData)> = artist_counts.into_iter().map(|(plays, artist)| {
(plays, ArtistData {
id: artist.id.unwrap(),
name: artist.name,
image_path: format!("/assets/images/artists/{}.webp", artist.id.unwrap()),
})
}).collect();
Ok(artist_data)
}

View File

@ -3,12 +3,17 @@ use crate::playbar::CustomTitle;
use crate::playstatus::PlayStatus;
use crate::queue::Queue;
use leptos::*;
use leptos::logging::*;
use leptos_meta::*;
use leptos_router::*;
use crate::pages::login::*;
use crate::pages::signup::*;
use crate::pages::profile::*;
use crate::error_template::{AppError, ErrorTemplate};
use crate::auth::get_logged_in_user;
use crate::models::User;
pub type LoggedInUserResource = Resource<(), Option<User>>;
#[component]
pub fn App() -> impl IntoView {
@ -19,6 +24,18 @@ pub fn App() -> impl IntoView {
let play_status = create_rw_signal(play_status);
let upload_open = create_rw_signal(false);
// A resource that fetches the logged in user
// This will not automatically refetch, so any login/logout related code
// should call `refetch` on this resource
let logged_in_user: LoggedInUserResource = create_resource(|| (), |_| async {
get_logged_in_user().await
.inspect_err(|e| {
error!("Error getting logged in user: {:?}", e);
})
.ok()
.flatten()
});
view! {
// injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet
@ -42,9 +59,11 @@ pub fn App() -> impl IntoView {
<Route path="" view=Dashboard />
<Route path="dashboard" view=Dashboard />
<Route path="search" view=Search />
<Route path="user/:id" view=move || view!{ <Profile logged_in_user /> } />
<Route path="user" view=move || view!{ <Profile logged_in_user /> } />
</Route>
<Route path="/login" view=Login />
<Route path="/signup" view=Signup />
<Route path="/login" view=move || view!{ <Login user=logged_in_user /> } />
<Route path="/signup" view=move || view!{ <Signup user=logged_in_user /> } />
</Routes>
</main>
</Router>
@ -54,7 +73,7 @@ pub fn App() -> impl IntoView {
use crate::components::sidebar::*;
use crate::components::dashboard::*;
use crate::components::search::*;
use crate::components::personal::*;
use crate::components::personal::Personal;
use crate::components::upload::*;
/// Renders the home page of your application.

View File

@ -1,8 +1,10 @@
use crate::components::dashboard_tile::DashboardTile;
use serde::{Serialize, Deserialize};
/// Holds information about an artist
///
/// Intended to be used in the front-end
#[derive(Clone, Serialize, Deserialize)]
pub struct ArtistData {
/// Artist id
pub id: i32,

View File

@ -57,7 +57,7 @@ pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
/// Takes in a username or email and a password in plaintext
/// Returns a Result with a boolean indicating if the login was successful
#[server(endpoint = "login")]
pub async fn login(credentials: UserCredentials) -> Result<bool, ServerFnError> {
pub async fn login(credentials: UserCredentials) -> Result<Option<User>, ServerFnError> {
use crate::users::validate_user;
let mut auth_session = extract::<AuthSession<AuthBackend>>().await
@ -66,12 +66,14 @@ pub async fn login(credentials: UserCredentials) -> Result<bool, ServerFnError>
let user = validate_user(credentials).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error validating user: {}", e)))?;
if let Some(user) = user {
if let Some(mut user) = user {
auth_session.login(&user).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error logging in user: {}", e)))?;
Ok(true)
user.password = None;
Ok(Some(user))
} else {
Ok(false)
Ok(None)
}
}
@ -145,6 +147,19 @@ pub async fn get_user() -> Result<User, ServerFnError> {
auth_session.user.ok_or(ServerFnError::<NoCustomError>::ServerError("User not logged in".to_string()))
}
#[server(endpoint = "get_logged_in_user")]
pub async fn get_logged_in_user() -> Result<Option<User>, ServerFnError> {
let auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
let user = auth_session.user.map(|mut user| {
user.password = None;
user
});
Ok(user)
}
/// Check if a user is an admin
/// Returns a Result with a boolean indicating if the user is logged in and an admin
#[server(endpoint = "check_admin")]

View File

@ -6,3 +6,5 @@ pub mod dashboard_tile;
pub mod dashboard_row;
pub mod upload;
pub mod song_list;
pub mod loading;
pub mod error;

45
src/components/error.rs Normal file
View File

@ -0,0 +1,45 @@
use leptos::*;
use leptos_icons::*;
use std::fmt::Display;
#[component]
pub fn ServerError<E: Display + 'static>(
#[prop(optional, into, default="An Error Occurred".into())]
title: TextProp,
#[prop(optional, into)]
message: TextProp,
#[prop(optional, into)]
error: Option<ServerFnError<E>>,
) -> impl IntoView {
view!{
<div class="error-container">
<div class="error-header">
<Icon icon=icondata::BiErrorSolid />
<h1>{title}</h1>
</div>
<p>{message}</p>
<p>{error.map(|error| format!("{}", error))}</p>
</div>
}
}
#[component]
pub fn Error<E: Display + 'static>(
#[prop(optional, into, default="An Error Occurred".into())]
title: TextProp,
#[prop(optional, into)]
message: TextProp,
#[prop(optional, into)]
error: Option<E>,
) -> impl IntoView {
view! {
<div class="error-container">
<div class="error-header">
<Icon icon=icondata::BiErrorSolid />
<h1>{title}</h1>
</div>
<p>{message}</p>
<p>{error.map(|error| format!("{}", error))}</p>
</div>
}
}

19
src/components/loading.rs Normal file
View File

@ -0,0 +1,19 @@
use leptos::*;
/// A loading indicator
#[component]
pub fn Loading() -> impl IntoView {
view! {
<div class="loading"></div>
}
}
/// A full page, centered loading indicator
#[component]
pub fn LoadingPage() -> impl IntoView {
view!{
<div class="loading-page">
<Loading />
</div>
}
}

View File

@ -18,8 +18,10 @@ pub fn SongList(songs: MaybeSignal<Vec<SongData>>) -> impl IntoView {
let playing = first_song.into();
first_song = false;
let extra = Option::<()>::None;
view! {
<SongListItem song={song.clone()} song_playing=playing />
<SongListItem song={song.clone()} song_playing=playing extra />
}
}).collect::<Vec<_>>()
})
@ -29,7 +31,33 @@ pub fn SongList(songs: MaybeSignal<Vec<SongData>>) -> impl IntoView {
}
#[component]
pub fn SongListItem(song: SongData, song_playing: MaybeSignal<bool>) -> impl IntoView {
pub fn SongListExtra<T>(songs: MaybeSignal<Vec<(SongData, T)>>) -> impl IntoView where
T: Clone + IntoView + 'static
{
view! {
<table class="song-list">
{
songs.with(|songs| {
let mut first_song = true;
songs.iter().map(|(song, extra)| {
let playing = first_song.into();
first_song = false;
view! {
<SongListItem song={song.clone()} song_playing=playing extra=Some(extra.clone()) />
}
}).collect::<Vec<_>>()
})
}
</table>
}
}
#[component]
pub fn SongListItem<T>(song: SongData, song_playing: MaybeSignal<bool>, extra: Option<T>) -> impl IntoView where
T: IntoView + 'static
{
let liked = create_rw_signal(song.like_dislike.map(|(liked, _)| liked).unwrap_or(false));
let disliked = create_rw_signal(song.like_dislike.map(|(_, disliked)| disliked).unwrap_or(false));
@ -44,6 +72,10 @@ pub fn SongListItem(song: SongData, song_playing: MaybeSignal<bool>) -> impl Int
<td class="song-list-spacer-big"></td>
<td class="song-like-dislike"><SongLikeDislike liked disliked/></td>
<td>{format!("{}:{:02}", song.duration / 60, song.duration % 60)}</td>
{extra.map(|extra| view! {
<td class="song-list-spacer"></td>
<td>{extra}</td>
})}
</tr>
}
}

View File

@ -1,5 +1,4 @@
use std::time::SystemTime;
use time::Date;
use chrono::{NaiveDate, NaiveDateTime};
use serde::{Deserialize, Serialize};
use cfg_if::cfg_if;
@ -39,8 +38,8 @@ pub struct User {
#[cfg_attr(feature = "ssr", diesel(deserialize_as = String))]
pub password: Option<String>,
/// The time the user was created
#[cfg_attr(feature = "ssr", diesel(deserialize_as = SystemTime))]
pub created_at: Option<SystemTime>,
#[cfg_attr(feature = "ssr", diesel(deserialize_as = NaiveDateTime))]
pub created_at: Option<NaiveDateTime>,
/// Whether the user is an admin
pub admin: bool,
}
@ -103,7 +102,7 @@ impl User {
///
#[cfg(feature = "ssr")]
pub fn get_history_songs(self: &Self, limit: Option<i64>, conn: &mut PgPooledConn) ->
Result<Vec<(SystemTime, Song)>, Box<dyn Error>> {
Result<Vec<(NaiveDateTime, Song)>, Box<dyn Error>> {
use crate::schema::songs::dsl::*;
use crate::schema::song_history::dsl::*;
@ -467,7 +466,7 @@ pub struct Album {
/// The album's title
pub title: String,
/// The album's release date
pub release_date: Option<Date>,
pub release_date: Option<NaiveDate>,
/// The path to the album's image file
pub image_path: Option<String>,
}
@ -546,7 +545,7 @@ pub struct Song {
/// The duration of the song in seconds
pub duration: i32,
/// The song's release date
pub release_date: Option<Date>,
pub release_date: Option<NaiveDate>,
/// The path to the song's audio file
pub storage_path: String,
/// The path to the song's image file
@ -622,7 +621,7 @@ pub struct HistoryEntry {
/// The id of the user who listened to the song
pub user_id: i32,
/// The date the song was listened to
pub date: SystemTime,
pub date: NaiveDateTime,
/// The id of the song that was listened to
pub song_id: i32,
}

View File

@ -1,2 +1,3 @@
pub mod login;
pub mod signup;
pub mod signup;
pub mod profile;

View File

@ -3,9 +3,10 @@ use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::users::UserCredentials;
use crate::app::LoggedInUserResource;
#[component]
pub fn Login() -> impl IntoView {
pub fn Login(user: LoggedInUserResource) -> impl IntoView {
let (username_or_email, set_username_or_email) = create_signal("".to_string());
let (password, set_password) = create_signal("".to_string());
@ -32,13 +33,22 @@ pub fn Login() -> impl IntoView {
if let Err(err) = login_result {
// Handle the error here, e.g., log it or display to the user
log!("Error logging in: {:?}", err);
} else if let Ok(true) = login_result {
// Since we're not sure what the state is, manually refetch the user
user.refetch();
} else if let Ok(Some(login_user)) = login_result {
// Manually set the user to the new user, avoiding a refetch
user.set(Some(login_user));
// Redirect to the login page
log!("Logged in Successfully!");
leptos_router::use_navigate()("/", Default::default());
log!("Navigated to home page after login");
} else if let Ok(false) = login_result {
} else if let Ok(None) = login_result {
log!("Invalid username or password");
// User could be already logged in or not, so refetch the user
user.refetch();
}
});
};

316
src/pages/profile.rs Normal file
View File

@ -0,0 +1,316 @@
use leptos::*;
use leptos_router::use_params_map;
use leptos_icons::*;
use server_fn::error::NoCustomError;
use crate::components::dashboard_row::DashboardRow;
use crate::components::dashboard_tile::DashboardTile;
use crate::components::song_list::*;
use crate::components::loading::*;
use crate::components::error::*;
use crate::api::profile::*;
use crate::app::LoggedInUserResource;
use crate::models::User;
use crate::users::get_user_by_id;
/// Duration in seconds backwards from now to aggregate history data for
const HISTORY_SECS: i64 = 60 * 60 * 24 * 30;
const HISTORY_MESSAGE: &str = "Last Month";
/// How many top songs to show
const TOP_SONGS_COUNT: i64 = 10;
/// How many recent songs to show
const RECENT_SONGS_COUNT: i64 = 5;
/// How many recent artists to show
const TOP_ARTISTS_COUNT: i64 = 10;
/// Profile page
/// Shows the current user's profile if no id is specified, or a user's profile if an id is specified in the path
#[component]
pub fn Profile(logged_in_user: LoggedInUserResource) -> impl IntoView {
let params = use_params_map();
view! {
<div class="profile-container home-component">
{move || params.with(|params| {
match params.get("id").map(|id| id.parse::<i32>()) {
None => {
// No id specified, show the current user's profile
view! { <OwnProfile logged_in_user /> }.into_view()
},
Some(Ok(id)) => {
// Id specified, get the user and show their profile
view! { <UserIdProfile id /> }.into_view()
},
Some(Err(e)) => {
// Invalid id, return an error
view! {
<Error<String>
title="Invalid User ID"
error=e.to_string()
/>
}.into_view()
}
}
})}
</div>
}
}
/// Show the logged in user's profile
#[component]
fn OwnProfile(logged_in_user: LoggedInUserResource) -> impl IntoView {
view! {
<Transition
fallback=move || view! { <LoadingPage /> }
>
{move || logged_in_user.get().map(|user| {
match user {
Some(user) => {
let user_id = user.id.unwrap();
view! {
<UserProfile user />
<TopSongs user_id={user_id} />
<RecentSongs user_id={user_id} />
<TopArtists user_id={user_id} />
}.into_view()
},
None => view! {
<Error<String>
title="Not Logged In"
message="You must be logged in to view your profile"
/>
}.into_view(),
}
})}
</Transition>
}
}
/// Show a user's profile by ID
#[component]
fn UserIdProfile(#[prop(into)] id: MaybeSignal<i32>) -> impl IntoView {
let user_info = create_resource(move || id.get(), move |id| {
get_user_by_id(id)
});
// Show the details if the user is found
let show_details = create_rw_signal(false);
view!{
<Transition
fallback=move || view! { <LoadingPage /> }
>
{move || user_info.get().map(|user| {
match user {
Ok(Some(user)) => {
show_details.set(true);
view! { <UserProfile user /> }.into_view()
},
Ok(None) => {
show_details.set(false);
view! {
<Error<String>
title="User Not Found"
message=format!("User with ID {} not found", id.get())
/>
}.into_view()
},
Err(error) => {
show_details.set(false);
view! {
<ServerError<NoCustomError>
title="Error Getting User"
error
/>
}.into_view()
}
}
})}
</Transition>
<div hidden={move || !show_details.get()}>
<TopSongs user_id={id} />
<RecentSongs user_id={id} />
<TopArtists user_id={id} />
</div>
}
}
/// Show a profile for a User object
#[component]
fn UserProfile(user: User) -> impl IntoView {
let user_id = user.id.unwrap();
let profile_image_path = format!("/assets/images/profile/{}.webp", user_id);
view! {
<div class="profile-header">
<object class="profile-image" data={profile_image_path.clone()} type="image/webp">
<Icon class="profile-image" icon=icondata::CgProfile width="75" height="75"/>
</object>
<h1>{user.username}</h1>
</div>
<div class="profile-details">
<p>
{user.email}
{
user.created_at.map(|created_at| {
format!(" • Joined {}", created_at.format("%B %Y"))
})
}
{
if user.admin {
" • Admin"
} else {
""
}
}
</p>
</div>
}
}
/// Show a list of top songs for a user
#[component]
fn TopSongs(#[prop(into)] user_id: MaybeSignal<i32>) -> impl IntoView {
let top_songs = create_resource(move || user_id.get(), |user_id| async move {
use chrono::{Local, Duration};
let now = Local::now();
let start = now - Duration::seconds(HISTORY_SECS);
let top_songs = top_songs(user_id, start.naive_utc(), now.naive_utc(), Some(TOP_SONGS_COUNT)).await;
top_songs.map(|top_songs| {
top_songs.into_iter().map(|(plays, song)| {
let plays = if plays == 1 {
format!("{} Play", plays)
} else {
format!("{} Plays", plays)
};
(song, plays)
}).collect::<Vec<_>>()
})
});
view! {
<h2>{format!("Top Songs {}", HISTORY_MESSAGE)}</h2>
<Transition
fallback=move || view! { <Loading /> }
>
<ErrorBoundary
fallback=|errors| view! {
{move || errors.get()
.into_iter()
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
.collect_view()
}
}
>
{move ||
top_songs.get().map(|top_songs| {
top_songs.map(|top_songs| {
view! {
<SongListExtra songs={top_songs.into()} />
}
})
})
}
</ErrorBoundary>
</Transition>
}
}
/// Show a list of recently played songs for a user
#[component]
fn RecentSongs(#[prop(into)] user_id: MaybeSignal<i32>) -> impl IntoView {
let recent_songs = create_resource(move || user_id.get(), |user_id| async move {
let recent_songs = recent_songs(user_id, Some(RECENT_SONGS_COUNT)).await;
recent_songs.map(|recent_songs| {
recent_songs.into_iter().map(|(_date, song)| {
song
}).collect::<Vec<_>>()
})
});
view! {
<h2>"Recently Played"</h2>
<Transition
fallback=move || view! { <Loading /> }
>
<ErrorBoundary
fallback=|errors| view! {
{move || errors.get()
.into_iter()
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
.collect_view()
}
}
>
{move ||
recent_songs.get().map(|recent_songs| {
recent_songs.map(|recent_songs| {
view! {
<SongList songs={recent_songs.into()} />
}
})
})
}
</ErrorBoundary>
</Transition>
}
}
/// Show a list of top artists for a user
#[component]
fn TopArtists(#[prop(into)] user_id: MaybeSignal<i32>) -> impl IntoView {
let top_artists = create_resource(move || user_id.get(), |user_id| async move {
use chrono::{Local, Duration};
let now = Local::now();
let start = now - Duration::seconds(HISTORY_SECS);
let top_artists = top_artists(user_id, start.naive_utc(), now.naive_utc(), Some(TOP_ARTISTS_COUNT)).await;
top_artists.map(|top_artists| {
top_artists.into_iter().map(|(_plays, artist)| {
artist
}).collect::<Vec<_>>()
})
});
view! {
<Transition
fallback=move || view! {
<h2>{format!("Top Artists {}", HISTORY_MESSAGE)}</h2>
<Loading />
}
>
<ErrorBoundary
fallback=|errors| view! {
<h2>{format!("Top Artists {}", HISTORY_MESSAGE)}</h2>
{move || errors.get()
.into_iter()
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
.collect_view()
}
}
>
{move ||
top_artists.get().map(|top_artists| {
top_artists.map(|top_artists| {
let tiles = top_artists.into_iter().map(|artist| {
Box::new(artist) as Box<dyn DashboardTile>
}).collect::<Vec<_>>();
DashboardRow::new(format!("Top Artists {}", HISTORY_MESSAGE), tiles)
})
})
}
</ErrorBoundary>
</Transition>
}
}

View File

@ -3,9 +3,10 @@ use crate::models::User;
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::app::LoggedInUserResource;
#[component]
pub fn Signup() -> impl IntoView {
pub fn Signup(user: LoggedInUserResource) -> impl IntoView {
let (username, set_username) = create_signal("".to_string());
let (email, set_email) = create_signal("".to_string());
let (password, set_password) = create_signal("".to_string());
@ -19,7 +20,7 @@ pub fn Signup() -> impl IntoView {
let on_submit = move |ev: leptos::ev::SubmitEvent| {
ev.prevent_default();
let new_user = User {
let mut new_user = User {
id: None,
username: username.get(),
email: email.get(),
@ -30,10 +31,17 @@ pub fn Signup() -> impl IntoView {
log!("new user: {:?}", new_user);
spawn_local(async move {
if let Err(err) = signup(new_user).await {
if let Err(err) = signup(new_user.clone()).await {
// Handle the error here, e.g., log it or display to the user
log!("Error signing up: {:?}", err);
// Since we're not sure what the state is, manually refetch the user
user.refetch();
} else {
// Manually set the user to the new user, avoiding a refetch
new_user.password = None;
user.set(Some(new_user));
// Redirect to the login page
log!("Signed up successfully!");
leptos_router::use_navigate()("/", Default::default());

View File

@ -1,12 +1,13 @@
use crate::models::{Album, Artist, Song};
use crate::components::dashboard_tile::DashboardTile;
use time::Date;
use serde::{Serialize, Deserialize};
use chrono::NaiveDate;
/// Holds information about a song
///
/// Intended to be used in the front-end, as it includes artist and album objects, rather than just their ids.
#[derive(Clone)]
#[derive(Serialize, Deserialize, Clone)]
pub struct SongData {
/// Song id
pub id: i32,
@ -21,7 +22,7 @@ pub struct SongData {
/// The duration of the song in seconds
pub duration: i32,
/// The song's release date
pub release_date: Option<Date>,
pub release_date: Option<NaiveDate>,
/// Path to song file, relative to the root of the web server.
/// For example, `"/assets/audio/Song.mp3"`
pub song_path: String,

View File

@ -10,7 +10,7 @@ cfg_if! {
use diesel::prelude::*;
use log::*;
use server_fn::error::NoCustomError;
use time::Date;
use chrono::NaiveDate;
}
}
@ -124,15 +124,14 @@ async fn validate_track_number(track_number: Field<'static>) -> Result<Option<i3
/// Validate the release date in a multipart field
/// Expects a field with a release date, and ensures it is a valid date in the format [year]-[month]-[day]
#[cfg(feature = "ssr")]
async fn validate_release_date(release_date: Field<'static>) -> Result<Option<Date>, ServerFnError> {
async fn validate_release_date(release_date: Field<'static>) -> Result<Option<NaiveDate>, ServerFnError> {
match release_date.text().await {
Ok(release_date) => {
if release_date.trim().is_empty() {
return Ok(None);
}
let date_format = time::macros::format_description!("[year]-[month]-[day]");
let release_date = Date::parse(&release_date.trim(), date_format);
let release_date = NaiveDate::parse_from_str(&release_date.trim(), "%Y-%m-%d");
match release_date {
Ok(release_date) => Ok(Some(release_date)),
@ -181,8 +180,7 @@ pub async fn upload(data: MultipartData) -> Result<(), ServerFnError> {
ServerError("Title field required and must precede file field".to_string()))?;
let clean_title = title.replace(" ", "_").replace("/", "_");
let date_format = time::macros::format_description!("[year]-[month]-[day]_[hour]:[minute]:[second]");
let date_str = time::OffsetDateTime::now_utc().format(date_format).unwrap_or_default();
let date_str = chrono::Utc::now().format("%Y-%m-%d_%H:%M:%S").to_string();
let upload_path = format!("assets/audio/upload-{}_{}.mp3", date_str, clean_title);
file_name = Some(format!("upload-{}_{}.mp3", date_str, clean_title));

View File

@ -128,3 +128,15 @@ pub async fn get_user(username_or_email: String) -> Result<Option<User>, ServerF
Ok(user)
}
#[server(endpoint = "get_user_by_id")]
pub async fn get_user_by_id(user_id: i32) -> Result<Option<User>, ServerFnError> {
let mut user = find_user_by_id(user_id).await?;
// Remove the password hash before returning the user
if let Some(user) = user.as_mut() {
user.password = None;
}
Ok(user)
}

View File

@ -1,7 +1,6 @@
@import "theme.scss";
.dashboard-container {
width: calc(100% - 22rem - 16rem);
.dashboard-header {
font-size: 1.2rem;
font-weight: 300;

18
style/error.scss Normal file
View File

@ -0,0 +1,18 @@
.error-container {
.error-header {
display: inline-grid;
svg {
width: 30px;
height: 30px;
grid-row-start: 1;
align-self: center;
padding-right: 10px;
}
h1 {
grid-row-start: 1;
align-self: center;
}
}
}

View File

@ -9,8 +9,9 @@
}
.home-component {
background: #1c1c1c;
height: 100vh;
width: calc(100% - 22rem - 16rem);
margin: 2px;
padding: 0.2rem 1.5rem 1.5rem 1rem;
padding: 0.2rem 1.5rem $playbar-size 1rem;
border-radius: 0.5rem;
overflow: scroll;
}

59
style/loading.scss Normal file
View File

@ -0,0 +1,59 @@
@import "theme.scss";
.loading-page {
display: flex;
justify-content: center;
align-items: center;
height: 100%;
}
.loading {
position: relative;
width: 10px;
height: 10px;
border-radius: 5px;
margin: 10px;
background-color: $accent-color;
color: $accent-color;
animation: dot-flashing 1s infinite linear alternate;
animation-delay: 0.5s;
}
.loading::before, .loading::after {
content: "";
display: inline-block;
position: absolute;
top: 0;
}
.loading::before {
left: -15px;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: $accent-color;
color: $accent-color;
animation: dot-flashing 1s infinite alternate;
animation-delay: 0s;
}
.loading::after {
left: 15px;
width: 10px;
height: 10px;
border-radius: 5px;
background-color: $accent-color;
color: $accent-color;
animation: dot-flashing 1s infinite alternate;
animation-delay: 1s;
}
@keyframes dot-flashing {
0% {
background-color: $accent-color;
}
50%, 100% {
background-color: $controls-hover-color;
}
}

View File

@ -11,7 +11,10 @@
@import 'dashboard_tile.scss';
@import 'dashboard_row.scss';
@import 'upload.scss';
@import 'error.scss';
@import 'song_list.scss';
@import 'profile.scss';
@import 'loading.scss';
body {
font-family: sans-serif;

View File

@ -3,7 +3,6 @@
.personal-container {
width: 16rem;
background: #1c1c1c;
height: 100vh;
margin: 2px;
border-radius: 0.5rem;

View File

@ -2,7 +2,7 @@
.playbar {
width: 100%;
height: 75px;
height: $playbar-size;
background-color: $play-bar-background-color;
opacity: 0.9;
position: fixed;

36
style/profile.scss Normal file
View File

@ -0,0 +1,36 @@
@import 'theme.scss';
.profile-container {
.profile-header {
display: flex;
.profile-image {
width: 75px;
height: 75px;
border-radius: 50%;
padding: 10px;
padding-bottom: 5px;
margin-top: auto;
margin-bottom: auto;
svg {
padding: 0;
margin: 0;
}
}
h1 {
font-size: 40px;
align-self: center;
padding: 10px;
padding-bottom: 5px;
}
}
.profile-details {
p {
font-size: 1rem;
margin: 0.5rem;
}
}
}

View File

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

View File

@ -16,3 +16,4 @@ $auth-inputs: #796dd4;
$auth-containers: white;
$dashboard-tile-size: 200px;
$playbar-size: 75px;