Compare commits

..

8 Commits

63 changed files with 1655 additions and 3586 deletions

View File

@ -8,4 +8,3 @@
!/style !/style
!/Cargo.lock !/Cargo.lock
!/Cargo.toml !/Cargo.toml
!/ascii_art.txt

View File

@ -1,17 +0,0 @@
# Example environment variable file
# Copy this to .env or manually set the environment variables
# Redis URL -- Used for storing session data
REDIS_URL=redis://localhost:6379
# PostgreSQL URL -- Used for storing data
# Option 1: Specify the URL directly
DATABASE_URL=postgresql://libretunes:password@localhost:5432/libretunes
# Option 2: Specify the individual components
# Must specify at least POSTGRES_HOST
# POSTGRES_USER=libretunes
# POSTGRES_PASSWORD=password
# POSTGRES_HOST=localhost
# POSTGRES_PORT=5432
# POSTGRES_DB=libretunes

View File

@ -2,25 +2,17 @@
build: build:
needs: [] needs: []
image: $CI_REGISTRY/libretunes/ops/docker-leptos:latest image: $CI_REGISTRY/libretunes/ops/docker-leptos:latest
variables:
RUSTFLAGS: "-D warnings"
script: script:
- cargo-leptos build - cargo-leptos build
.docker:
image: docker:latest
services:
- docker:dind
tags:
- docker
before_script:
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
# Build the docker image and push it to the registry # Build the docker image and push it to the registry
docker-build: docker-build:
needs: ["build"] needs: ["build"]
extends: .docker image: docker:latest
script: script:
- /usr/local/bin/dockerd-entrypoint.sh &
- while ! docker info; do echo "Waiting for Docker to become available..."; sleep 1; done
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA . - docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
# If running on the default branch, tag as latest # If running on the default branch, tag as latest
- if [ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]; then docker tag - if [ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]; then docker tag
@ -52,50 +44,35 @@ cargo-doc:
paths: paths:
- target/doc - target/doc
.argocd:
image: argoproj/argocd:v2.6.15
before_script:
- argocd login ${ARGOCD_SERVER} --username ${ARGOCD_USERNAME} --password ${ARGOCD_PASSWORD} --grpc-web
# Start the review environment # Start the review environment
start-review: start-review:
extends: .docker extends: .argocd
rules: rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual when: manual
script: script:
- apk add curl openssl - argocd app sync argocd/libretunes-review-${CI_COMMIT_SHORT_SHA}
- cd cicd - argocd app wait argocd/libretunes-review-${CI_COMMIT_SHORT_SHA}
- echo "$CLOUDFLARE_TUNNEL_AUTH_JSON" > tunnel-auth.json
- ./add-dns.sh $CLOUDFLARE_ZONE_ID review-$CI_COMMIT_SHORT_SHA libretunes-auto-review $CLOUDFLARE_API_TOKEN $CLOUDFLARE_TUNNEL_ID
- ./create-tunnel-config.sh http://libretunes:3000 review-$CI_COMMIT_SHORT_SHA.libretunes.xyz $CLOUDFLARE_TUNNEL_ID
- export COMPOSE_PROJECT_NAME=review-$CI_COMMIT_SHORT_SHA
- export POSTGRES_PASSWORD=$(openssl rand -hex 16)
- export LIBRETUNES_VERSION=$CI_COMMIT_SHORT_SHA
- docker compose --file docker-compose-cicd.yml pull
- docker compose --file docker-compose-cicd.yml create
- export CONFIG_VOL_NAME=review-${CI_COMMIT_SHORT_SHA}_cloudflared-config
- export TMP_CONTAINER_NAME=$(docker run --rm -d -v $CONFIG_VOL_NAME:/data busybox sh -c "sleep infinity")
- docker cp tunnel-auth.json $TMP_CONTAINER_NAME:/data/auth.json
- docker cp cloudflared-tunnel-config.yml $TMP_CONTAINER_NAME:/data/config.yml
- docker stop $TMP_CONTAINER_NAME
- docker compose --file docker-compose-cicd.yml up -d
environment: environment:
name: review/$CI_COMMIT_SHORT_SHA name: review/$CI_COMMIT_SHORT_SHA
url: https://review-$CI_COMMIT_SHORT_SHA.libretunes.xyz url: https://review-$CI_COMMIT_SHORT_SHA.libretunes.mregirouard.com
on_stop: stop-review on_stop: stop-review
auto_stop_in: 1 week
# Stop the review environment # Stop the review environment
stop-review: stop-review:
needs: ["start-review"] needs: ["start-review"]
extends: .docker extends: .argocd
rules: rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event" - if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual when: manual
allow_failure: true allow_failure: true
script: script:
- apk add jq curl - argocd app delete argocd/libretunes-review-${CI_COMMIT_SHORT_SHA} --cascade
- ./cicd/remove-dns.sh $CLOUDFLARE_ZONE_ID review-$CI_COMMIT_SHORT_SHA.libretunes.xyz libretunes-auto-review $CLOUDFLARE_API_TOKEN
- export COMPOSE_PROJECT_NAME=review-$CI_COMMIT_SHORT_SHA
- export LIBRETUNES_VERSION=$CI_COMMIT_SHORT_SHA
- docker compose --file cicd/docker-compose-cicd.yml down
- docker compose --file cicd/docker-compose-cicd.yml rm -f -v
environment: environment:
name: review/$CI_COMMIT_SHORT_SHA name: review/$CI_COMMIT_SHORT_SHA
action: stop action: stop

2247
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -8,52 +8,47 @@ build = "src/build.rs"
crate-type = ["cdylib", "rlib"] crate-type = ["cdylib", "rlib"]
[dependencies] [dependencies]
console_error_panic_hook = { version = "0.1", optional = true } actix-files = { version = "0.6", optional = true }
actix-web = { version = "4", optional = true, features = ["macros"] }
console_error_panic_hook = "0.1"
cfg-if = "1" cfg-if = "1"
http = { version = "1.0", default-features = false } http = { version = "0.2", optional = true }
leptos = { version = "0.6", default-features = false, 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 = { version = "=0.2.92", default-features = false, optional = true } wasm-bindgen = "=0.2.89"
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",
"BsThreeDotsVertical",
] }
dotenv = { version = "0.15.0", optional = true } 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", "time"], optional = true }
lazy_static = { version = "1.4.0", optional = true } lazy_static = { version = "1.4.0", optional = true }
serde = { version = "1.0.195", features = ["derive"], default-features = false } 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"], default-features = false } 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 }
tokio = { version = "1", optional = true, features = ["rt-multi-thread"] } futures = { version = "0.3.30", default-features = false, optional = true }
axum = { version = "0.7.5", features = ["tokio", "http1"], default-features = false, optional = true }
tower = { version = "0.4.13", optional = true }
tower-http = { version = "0.5", optional = true, features = ["fs"] }
thiserror = "1.0.57"
tower-sessions-redis-store = { version = "0.11", optional = true }
async-trait = { version = "0.1.79", optional = true }
axum-login = { version = "0.14.0", optional = true }
server_fn = { version = "0.6.11", features = ["multipart"] }
symphonia = { version = "0.5.4", default-features = false, features = ["mp3"], optional = true }
multer = { version = "3.0.0", optional = true }
log = { version = "0.4.21", optional = true }
flexi_logger = { version = "0.28.0", optional = true, default-features = false }
web-sys = "0.3.69"
[patch.crates-io]
gloo-net = { git = "https://github.com/rustwasm/gloo.git", rev = "a823fab7ecc4068e9a28bd669da5eaf3f0a56380" }
[features] [features]
hydrate = [ csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
"leptos/hydrate", hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
"leptos_meta/hydrate",
"leptos_router/hydrate",
"console_error_panic_hook",
"wasm-bindgen",
]
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",
@ -62,18 +57,10 @@ ssr = [
"lazy_static", "lazy_static",
"openssl", "openssl",
"diesel_migrations", "diesel_migrations",
"actix-identity",
"actix-session",
"pbkdf2", "pbkdf2",
"tokio", "futures",
"axum",
"tower",
"tower-http",
"tower-sessions-redis-store",
"async-trait",
"axum-login",
"symphonia",
"multer",
"log",
"flexi_logger",
] ]
# 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

@ -32,7 +32,6 @@ COPY style /app/style
# Minify CSS # Minify CSS
RUN npx tailwindcss -i /app/style/main.scss -o /app/style/main.scss --minify RUN npx tailwindcss -i /app/style/main.scss -o /app/style/main.scss --minify
COPY ascii_art.txt /app/ascii_art.txt
COPY assets /app/assets COPY assets /app/assets
COPY src /app/src COPY src /app/src
COPY migrations /app/migrations COPY migrations /app/migrations

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2023-2024 The LibreTunes Authors Copyright (c) 2022 henrik
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

View File

@ -1,10 +0,0 @@
.-=. =+==-.
.=++++. =+++++=.
_ _ _ _______ =++++++= :*++++++=
| | (_) | |__ __| -++++**+. -+**++++-
| | _| |__ _ __ ___| |_ _ _ __ ___ ___ *+++**+ +**+++*
| | | | '_ \| '__/ _ \ | | | | '_ \ / _ \/ __| *+++**+ +**+++*
| |____| | |_) | | | __/ | |_| | | | | __/\__ \ -++++**+-: +**++++-
|______|_|_.__/|_| \___|_|\__,_|_| |_|\___||___/ =++++++**+ -+++++=
.=+++++++=.+++=.
.-==++++---.

View File

@ -1,22 +0,0 @@
#!/bin/sh
set -e
ZONE_ID=$1
RECORD_NAME=$2
RECORD_COMMENT=$3
API_TOKEN=$4
TUNNEL_ID=$5
curl --request POST --silent \
--url https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records \
--header 'Content-Type: application/json' \
--header "Authorization: Bearer $API_TOKEN" \
--data '{
"content": "'$TUNNEL_ID'.cfargotunnel.com",
"name": "'$RECORD_NAME'",
"comment": "'$RECORD_COMMENT'",
"proxied": true,
"type": "CNAME",
"ttl": 1
}' \

View File

@ -1,19 +0,0 @@
#!/bin/sh
set -e
SERVICE=$1
HOSTNAME=$2
TUNNEL_ID=$3
echo "Creating tunnel config for $HOSTNAME"
cat <<EOF > cloudflared-tunnel-config.yml
tunnel: $TUNNEL_ID
credentials-file: /etc/cloudflared/auth.json
ingress:
- hostname: $HOSTNAME
service: $SERVICE
- service: http_status:404
EOF

View File

@ -1,55 +0,0 @@
version: '3'
services:
cloudflare:
image: cloudflare/cloudflared:latest
command: tunnel run
volumes:
- cloudflared-config:/etc/cloudflared:ro
libretunes:
image: registry.mregirouard.com/libretunes/libretunes:${LIBRETUNES_VERSION}
environment:
REDIS_URL: redis://redis:6379
POSTGRES_HOST: postgres
POSTGRES_USER: libretunes
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: libretunes
volumes:
- libretunes-audio:/site/audio
depends_on:
- redis
- postgres
restart: always
redis:
image: redis:latest
volumes:
- libretunes-redis:/data
restart: always
healthcheck:
test: ["CMD-SHELL", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
postgres:
image: postgres:latest
environment:
POSTGRES_USER: libretunes
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: libretunes
volumes:
- libretunes-postgres:/var/lib/postgresql/data
restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U libretunes"]
interval: 10s
timeout: 5s
retries: 5
volumes:
cloudflared-config:
libretunes-audio:
libretunes-redis:
libretunes-postgres:

View File

@ -1,22 +0,0 @@
#!/bin/sh
set -e
ZONE_ID=$1
RECORD_NAME=$2
RECORD_COMMENT=$3
API_TOKEN=$4
RECORD_ID=$(
curl --request GET --silent \
--url "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records?name=$RECORD_NAME&comment=$RECORD_COMMENT" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $API_TOKEN" \
| jq -r '.result[0].id')
echo "Deleting DNS record ID $RECORD_ID"
curl --request DELETE --silent \
--url "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records/$RECORD_ID" \
--header "Content-Type: application/json" \
--header "Authorization: Bearer $API_TOKEN"

View File

@ -1 +0,0 @@
ALTER TABLE albums DROP COLUMN image_path;

View File

@ -1 +0,0 @@
ALTER TABLE albums ADD COLUMN image_path VARCHAR;

View File

@ -1 +0,0 @@
ALTER TABLE users DROP COLUMN admin;

View File

@ -1 +0,0 @@
ALTER TABLE users ADD COLUMN admin BOOLEAN DEFAULT FALSE NOT NULL;

View File

@ -1,66 +0,0 @@
use leptos::*;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::database::get_db_conn;
use diesel::prelude::*;
use time::Date;
}
}
/// Add an album to the database
///
/// # Arguments
///
/// * `album_title` - The name of the artist to add
/// * `release_data` - The release date of the album (Optional)
/// * `image_path` - The path to the album's image file (Optional)
///
/// # Returns
/// * `Result<(), Box<dyn Error>>` - A empty result if successful, or an error
///
#[server(endpoint = "albums/add-album")]
pub async fn add_album(album_title: String, release_date: Option<String>, image_path: Option<String>) -> Result<(), ServerFnError> {
use crate::schema::albums::{self};
use crate::models::Album;
use leptos::server_fn::error::NoCustomError;
let date_format = time::macros::format_description!("[year]-[month]-[day]");
let parsed_release_date = match release_date {
Some(date) => {
match Date::parse(&date, &date_format) {
Ok(parsed_date) => Some(parsed_date),
Err(_e) => return Err(ServerFnError::<NoCustomError>::ServerError("Invalid release date".to_string()))
}
},
None => None
};
let image_path_arg = match image_path {
Some(image_path) => {
if image_path.is_empty() {
None
} else {
Some(image_path)
}
},
None => None
};
let new_album = Album {
id: None,
title: album_title,
release_date: parsed_release_date,
image_path: image_path_arg
};
let db = &mut get_db_conn();
diesel::insert_into(albums::table)
.values(&new_album)
.execute(db)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error adding album: {}", e)))?;
Ok(())
}

View File

@ -1,39 +0,0 @@
use leptos::*;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::database::get_db_conn;
use diesel::prelude::*;
}
}
/// Add an artist to the database
///
/// # Arguments
///
/// * `artist_name` - The name of the artist to add
///
/// # Returns
/// * `Result<(), Box<dyn Error>>` - A empty result if successful, or an error
///
#[server(endpoint = "artists/add-artist")]
pub async fn add_artist(artist_name: String) -> Result<(), ServerFnError> {
use crate::schema::artists::dsl::*;
use crate::models::Artist;
use leptos::server_fn::error::NoCustomError;
let new_artist = Artist {
id: None,
name: artist_name,
};
let db = &mut get_db_conn();
diesel::insert_into(artists)
.values(&new_artist)
.execute(db)
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error adding artist: {}", e)))?;
Ok(())
}

View File

@ -1,2 +0,0 @@
pub mod artists;
pub mod albums;

View File

@ -1,25 +1,18 @@
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 crate::searchbar::SearchBar;
use leptos::*; use leptos::*;
use leptos_meta::*; use leptos_meta::*;
use leptos_router::*; use leptos_router::*;
use crate::pages::login::*; use crate::pages::login::*;
use crate::pages::signup::*; use crate::pages::signup::*;
use crate::error_template::{AppError, ErrorTemplate};
#[component] #[component]
pub fn App() -> impl IntoView { pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc. // Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context(); provide_meta_context();
let play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status);
let upload_open = create_rw_signal(false);
let add_artist_open = create_rw_signal(false);
let add_album_open = create_rw_signal(false);
view! { view! {
// injects a stylesheet into the document <head> // injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet // id=leptos means cargo-leptos will hot-reload this stylesheet
@ -29,27 +22,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=move || <Route path="" view=HomePage/>
view! { <HomePage play_status=play_status <Route path="/*any" view=NotFound/>
upload_open=upload_open
add_artist_open=add_artist_open
add_album_open=add_album_open
/>
}>
<Route path="" view=Dashboard />
<Route path="dashboard" view=Dashboard />
<Route path="search" view=Search />
</Route>
<Route path="/login" view=Login /> <Route path="/login" view=Login />
<Route path="/signup" view=Signup /> <Route path="/signup" view=Signup />
</Routes> </Routes>
@ -58,28 +35,17 @@ pub fn App() -> impl IntoView {
} }
} }
use crate::components::sidebar::*;
use crate::components::dashboard::*;
use crate::components::search::*;
use crate::components::personal::*;
use crate::components::upload::*;
use crate::components::add_artist::AddArtist;
use crate::components::add_album::AddAlbum;
/// Renders the home page of your application. /// Renders the home page of your application.
#[component] #[component]
fn HomePage(play_status: RwSignal<PlayStatus>, upload_open: RwSignal<bool>, add_artist_open: RwSignal<bool>, add_album_open: RwSignal<bool>) -> impl IntoView { fn HomePage() -> impl IntoView {
let mut play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status);
view! { view! {
<div class="home-container"> <div class="home">
<Upload open=upload_open/>
<AddArtist open=add_artist_open/>
<AddAlbum open=add_album_open/>
<Sidebar upload_open=upload_open add_artist_open=add_artist_open add_album_open=add_album_open/>
// This <Outlet /> will render the child route components
<Outlet />
<Personal />
<PlayBar status=play_status/> <PlayBar status=play_status/>
<Queue status=play_status/> <Queue status=play_status/>
<SearchBar status=play_status/>
</div> </div>
} }
} }
@ -97,8 +63,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,137 +8,64 @@ 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;
// Ensure the user has no id, and is not a self-proclaimed admin use leptos_actix::extract;
use actix_web::{HttpMessage, HttpRequest};
use actix_identity::Identity;
// Ensure the user has no id
let new_user = User { let new_user = User {
id: None, id: None,
admin: false,
..new_user ..new_user
}; };
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();
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")))
} }
}) }).await?;
}
/// 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")]
pub async fn check_admin() -> 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.as_ref().map(|u| u.admin).unwrap_or(false))
}
/// Require that a user is logged in and an admin
/// Returns a Result with the error message if the user is not logged in or is not an admin
/// Intended to be used at the start of a protected route, to ensure the user is logged in and an admin:
/// ```rust
/// use leptos::*;
/// use libretunes::auth::require_admin;
/// #[server(endpoint = "protected_admin_route")]
/// pub async fn protected_admin_route() -> Result<(), ServerFnError> {
/// require_admin().await?;
/// // Continue with protected route
/// Ok(())
/// }
/// ```
#[cfg(feature = "ssr")]
pub async fn require_admin() -> Result<(), ServerFnError> {
check_admin().await.and_then(|is_admin| {
if is_admin {
Ok(()) Ok(())
} else {
Err(ServerFnError::<NoCustomError>::ServerError(format!("Unauthorized")))
}
})
} }

View File

@ -1,48 +0,0 @@
use axum_login::{AuthnBackend, AuthUser, UserId};
use crate::users::UserCredentials;
use leptos::server_fn::error::ServerFnErrorErr;
use crate::models::User;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use async_trait::async_trait;
}
}
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,8 +0,0 @@
pub mod sidebar;
pub mod dashboard;
pub mod search;
pub mod personal;
pub mod upload;
pub mod upload_dropdown;
pub mod add_artist;
pub mod add_album;

View File

@ -1,92 +0,0 @@
use leptos::*;
use leptos::leptos_dom::log;
use leptos_icons::*;
use crate::api::albums::add_album;
#[component]
pub fn AddAlbumBtn(add_album_open: RwSignal<bool>) -> impl IntoView {
let open_dialog = move |_| {
add_album_open.set(true);
};
view! {
<button class="add-album-btn add-btns" on:click=open_dialog>
Add Album
</button>
}
}
#[component]
pub fn AddAlbum(open: RwSignal<bool>) -> impl IntoView {
let album_title = create_rw_signal("".to_string());
let release_date = create_rw_signal("".to_string());
let image_path = create_rw_signal("".to_string());
let close_dialog = move |ev: leptos::ev::MouseEvent| {
ev.prevent_default();
open.set(false);
};
let on_add_album = move |ev: leptos::ev::SubmitEvent| {
ev.prevent_default();
let album_title_clone = album_title.get();
let release_date_clone = Some(release_date.get());
let image_path_clone = Some(image_path.get());
spawn_local(async move {
let add_album_result = add_album(album_title_clone, release_date_clone, image_path_clone).await;
if let Err(err) = add_album_result {
log!("Error adding album: {:?}", err);
} else if let Ok(album) = add_album_result {
log!("Added album: {:?}", album);
album_title.set("".to_string());
release_date.set("".to_string());
image_path.set("".to_string());
}
})
};
view! {
<Show when=open fallback=move|| view!{}>
<div class="add-album-container">
<div class="upload-header">
<h1>Add Album</h1>
</div>
<div class="close-button" on:click=close_dialog><Icon icon=icondata::IoClose /></div>
<form class="create-album-form" action="POST" on:submit=on_add_album>
<div class="input-bx">
<input type="text" required class="text-input"
prop:value=album_title
on:input=move |ev: leptos::ev::Event| {
album_title.set(event_target_value(&ev));
}
required
/>
<span>Album Title</span>
</div>
<div class="release-date">
<div class="left">
<span>Release</span>
<span>Date</span>
</div>
<input class="info" type="date"
prop:value=release_date
on:input=move |ev: leptos::ev::Event| {
release_date.set(event_target_value(&ev));
}
/>
</div>
<div class="input-bx">
<input type="text" class="text-input"
prop:value=image_path
on:input=move |ev: leptos::ev::Event| {
image_path.set(event_target_value(&ev));
}
/>
<span>Image Path</span>
</div>
<button type="submit" class="upload-button">Add</button>
</form>
</div>
</Show>
}
}

View File

@ -1,62 +0,0 @@
use leptos::*;
use leptos::leptos_dom::log;
use leptos_icons::*;
use crate::api::artists::add_artist;
#[component]
pub fn AddArtistBtn(add_artist_open: RwSignal<bool>) -> impl IntoView {
let open_dialog = move |_| {
add_artist_open.set(true);
};
view! {
<button class="add-artist-btn add-btns" on:click=open_dialog>
Add Artist
</button>
}
}
#[component]
pub fn AddArtist(open: RwSignal<bool>) -> impl IntoView {
let artist_name = create_rw_signal("".to_string());
let close_dialog = move |ev: leptos::ev::MouseEvent| {
ev.prevent_default();
open.set(false);
};
let on_add_artist = move |ev: leptos::ev::SubmitEvent| {
ev.prevent_default();
let artist_name_clone = artist_name.get();
spawn_local(async move {
let add_artist_result = add_artist(artist_name_clone).await;
if let Err(err) = add_artist_result {
log!("Error adding artist: {:?}", err);
} else if let Ok(artist) = add_artist_result {
log!("Added artist: {:?}", artist);
artist_name.set("".to_string());
}
})
};
view! {
<Show when=open fallback=move|| view!{}>
<div class="add-artist-container">
<div class="upload-header">
<h1>Add Artist</h1>
</div>
<div class="close-button" on:click=close_dialog><Icon icon=icondata::IoClose /></div>
<form class="create-artist-form" action="POST" on:submit=on_add_artist>
<div class="input-bx">
<input type="text" name="title" required class="text-input"
prop:value=artist_name
on:input=move |ev: leptos::ev::Event| {
artist_name.set(event_target_value(&ev));
}
required
/>
<span>Artist Name</span>
</div>
<button type="submit" class="upload-button">Add</button>
</form>
</div>
</Show>
}
}

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,42 +0,0 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
#[component]
pub fn Personal() -> impl IntoView {
view! {
<div class=" personal-container">
<Profile />
</div>
}
}
#[component]
pub fn Profile() -> 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"}}>
<DropDownNotLoggedIn />
</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>
}
}

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,74 +0,0 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::components::upload_dropdown::*;
#[component]
pub fn Sidebar(upload_open: RwSignal<bool>, add_artist_open: RwSignal<bool>, add_album_open: RwSignal<bool>) -> impl IntoView {
use leptos_router::use_location;
let location = use_location();
let dropdown_open = create_rw_signal(false);
let on_dashboard = Signal::derive(
move || location.pathname.get().starts_with("/dashboard") || location.pathname.get() == "/",
);
let on_search = Signal::derive(
move || location.pathname.get().starts_with("/search"),
);
view! {
<div class="sidebar-container">
<div class="sidebar-top-container">
<Show
when=move || {upload_open.get() || add_artist_open.get() || add_album_open.get()}
fallback=move || view! {}
>
<div class="upload-overlay" on:click=move |_| {
upload_open.set(false);
add_artist_open.set(false);
add_album_open.set(false);
}></div>
</Show>
<h2 class="header">LibreTunes</h2>
<div class="upload-dropdown-container">
<UploadDropdownBtn dropdown_open=dropdown_open/>
<Show
when= move || dropdown_open()
fallback=move || view! {}
>
<UploadDropdown dropdown_open=dropdown_open upload_open=upload_open add_artist_open=add_artist_open add_album_open=add_album_open/>
</Show>
</div>
<a class="buttons" href="/dashboard" style={move || if on_dashboard() {"color: #e1e3e1"} else {""}} >
<Icon icon=icondata::OcHomeFillLg />
<h1>Dashboard</h1>
</a>
<a class="buttons" href="/search" style={move || if on_search() {"color: #e1e3e1"} else {""}}>
<Icon icon=icondata::BiSearchRegular />
<h1>Search</h1>
</a>
</div>
<Bottom />
</div>
}
}
#[component]
pub fn Bottom() -> impl IntoView {
view! {
<div class="sidebar-bottom-container">
<div class="heading">
<h1 class="header">Playlists</h1>
<button class="add-playlist">
<div class="add-sign">
<Icon icon=icondata::IoAddSharp />
</div>
New Playlist
</button>
</div>
</div>
}
}

View File

@ -1,242 +0,0 @@
use std::rc::Rc;
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use leptos_router::Form;
use web_sys::Response;
use crate::search::search_artists;
use crate::search::search_albums;
use crate::models::Artist;
use crate::models::Album;
#[component]
pub fn UploadBtn(dialog_open: RwSignal<bool>) -> impl IntoView {
let open_dialog = move |_| {
dialog_open.set(true);
};
view! {
<button class="upload-btn add-btns" on:click=open_dialog>
Upload Song
</button>
}
}
#[component]
pub fn Upload(open: RwSignal<bool>) -> impl IntoView {
// Create signals for the artist input and the filtered artists
let (artists, set_artists) = create_signal("".to_string());
let (filtered_artists, set_filtered_artists) = create_signal(vec![]);
let (albums, set_albums) = create_signal("".to_string());
let (filtered_albums, set_filtered_albums) = create_signal(vec![]);
let (error_msg, set_error_msg) = create_signal::<Option<String>>(None);
let close_dialog = move |ev: leptos::ev::MouseEvent| {
ev.prevent_default();
open.set(false);
};
// Create a filter function to handle filtering artists
// Allow users to search for artists by name, converts the artist name to artist id to be handed off to backend
let handle_filter_artists = move |ev: leptos::ev::Event| {
ev.prevent_default();
let artist_input: String = event_target_value(&ev);
//Get the artist that we are currently searching for
let mut all_artists: Vec<&str> = artist_input.split(",").collect();
let search = all_artists.pop().unwrap().to_string();
//Update the artist signal with the input
set_artists.update(|value: &mut String| *value = artist_input);
spawn_local(async move {
let filter_results = search_artists(search, 3).await;
if let Err(err) = filter_results {
log!("Error filtering artists: {:?}", err);
} else if let Ok(artists) = filter_results {
log!("Filtered artists: {:?}", artists);
set_filtered_artists.update(|value| *value = artists);
}
})
};
// Create a filter function to handle filtering albums
// Allow users to search for albums by title, converts the album title to album id to be handed off to backend
let handle_filter_albums = move |ev: leptos::ev::Event| {
ev.prevent_default();
let album_input: String = event_target_value(&ev);
//Update the album signal with the input
set_albums.update(|value: &mut String| *value = album_input);
spawn_local(async move {
let filter_results = search_albums(albums.get_untracked(), 3).await;
if let Err(err) = filter_results {
log!("Error filtering albums: {:?}", err);
} else if let Ok(albums) = filter_results {
log!("Filtered albums: {:?}", albums);
set_filtered_albums.update(|value| *value = albums);
}
})
};
let handle_response = Rc::new(move |response: &Response| {
if response.ok() {
set_error_msg.update(|value| *value = None);
set_filtered_artists.update(|value| *value = vec![]);
set_filtered_albums.update(|value| *value = vec![]);
set_artists.update(|value| *value = "".to_string());
set_albums.update(|value| *value = "".to_string());
open.set(false);
} else {
// TODO: Extract error message from response
set_error_msg.update(|value| *value = Some("Error uploading song".to_string()));
}
});
view! {
<Show when=open fallback=move || view! {}>
<div class="upload-container" open=open>
<div class="close-button" on:click=close_dialog><Icon icon=icondata::IoClose /></div>
<div class="upload-header">
<h1>Upload Song</h1>
</div>
<Form action="/api/upload" method="POST" enctype=String::from("multipart/form-data")
class="upload-form" on_response=handle_response.clone()>
<div class="input-bx">
<input type="text" name="title" required class="text-input" required/>
<span>Title</span>
</div>
<div class="artists has-search">
<div class="input-bx">
<input type="text" name="artist_ids" class="text-input" prop:value=artists on:input=handle_filter_artists/>
<span>Artists</span>
</div>
<Show
when=move || {filtered_artists.get().len() > 0}
fallback=move || view! {}
>
<ul class="artist_results search-results">
{
move || filtered_artists.get().iter().enumerate().map(|(_index,filtered_artist)| view! {
<Artist artist=filtered_artist.clone() artists=artists set_artists=set_artists set_filtered=set_filtered_artists/>
}).collect::<Vec<_>>()
}
</ul>
</Show>
</div>
<div class="albums has-search">
<div class="input-bx">
<input type="text" name="album_id" class="text-input" prop:value=albums on:input=handle_filter_albums/>
<span>Album ID</span>
</div>
<Show
when=move || {filtered_albums.get().len() > 0}
fallback=move || view! {}
>
<ul class="album_results search-results">
{
move || filtered_albums.get().iter().enumerate().map(|(_index,filtered_album)| view! {
<Album album=filtered_album.clone() _albums=albums set_albums=set_albums set_filtered=set_filtered_albums/>
}).collect::<Vec<_>>()
}
</ul>
</Show>
</div>
<div class="input-bx">
<input type="number" name="track_number" class="text-input"/>
<span>Track Number</span>
</div>
<div class="release-date">
<div class="left">
<span>Release</span>
<span>Date</span>
</div>
<input class="info" type="date" name="release_date"/>
</div>
<div class="file">
<span>File</span>
<input class="info" type="file" accept=".mp3" name="file" required/>
</div>
<button type="submit" class="upload-button">Upload</button>
</Form>
<Show
when=move || {error_msg.get().is_some()}
fallback=move || view! {}
>
<div class="error-msg">
<Icon icon=icondata::IoAlertCircleSharp />
{error_msg.get().as_ref().unwrap()}
</div>
</Show>
</div>
</Show>
}
}
#[component]
pub fn Artist(artist: Artist, artists: ReadSignal<String>, set_artists: WriteSignal<String>, set_filtered: WriteSignal<Vec<Artist>>) -> impl IntoView {
// Converts artist name to artist id and adds it to the artist input
let add_artist = move |_| {
//Create an empty string to hold previous artist ids
let mut s: String = String::from("");
//Get the current artist input
let all_artirts: String = artists.get();
//Split the input into a vector of artists separated by commas
let mut ids: Vec<&str> = all_artirts.split(",").collect();
//If there is only one artist in the input, get their id equivalent and add it to the string
if ids.len() == 1 {
let value_str = match artist.id.clone() {
Some(v) => v.to_string(),
None => String::from("None"),
};
s.push_str(&value_str);
s.push_str(",");
set_artists.update(|value| *value = s);
//If there are multiple artists in the input, pop the last artist by string off the vector,
//get their id equivalent, and add it to the string
} else {
ids.pop();
for id in ids {
s.push_str(id);
s.push_str(",");
}
let value_str = match artist.id.clone() {
Some(v) => v.to_string(),
None => String::from("None"),
};
s.push_str(&value_str);
s.push_str(",");
set_artists.update(|value| *value = s);
}
//Clear the search results
set_filtered.update(|value| *value = vec![]);
};
view! {
<div class="artist result" on:click=add_artist>
{artist.name.clone()}
</div>
}
}
#[component]
pub fn Album(album: Album, _albums: ReadSignal<String>, set_albums: WriteSignal<String>, set_filtered: WriteSignal<Vec<Album>>) -> impl IntoView {
//Converts album title to album id to upload a song
let add_album = move |_| {
let value_str = match album.id.clone() {
Some(v) => v.to_string(),
None => String::from("None"),
};
set_albums.update(|value| *value = value_str);
set_filtered.update(|value| *value = vec![]);
};
view! {
<div class="album result" on:click=add_album>
{album.title.clone()}
</div>
}
}

View File

@ -1,30 +0,0 @@
use leptos::*;
use leptos_icons::*;
use crate::components::upload::*;
use crate::components::add_artist::*;
use crate::components::add_album::*;
#[component]
pub fn UploadDropdownBtn(dropdown_open: RwSignal<bool>) -> impl IntoView {
let open_dropdown = move |_| {
dropdown_open.set(!dropdown_open.get());
};
view! {
<button class={move || if dropdown_open() {"upload-dropdown-btn upload-dropdown-btn-active"} else {"upload-dropdown-btn"}} on:click=open_dropdown>
<div class="add-sign">
<Icon icon=icondata::IoAddSharp />
</div>
</button>
}
}
#[component]
pub fn UploadDropdown(dropdown_open: RwSignal<bool>, upload_open: RwSignal<bool>, add_artist_open: RwSignal<bool>, add_album_open: RwSignal<bool>) -> impl IntoView {
view! {
<div class="upload-dropdown" on:click=move |_| dropdown_open.set(false)>
<UploadBtn dialog_open=upload_open />
<AddArtistBtn add_artist_open=add_artist_open/>
<AddAlbumBtn add_album_open=add_album_open/>
</div>
}
}

View File

@ -1,8 +1,8 @@
use cfg_if::cfg_if; use cfg_if::cfg_if;
use leptos::logging::log;
cfg_if! { cfg_if! {
if #[cfg(feature = "ssr")] { if #[cfg(feature = "ssr")] {
use leptos::logging::log;
use lazy_static::lazy_static; use lazy_static::lazy_static;
use std::env; use std::env;

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

@ -8,20 +8,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 users; pub mod users;
pub mod search; pub mod search;
pub mod fileserv; pub mod searchbar;
pub mod error_template;
pub mod upload;
pub mod util;
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;
} }
} }
@ -34,6 +27,7 @@ if #[cfg(feature = "hydrate")] {
#[wasm_bindgen] #[wasm_bindgen]
pub fn hydrate() { pub fn hydrate() {
use app::*; use app::*;
use leptos::*;
console_error_panic_hook::set_once(); console_error_panic_hook::set_once();

View File

@ -12,69 +12,93 @@ 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 axum_login::tower_sessions::SessionManagerLayer;
use tower_sessions_redis_store::{fred::prelude::*, RedisStore};
use axum_login::AuthManagerLayerBuilder;
use libretunes::auth_backend::AuthBackend;
use log::*;
flexi_logger::Logger::try_with_env_or_str("debug").unwrap().format(flexi_logger::opt_format).start().unwrap();
info!("\n{}", include_str!("../ascii_art.txt"));
info!("Starting Leptos server...");
use dotenv::dotenv; use dotenv::dotenv;
dotenv().ok(); dotenv().ok();
debug!("Running database migrations...");
// Bring the database up to date // Bring the database up to date
libretunes::database::migrate(); libretunes::database::migrate();
debug!("Connecting to Redis..."); 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);
println!("listening on http://{}", &addr);
let app = Router::new() HttpServer::new(move || {
.leptos_routes(&leptos_options, routes, App) let leptos_options = &conf.leptos_options;
.route("/assets/*uri", get(|uri| get_static_file(uri, ""))) let site_root = &leptos_options.site_root;
.layer(auth_layer)
.fallback(file_and_error_handler)
.with_state(leptos_options);
let listener = tokio::net::TcpListener::bind(&addr).await.expect(&format!("Could not bind to {}", &addr)); App::new()
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
info!("Listening on http://{}", &addr); // serve JS/WASM/CSS from `pkg`
.service(Files::new("/pkg", format!("{site_root}/pkg")))
axum::serve(listener, app.into_make_service()).await.expect("Server failed"); // 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(not(feature = "ssr"))] #[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")))]
pub fn main() { pub fn main() {
// no client-side main function // no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing // unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead // see lib.rs for hydration function instead
// see optional feature `csr` instead
}
#[cfg(all(not(feature = "ssr"), feature = "csr"))]
pub fn main() {
// a client-side main function is required for using `trunk serve`
// prefer using `cargo leptos serve` instead
// to run: `trunk serve --open --features csr`
use leptos::*;
use libretunes::app::*;
use wasm_bindgen::prelude::wasm_bindgen;
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
} }

View File

@ -1,4 +1,5 @@
use std::time::SystemTime; use std::time::SystemTime;
use std::error::Error;
use time::Date; use time::Date;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@ -8,7 +9,6 @@ cfg_if! {
if #[cfg(feature = "ssr")] { if #[cfg(feature = "ssr")] {
use diesel::prelude::*; use diesel::prelude::*;
use crate::database::PgPooledConn; use crate::database::PgPooledConn;
use std::error::Error;
} }
} }
@ -41,15 +41,13 @@ pub struct User {
/// The time the user was created /// The time the user was created
#[cfg_attr(feature = "ssr", diesel(deserialize_as = SystemTime))] #[cfg_attr(feature = "ssr", diesel(deserialize_as = SystemTime))]
pub created_at: Option<SystemTime>, pub created_at: Option<SystemTime>,
/// Whether the user is an admin
pub admin: bool,
} }
/// Model for an artist /// Model for an artist
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable, Identifiable))] #[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, Clone, Debug)] #[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))]
@ -167,10 +165,10 @@ impl Artist {
} }
/// Model for an album /// Model for an album
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable, Identifiable))] #[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::albums))] #[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::albums))]
#[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, Clone, Debug)] #[derive(Serialize, Deserialize)]
pub struct Album { pub struct Album {
/// A unique id for the album /// A unique id for the album
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))] #[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
@ -179,8 +177,6 @@ pub struct Album {
pub title: String, pub title: String,
/// The album's release date /// The album's release date
pub release_date: Option<Date>, pub release_date: Option<Date>,
/// The path to the album's image file
pub image_path: Option<String>,
} }
impl Album { impl Album {

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>
@ -74,11 +70,11 @@ pub fn Login() -> impl IntoView {
<Show <Show
when=move || {show_password() == false} when=move || {show_password() == false}
fallback=move || view!{ <button on:click=toggle_password class="login-password-visibility"> fallback=move || view!{ <button on:click=toggle_password class="login-password-visibility">
<Icon icon=icondata::AiEyeInvisibleFilled /> <Icon icon=Icon::from(AiEyeInvisibleFilled) />
</button> /> } </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

@ -1,7 +1,10 @@
use crate::auth::signup; use crate::auth::signup;
use crate::models::User; use crate::models::User;
use leptos::ev::input;
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]
@ -12,6 +15,8 @@ pub fn Signup() -> impl IntoView {
let (show_password, set_show_password) = create_signal(false); let (show_password, set_show_password) = create_signal(false);
let navigate = leptos_router::use_navigate();
let toggle_password = move |_| { let toggle_password = move |_| {
set_show_password.update(|show_password| *show_password = !*show_password); set_show_password.update(|show_password| *show_password = !*show_password);
log!("showing password"); log!("showing password");
@ -25,7 +30,6 @@ pub fn Signup() -> impl IntoView {
email: email.get(), email: email.get(),
password: Some(password.get()), password: Some(password.get()),
created_at: None, created_at: None,
admin: false,
}; };
log!("new user: {:?}", new_user); log!("new user: {:?}", new_user);
@ -45,7 +49,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>
@ -82,10 +86,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 std::time::Duration;
use crate::playstatus::PlayStatus; use crate::playstatus::PlayStatus;
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
@ -191,9 +195,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 +206,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 +214,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>
@ -335,7 +339,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>
} }
@ -346,7 +350,7 @@ fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView { pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// 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" && status.with_untracked(|status| status.search_active) == false {
e.prevent_default(); e.prevent_default();
log!("Right arrow key pressed, skipping forward by {} seconds", ARROW_KEY_SKIP_TIME); log!("Right arrow key pressed, skipping forward by {} seconds", ARROW_KEY_SKIP_TIME);
@ -359,7 +363,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
error!("Unable to skip forward: Unable to get current duration"); error!("Unable to skip forward: Unable to get current duration");
} }
} else if e.key() == "ArrowLeft" { } else if e.key() == "ArrowLeft" && status.with_untracked(|status| status.search_active) == false {
e.prevent_default(); e.prevent_default();
log!("Left arrow key pressed, skipping backward by {} seconds", ARROW_KEY_SKIP_TIME); log!("Left arrow key pressed, skipping backward by {} seconds", ARROW_KEY_SKIP_TIME);
@ -376,7 +380,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// Listen for space bar presses to play/pause // Listen for space bar presses to play/pause
let _space_bar_handle = window_event_listener(ev::keypress, move |e: ev::KeyboardEvent| { let _space_bar_handle = window_event_listener(ev::keypress, move |e: ev::KeyboardEvent| {
if e.key() == " " { if e.key() == " " && status.with_untracked(|status| status.search_active) == false {
e.prevent_default(); e.prevent_default();
log!("Space bar pressed, toggling play/pause"); log!("Space bar pressed, toggling play/pause");

View File

@ -11,6 +11,8 @@ pub struct PlayStatus {
pub playing: bool, pub playing: bool,
/// Whether or not the queue is open /// Whether or not the queue is open
pub queue_open: bool, pub queue_open: bool,
/// Whether or not the search bar is active (useful for knowing when spacebar to play/pause, etc should be disabled)
pub search_active: bool,
/// 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
@ -56,6 +58,7 @@ impl Default for PlayStatus {
Self { Self {
playing: false, playing: false,
queue_open: false, queue_open: false,
search_active: false,
audio_player: None, audio_player: None,
history: VecDeque::new(), history: VecDeque::new(),
queue: VecDeque::new(), queue: VecDeque::new(),

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";
@ -105,7 +106,7 @@ pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
<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

@ -12,7 +12,6 @@ diesel::table! {
id -> Int4, id -> Int4,
title -> Varchar, title -> Varchar,
release_date -> Nullable<Date>, release_date -> Nullable<Date>,
image_path -> Nullable<Varchar>,
} }
} }
@ -50,7 +49,6 @@ diesel::table! {
email -> Varchar, email -> Varchar,
password -> Varchar, password -> Varchar,
created_at -> Timestamp, created_at -> Timestamp,
admin -> Bool,
} }
} }

View File

@ -39,10 +39,11 @@ if #[cfg(feature = "ssr")] {
/// # Returns /// # Returns
/// A Result containing a vector of albums if the search was successful, or an error if the search failed /// A Result containing a vector of albums if the search was successful, or an error if the search failed
#[server(endpoint = "search_albums")] #[server(endpoint = "search_albums")]
pub async fn search_albums(query: String, limit: i64) -> Result<Vec<Album>, ServerFnError> { pub async fn search_albums(query: String, limit: i64) -> Result<Vec<(Album, f32)>, ServerFnError> {
use crate::schema::albums::dsl::*; use crate::schema::albums::dsl::*;
Ok(albums Ok(albums
.select((albums::all_columns(), trgm_distance(title, query.clone())))
.filter(trgm_similar(title, query.clone())) .filter(trgm_similar(title, query.clone()))
.order_by(trgm_distance(title, query)) .order_by(trgm_distance(title, query))
.limit(limit) .limit(limit)
@ -58,10 +59,11 @@ pub async fn search_albums(query: String, limit: i64) -> Result<Vec<Album>, Serv
/// # Returns /// # Returns
/// A Result containing a vector of artists if the search was successful, or an error if the search failed /// A Result containing a vector of artists if the search was successful, or an error if the search failed
#[server(endpoint = "search_artists")] #[server(endpoint = "search_artists")]
pub async fn search_artists(query: String, limit: i64) -> Result<Vec<Artist>, ServerFnError> { pub async fn search_artists(query: String, limit: i64) -> Result<Vec<(Artist, f32)>, ServerFnError> {
use crate::schema::artists::dsl::*; use crate::schema::artists::dsl::*;
Ok(artists Ok(artists
.select((artists::all_columns(), trgm_distance(name, query.clone())))
.filter(trgm_similar(name, query.clone())) .filter(trgm_similar(name, query.clone()))
.order_by(trgm_distance(name, query)) .order_by(trgm_distance(name, query))
.limit(limit) .limit(limit)
@ -77,10 +79,11 @@ pub async fn search_artists(query: String, limit: i64) -> Result<Vec<Artist>, Se
/// # Returns /// # Returns
/// A Result containing a vector of songs if the search was successful, or an error if the search failed /// A Result containing a vector of songs if the search was successful, or an error if the search failed
#[server(endpoint = "search_songs")] #[server(endpoint = "search_songs")]
pub async fn search_songs(query: String, limit: i64) -> Result<Vec<Song>, ServerFnError> { pub async fn search_songs(query: String, limit: i64) -> Result<Vec<(Song, f32)>, ServerFnError> {
use crate::schema::songs::dsl::*; use crate::schema::songs::dsl::*;
Ok(songs Ok(songs
.select((songs::all_columns(), trgm_distance(title, query.clone())))
.filter(trgm_similar(title, query.clone())) .filter(trgm_similar(title, query.clone()))
.order_by(trgm_distance(title, query)) .order_by(trgm_distance(title, query))
.limit(limit) .limit(limit)
@ -95,14 +98,15 @@ pub async fn search_songs(query: String, limit: i64) -> Result<Vec<Song>, Server
/// `limit` - The maximum number of results to return for each type /// `limit` - The maximum number of results to return for each type
/// ///
/// # Returns /// # Returns
/// A Result containing a tuple of vectors of albums, artists, and songs if the search was successful, /// A Result containing a tuple of vectors of albums, artists, and songs,
/// along with respective similarity scores, if the search was successful.
#[server(endpoint = "search")] #[server(endpoint = "search")]
pub async fn search(query: String, limit: i64) -> Result<(Vec<Album>, Vec<Artist>, Vec<Song>), ServerFnError> { pub async fn search(query: String, limit: i64) -> Result<(Vec<(Album, f32)>, Vec<(Artist, f32)>, Vec<(Song, f32)>), ServerFnError> {
let albums = search_albums(query.clone(), limit); let albums = search_albums(query.clone(), limit);
let artists = search_artists(query.clone(), limit); let artists = search_artists(query.clone(), limit);
let songs = search_songs(query.clone(), limit); let songs = search_songs(query.clone(), limit);
use tokio::join; use futures::join;
let (albums, artists, songs) = join!(albums, artists, songs); let (albums, artists, songs) = join!(albums, artists, songs);
Ok((albums?, artists?, songs?)) Ok((albums?, artists?, songs?))

154
src/searchbar.rs Normal file
View File

@ -0,0 +1,154 @@
use crate::search::search;
use crate::playstatus::PlayStatus;
use crate::song::Song;
use crate::models::Album;
use crate::models::Artist;
use crate::models::Song;
use leptos::*;
use leptos::ev::*;
use leptos::leptos_dom::*;
use leptos_icons::*;
use leptos_icons::BsIcon::*;
const OPTIONS_BTN_SIZE: &str = "2.5rem";
#[component]
pub fn SearchBar(status: RwSignal<PlayStatus>) -> impl IntoView {
let search_query = create_rw_signal(String::new());
let search_results = create_rw_signal((Vec::<(Album, f32)>::new(), Vec::<(Artist, f32)>::new(), Vec::<(Song, f32)>::new()));
let search_limit = 10;
let on_input = move |e: Event| {
search_query.set(event_target_value(&e));
log!("Search Query: {:?}", search_query.get_untracked());
if search_query.get_untracked().len() < 3 {
search_results.set((Vec::<(Album, f32)>::new(), Vec::<(Artist, f32)>::new(), Vec::<(Song, f32)>::new()));
return;
}
spawn_local(async move {
log!("Searching for: {:?}", search_query.get_untracked());
let results = search(search_query.get_untracked(), search_limit).await;
match results {
Ok((albums, artists, songs)) => {
search_results.set((albums, artists, songs));
}
Err(err) => {
log!("Error searching: {:?}", err);
}
}
});
};
let on_disabled = move |_e: FocusEvent| {
log!("Search Bar Disabled");
};
let on_enabled = move |_e: FocusEvent| {
status.update(|status| {
status.search_active = true;
});
log!("Search Bar Enabled");
};
let prevent_focus = move |e: MouseEvent| {
e.prevent_default();
};
view! {
<div class="search-container">
<div class="search-bar">
<input type="search" placeholder="Search" on:input=on_input on:blur=on_disabled on:focus=on_enabled/>
</div>
<div class="search-results">
<ul class="search-results-list">
{
move || search_results.with(|(albums, artists, songs)| -> Vec<_> {
let mut album_index = 0;
let mut artist_index = 0;
let mut song_index = 0;
let mut views = Vec::new();
while album_index < albums.len() || artist_index < artists.len() || song_index < songs.len() {
const RM_BTN_SIZE: &str = "2.5rem";
let album_score = if album_index < albums.len() { albums[album_index].1 } else { f32::MAX };
let artist_score = if artist_index < artists.len() { artists[artist_index].1 } else { f32::MAX };
let song_score = if song_index < songs.len() { songs[song_index].1 } else { f32::MAX };
if artist_score <= album_score && artist_score <= song_score {
let artist = &artists[artist_index].0;
artist_index += 1;
views.push(view! {
<li class="search-result">
<div class="result-container">
<div class="search-result-artist">
{artist.name.clone()}
</div>
<div class="right-side-result">
<div class="search-item-type">
"(Artist)"
</div>
<button class="search-result-options" on:mousedown=prevent_focus>
<Icon class="search-result-options-icon" width=OPTIONS_BTN_SIZE height=OPTIONS_BTN_SIZE icon=Icon::from(BsThreeDotsVertical) />
</button>
</div>
</div>
</li>
});
}
else if album_score <= artist_score && album_score <= song_score {
let album = &albums[album_index].0;
album_index += 1;
views.push(view! {
<li class="search-result">
<div class="result-container">
<div class="search-result-album">
{album.title.clone()}
{match album.release_date {
Some(date) => format!(" ({})", date),
None => "".to_string()
}}
</div>
<div class="right-side-result">
<div class="search-item-type">
"(Album)"
</div>
<button class="search-result-options" on:mousedown=prevent_focus>
<Icon class="search-result-options-icon" width=OPTIONS_BTN_SIZE height=OPTIONS_BTN_SIZE icon=Icon::from(BsThreeDotsVertical) />
</button>
</div>
</div>
</li>
});
}
else if song_score <= artist_score && song_score <= album_score {
let song = &songs[song_index].0;
song_index += 1;
views.push(view! {
<li class="search-result">
<div class="result-container">
<Song song_image_path=match song.image_path.clone() {
Some(path) => path,
None => "".to_string()
} song_title=song.title.clone() song_artist="".to_string() />
<div class="right-side-result">
<div class="search-item-type">
"(Song)"
</div>
<button class="search-result-options" on:mousedown=prevent_focus>
<Icon class="search-result-options-icon" width=OPTIONS_BTN_SIZE height=OPTIONS_BTN_SIZE icon=Icon::from(BsThreeDotsVertical) />
</button>
</div>
</div>
</li>
});
}
}
views
})
}
</ul>
</div>
</div>
}
}

View File

@ -3,9 +3,9 @@ use leptos::*;
#[component] #[component]
pub fn Song(song_image_path: String, song_title: String, song_artist: String) -> impl IntoView { pub fn Song(song_image_path: String, song_title: String, song_artist: String) -> impl IntoView {
view!{ view!{
<div class="queue-song"> <div class="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="song-info">
<h3>{song_title}</h3> <h3>{song_title}</h3>
<p>{song_artist}</p> <p>{song_artist}</p>
</div> </div>

View File

@ -1,294 +0,0 @@
use leptos::*;
use server_fn::codec::{MultipartData, MultipartFormData};
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use multer::Field;
use crate::database::get_db_conn;
use diesel::prelude::*;
use log::*;
use server_fn::error::NoCustomError;
use time::Date;
}
}
/// Extract the text from a multipart field
#[cfg(feature = "ssr")]
async fn extract_field(field: Field<'static>) -> Result<String, ServerFnError> {
let field = match field.text().await {
Ok(field) => field,
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading field: {}", e)))?,
};
Ok(field)
}
/// Validate the artist ids in a multipart field
/// Expects a field with a comma-separated list of artist ids, and ensures each is a valid artist id in the database
#[cfg(feature = "ssr")]
async fn validate_artist_ids(artist_ids: Field<'static>) -> Result<Vec<i32>, ServerFnError> {
use crate::models::Artist;
use diesel::result::Error::NotFound;
// Extract the artist id from the field
match artist_ids.text().await {
Ok(artist_ids) => {
let artist_ids = artist_ids.trim_end_matches(',').split(',');
artist_ids.filter(|artist_id| !artist_id.is_empty()).map(|artist_id| {
// Parse the artist id as an integer
if let Ok(artist_id) = artist_id.parse::<i32>() {
// Check if the artist exists
let db_con = &mut get_db_conn();
let artist = crate::schema::artists::dsl::artists.find(artist_id).first::<Artist>(db_con);
match artist {
Ok(_) => Ok(artist_id),
Err(NotFound) => Err(ServerFnError::<NoCustomError>::
ServerError("Artist does not exist".to_string())),
Err(e) => Err(ServerFnError::<NoCustomError>::
ServerError(format!("Error finding artist id: {}", e))),
}
} else {
Err(ServerFnError::<NoCustomError>::ServerError("Error parsing artist id".to_string()))
}
}).collect()
},
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading artist id: {}", e))),
}
}
/// Validate the album id in a multipart field
/// Expects a field with an album id, and ensures it is a valid album id in the database
#[cfg(feature = "ssr")]
async fn validate_album_id(album_id: Field<'static>) -> Result<Option<i32>, ServerFnError> {
use crate::models::Album;
use diesel::result::Error::NotFound;
// Extract the album id from the field
match album_id.text().await {
Ok(album_id) => {
if album_id.is_empty() {
return Ok(None);
}
// Parse the album id as an integer
if let Ok(album_id) = album_id.parse::<i32>() {
// Check if the album exists
let db_con = &mut get_db_conn();
let album = crate::schema::albums::dsl::albums.find(album_id).first::<Album>(db_con);
match album {
Ok(_) => Ok(Some(album_id)),
Err(NotFound) => Err(ServerFnError::<NoCustomError>::
ServerError("Album does not exist".to_string())),
Err(e) => Err(ServerFnError::<NoCustomError>::
ServerError(format!("Error finding album id: {}", e))),
}
} else {
Err(ServerFnError::<NoCustomError>::ServerError("Error parsing album id".to_string()))
}
},
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading album id: {}", e))),
}
}
/// Validate the track number in a multipart field
/// Expects a field with a track number, and ensures it is a valid track number (non-negative integer)
#[cfg(feature = "ssr")]
async fn validate_track_number(track_number: Field<'static>) -> Result<Option<i32>, ServerFnError> {
match track_number.text().await {
Ok(track_number) => {
if track_number.is_empty() {
return Ok(None);
}
if let Ok(track_number) = track_number.parse::<i32>() {
if track_number < 0 {
return Err(ServerFnError::<NoCustomError>::
ServerError("Track number must be positive or 0".to_string()));
} else {
Ok(Some(track_number))
}
} else {
return Err(ServerFnError::<NoCustomError>::ServerError("Error parsing track number".to_string()));
}
},
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading track number: {}", e)))?,
}
}
/// 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> {
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);
match release_date {
Ok(release_date) => Ok(Some(release_date)),
Err(_) => Err(ServerFnError::<NoCustomError>::ServerError("Invalid release date".to_string())),
}
},
Err(e) => Err(ServerFnError::<NoCustomError>::ServerError(format!("Error reading release date: {}", e))),
}
}
/// Handle the file upload form
#[server(input = MultipartFormData, endpoint = "/upload")]
pub async fn upload(data: MultipartData) -> Result<(), ServerFnError> {
// Safe to unwrap - "On the server side, this always returns Some(_). On the client side, always returns None."
let mut data = data.into_inner().unwrap();
let mut title = None;
let mut artist_ids = None;
let mut album_id = None;
let mut track = None;
let mut release_date = None;
let mut file_name = None;
let mut duration = None;
// Fetch the fields from the form data
while let Ok(Some(mut field)) = data.next_field().await {
let name = field.name().unwrap_or_default().to_string();
match name.as_str() {
"title" => { title = Some(extract_field(field).await?); },
"artist_ids" => { artist_ids = Some(validate_artist_ids(field).await?); },
"album_id" => { album_id = Some(validate_album_id(field).await?); },
"track_number" => { track = Some(validate_track_number(field).await?); },
"release_date" => { release_date = Some(validate_release_date(field).await?); },
"file" => {
use symphonia::core::codecs::CODEC_TYPE_MP3;
use crate::util::audio::extract_metadata;
use std::fs::OpenOptions;
use std::io::{Seek, Write};
// Some logging is done here where there is high potential for bugs / failures,
// or behavior that we may wish to change in the future
// Create file name
let title = title.clone().ok_or(ServerFnError::<NoCustomError>::
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 upload_path = format!("assets/audio/upload-{}_{}.mp3", date_str, clean_title);
file_name = Some(format!("upload-{}_{}.mp3", date_str, clean_title));
debug!("Saving uploaded file {}", upload_path);
// Save file to disk
// Use these open options to create the file, write to it, then read from it
let mut file = OpenOptions::new()
.read(true)
.write(true)
.create(true)
.open(upload_path.clone())?;
while let Some(chunk) = field.chunk().await? {
file.write(&chunk)?;
}
file.flush()?;
// Rewind the file so the duration can be measured
file.rewind()?;
// Get the codec and duration of the file
let (file_codec, file_duration) = extract_metadata(file)
.map_err(|e| {
let msg = format!("Error measuring duration of audio file {}: {}", upload_path, e);
warn!("{}", msg);
ServerFnError::<NoCustomError>::ServerError(msg)
})?;
if file_codec != CODEC_TYPE_MP3 {
let msg = format!("Invalid uploaded audio file codec: {}", file_codec);
warn!("{}", msg);
return Err(ServerFnError::<NoCustomError>::ServerError(msg));
}
duration = Some(file_duration);
},
_ => {
warn!("Unknown file upload field: {}", name);
}
}
}
// Unwrap mandatory fields
let title = title.ok_or(ServerFnError::<NoCustomError>::ServerError("Missing title".to_string()))?;
let artist_ids = artist_ids.unwrap_or(vec![]);
let file_name = file_name.ok_or(ServerFnError::<NoCustomError>::ServerError("Missing file".to_string()))?;
let duration = duration.ok_or(ServerFnError::<NoCustomError>::ServerError("Missing duration".to_string()))?;
let duration = i32::try_from(duration).map_err(|e| ServerFnError::<NoCustomError>::
ServerError(format!("Error converting duration to i32: {}", e)))?;
let album_id = album_id.unwrap_or(None);
let track = track.unwrap_or(None);
let release_date = release_date.unwrap_or(None);
if album_id.is_some() != track.is_some() {
return Err(ServerFnError::<NoCustomError>
::ServerError("Album id and track number must both be present or both be absent".to_string()));
}
// Create the song
use crate::models::Song;
let song = Song {
id: None,
title,
album_id,
track,
duration,
release_date,
storage_path: file_name,
image_path: None,
};
// Save the song to the database
let db_con = &mut get_db_conn();
let song = song.insert_into(crate::schema::songs::table)
.get_result::<Song>(db_con)
.map_err(|e| {
let msg = format!("Error saving song to database: {}", e);
warn!("{}", msg);
ServerFnError::<NoCustomError>::ServerError(msg)
})?;
// Save the song's artists to the database
let song_id = song.id.ok_or_else(|| {
let msg = "Error saving song to database: song id not found after insertion".to_string();
warn!("{}", msg);
ServerFnError::<NoCustomError>::ServerError(msg)
})?;
use crate::schema::song_artists;
use diesel::ExpressionMethods;
let artist_ids = artist_ids.into_iter().map(|artist_id| {
(song_artists::song_id.eq(song_id), song_artists::artist_id.eq(artist_id))
}).collect::<Vec<_>>();
diesel::insert_into(crate::schema::song_artists::table)
.values(&artist_ids)
.execute(db_con)
.map_err(|e| {
let msg = format!("Error saving song artists to database: {}", e);
warn!("{}", msg);
ServerFnError::<NoCustomError>::ServerError(msg)
})?;
Ok(())
}

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,37 +0,0 @@
use symphonia::core::codecs::CodecType;
use symphonia::core::formats::FormatOptions;
use symphonia::core::io::MediaSourceStream;
use symphonia::core::meta::MetadataOptions;
use symphonia::core::probe::Hint;
use std::fs::File;
/// Extract the codec and duration of an audio file
/// This is combined into one function because the file object will be consumed
pub fn extract_metadata(file: File) -> Result<(CodecType, u64), Box<dyn std::error::Error>> {
let source_stream = MediaSourceStream::new(Box::new(file), Default::default());
let hint = Hint::new();
let format_opts = FormatOptions::default();
let metadata_opts = MetadataOptions::default();
let probe = symphonia::default::get_probe().format(&hint, source_stream, &format_opts, &metadata_opts)?;
let reader = probe.format;
if reader.tracks().len() != 1 {
return Err(format!("Expected 1 track, found {}", reader.tracks().len()).into())
}
let track = &reader.tracks()[0];
let time_base = track.codec_params.time_base.ok_or("Missing time base")?;
let duration = track.codec_params.n_frames
.map(|frames| track.codec_params.start_ts + frames)
.ok_or("Missing number of frames")?;
let duration = duration
.checked_mul(time_base.numer as u64)
.and_then(|v| v.checked_div(time_base.denom as u64))
.ok_or("Overflow while computing duration")?;
Ok((track.codec_params.codec, duration))
}

View File

@ -1,7 +0,0 @@
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
pub mod audio;
}
}

View File

@ -1,135 +0,0 @@
@import "theme.scss";
.add-album-container {
position: fixed;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
width: 30rem;
height: 24rem;
border: 1px solid white;
border-radius: 5px;
padding: 1rem;
padding-top: 0;
z-index: 2;
display: flex;
flex-direction: column;
background-color: #1c1c1c;
z-index: 11;
.upload-header {
font-size: .7rem;
font-weight: 300;
padding-bottom: 0;
border-bottom: 1px solid white;
font-family: "Roboto", sans-serif;
}
.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;
border: none;
}
.close-button:hover {
transform: scale(1.1);
background-color: rgba(255, 255, 255, 0.1);
}
.close-button:active {
transform: scale(0.8);
}
.create-album-form {
width:100%;
height: 100%;
position: relative;
.input-bx{
position: relative;
margin-top: 1rem;
width: 300px;
input{
width: 100%;
padding: 10px;
border: 2px solid #7f8fa6;
border-radius: 5px;
outline: none;
font-size: 1rem;
transition: 0.6s;
background-color: transparent;
}
span{
position: absolute;
left: 0;
top: 1px;
padding: 10px;
font-size: 1rem;
color: #7f8fa6;
text-transform: uppercase;
pointer-events: none;
transition: 0.6s;
background-color: transparent;
}
input:valid ~ span,
input:focus ~ span{
color: #fff;
transform: translateX(10px) translateY(-7px);
font-size: 0.65rem;
font-weight: 600;
padding: 0 10px;
background: #1c1c1c;
letter-spacing: 0.1rem;
}
input:valid,
input:focus{
color: #fff;
border: 2px solid #fff;
}
}
.release-date {
margin-top: 1rem;
font-size: 1.2rem;
color: #7f8fa6;
font-family: "Roboto", sans-serif;
display: flex;
align-items: center;
.left {
display: flex;
flex-direction: column;
margin-left: 5px;
margin-right: 10px;
}
span {
font-size: .85rem;
}
input {
padding: 8px;
}
}
.upload-button {
position: absolute;
bottom: 5px;
margin-top: 1rem;
padding: 10px;
background-color: #7f8fa6;
color: #fff;
width: 100%;
font-size: 1rem;
font-family: "Roboto", sans-serif;
border: none;
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
&:hover {
background-color: #fff;
color: #7f8fa6;
}
}
}
}

View File

@ -1,115 +0,0 @@
@import "theme.scss";
.add-artist-container {
position: fixed;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
width: 30rem;
height: 15rem;
border: 1px solid white;
border-radius: 5px;
padding: 1rem;
padding-top: 0;
z-index: 2;
display: flex;
flex-direction: column;
background-color: #1c1c1c;
z-index: 11;
.upload-header {
font-size: .7rem;
font-weight: 300;
padding-bottom: 0;
border-bottom: 1px solid white;
font-family: "Roboto", sans-serif;
}
.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;
border: none;
}
.close-button:hover {
transform: scale(1.1);
background-color: rgba(255, 255, 255, 0.1);
}
.close-button:active {
transform: scale(0.8);
}
.create-artist-form {
width:100%;
height: 100%;
position: relative;
.input-bx{
margin-top: 1rem;
width: 300px;
position: relative;
input{
width: 100%;
padding: 10px;
border: 2px solid #7f8fa6;
border-radius: 5px;
outline: none;
font-size: 1rem;
transition: 0.6s;
background-color: transparent;
}
span{
position: absolute;
left: 0;
top: 1px;
padding: 10px;
font-size: 1rem;
color: #7f8fa6;
text-transform: uppercase;
pointer-events: none;
transition: 0.6s;
background-color: transparent;
}
input:valid ~ span,
input:focus ~ span{
color: #fff;
transform: translateX(10px) translateY(-7px);
font-size: 0.65rem;
font-weight: 600;
padding: 0 10px;
background: #1c1c1c;
letter-spacing: 0.1rem;
}
input:valid,
input:focus{
color: #fff;
border: 2px solid #fff;
}
}
.upload-button {
position: absolute;
bottom: 5px;
margin-top: 1rem;
padding: 10px;
background-color: #7f8fa6;
color: #fff;
width: 100%;
font-size: 1rem;
font-family: "Roboto", sans-serif;
border: none;
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
&:hover {
background-color: #fff;
color: #7f8fa6;
}
}
}
}

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,17 +0,0 @@
@import "theme.scss";
.home-container {
margin-top: 0;
width: 100%;
height: 100vh;
display: flex;
flex-direction: row;
overflow: hidden;
}
.home-component {
background: #1c1c1c;
height: 100vh;
margin: 2px;
padding: 0.2rem 1.5rem 1.5rem 1rem;
border-radius: 0.5rem;
}

View File

@ -1,16 +1,10 @@
@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 'song.scss';
@import "dashboard.scss"; @import 'searchbar.scss';
@import 'home.scss';
@import 'search.scss';
@import 'personal.scss';
@import 'upload.scss';
@import 'addArtist.scss';
@import 'addAlbum.scss';
body { body {
font-family: sans-serif; font-family: sans-serif;
@ -19,3 +13,8 @@ body {
margin: 0; margin: 0;
padding: 0; padding: 0;
} }
.home {
width: 100%;
height: 100%;
}

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

@ -5,10 +5,12 @@
top: 0; top: 0;
right: 0; right: 0;
width: 400px; width: 400px;
height: calc(100% - 78.9px); /* Adjust height to fit the queue */ height: calc(100% - 87px); /* Adjust height to fit the queue */
background-color: #424242; /* Queue background color */ background-color: #424242; /* Queue background color */
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2); box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
overflow-y: auto; /* Add scroll bar when queue is too long */ overflow-y: auto; /* Add scroll bar when queue is too long */
margin: 5px;
border-radius: 5px;
.queue-header { .queue-header {
background-color: #333; /* Header background color */ background-color: #333; /* Header background color */
@ -30,31 +32,6 @@
padding-top: 5px; padding-top: 5px;
padding-bottom: 5px; padding-bottom: 5px;
.queue-song {
display: flex;
align-items: center;
padding: 10px;
border-bottom: 1px solid #ccc; /* Separator line color */
img {
max-width: 50px; /* Adjust maximum width for images */
margin-right: 10px; /* Add spacing between image and text */
border-radius: 5px; /* Add border radius to image */
}
.queue-song-info {
h3 {
margin: 0; /* Remove default margin for heading */
color: #fff; /* Adjust text color for song */
}
p {
margin: 0; /* Remove default margin for paragraph */
color: #aaa; /* Adjust text color for artist */
}
}
}
button { button {
background: none; background: none;
border: none; border: none;

View File

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

99
style/searchbar.scss Normal file
View File

@ -0,0 +1,99 @@
@import 'theme.scss';
.search-container {
display: flex;
margin: 5px auto;
margin-left: 282px;
border-radius: 5px;
height: 100%;
width: calc(100% - 690px);
background-color: $search-background-color;
}
.search-bar {
background-color: transparent;
border-radius: 5px;
padding: 10px;
display: flex;
justify-content: left;
z-index: 10;
}
.search-bar input[type="search"] {
background-color: $search-bar-input-background-color;
border: none;
outline: none;
color: $search-bar-input-color;
padding: 10px;
border-radius: 5px;
font-size: 16px;
&::placeholder {
color: rgb(61, 61, 61);
}
}
.search-results {
background-color: $search-background-color;
border-bottom-left-radius: 5px;
border-bottom-right-radius: 5px;
display: flex;
margin-top: 55px;
height: calc(100% - 143px);
width: calc(100% - 690px);
position: absolute;
ul {
list-style: none;
padding: 0;
margin: 0;
width: 100%;
li {
width: calc(100% - 20px);
padding: 10px;
border-bottom: 1px solid $search-highlight-color;
border-radius: 5px;
color: white;
font-size: 16px;
cursor: pointer;
&:hover {
background-color: $search-highlight-color;
}
&:first-child {
border-top: 2px solid $search-highlight-color;
}
.result-container {
display: flex;
align-items: center;
justify-content: space-between;
}
.right-side-result {
display: flex;
align-items: center;
justify-content: space-between;
.search-item-type {
color: $search-item-type-color;
margin-right: 10px;
}
.search-result-options {
background-color: transparent;
border: none;
&:hover {
color: $search-options-color;
}
&:active {
color: $search-options-color;
}
}
}
}
}
}

View File

@ -1,152 +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;
position: relative;
.upload-overlay {
position: absolute;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 10;
}
.header {
font-size: 1.2rem;
}
.upload-dropdown-container {
position: absolute;
top: 10px;
right: 7px;
.upload-dropdown-btn {
display: flex;
flex-direction: row;
justify-content: center;
font-size: 0.9rem;
border-radius: 50px;
border: none;
height: 2.2rem;
padding-right: 1rem;
padding-left: 1rem;
cursor: pointer;
transition: all 0.3s ease;
.add-sign {
font-size: 1.5rem;
margin-top: auto;
}
}
.upload-dropdown-btn:hover {
background-color: #9e9e9e;
}
.upload-dropdown-btn-active {
border-radius: 12.5px 12.5px 0 0;
width: 110px;
}
.upload-dropdown {
background-color: #f0ecec;
color: black;
width: 110px;
border-radius: 0 0 5px 5px;
.add-btns {
border: none;
border-bottom: 1px solid black;
width: 100%;
padding: 0.25rem;
cursor: pointer;
}
.add-btns:first-child {
border-top: 1px solid black;
}
.add-btns:last-child {
border-radius: 0 0 5px 5px;
}
}
}
.buttons {
display: flex;
flex-direction: row;
font-size: 1.8rem;
align-items: center;
transition: all 0.5s;
cursor: pointer;
color: grey;
text-decoration: none;
}
.buttons:hover {
color: white;
}
.buttons:last-child {
margin-left: 0.02rem;
margin-top: 0.5rem;
}
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);
.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;
}
}
}
}

22
style/song.scss Normal file
View File

@ -0,0 +1,22 @@
.song {
display: flex;
align-items: center;
img {
max-width: 50px; /* 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;
color: #fff; /* Adjust text color for song */
}
p {
margin: 0;
color: #aaa; /* Adjust text color for artist */
}
}
}

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;
@ -11,6 +7,12 @@ $play-bar-background-color: #212121;
$play-grad-start: #0a0533; $play-grad-start: #0a0533;
$play-grad-end: $accent-color; $play-grad-end: $accent-color;
$queue-background-color: $play-bar-background-color; $queue-background-color: $play-bar-background-color;
$search-background-color: $play-bar-background-color;
$search-bar-input-background-color: gray;
$search-bar-input-color: black;
$search-highlight-color: #333;
$search-item-type-color: #666;
$search-options-color: #666;
$auth-inputs: #796dd4; $auth-inputs: #796dd4;
$auth-containers: white; $auth-containers: white;

View File

@ -1,193 +0,0 @@
@import "theme.scss";
.upload-container {
position: fixed;
top: 45%;
left: 50%;
transform: translate(-50%, -50%);
width: 30rem;
height: 30rem;
border: 1px solid white;
border-radius: 5px;
padding: 1rem;
padding-top: 0;
z-index: 2;
display: flex;
flex-direction: column;
background-color: #1c1c1c;
z-index: 11;
.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;
border: none;
}
.close-button:hover {
transform: scale(1.1);
background-color: rgba(255, 255, 255, 0.1);
}
.close-button:active {
transform: scale(0.8);
}
.upload-header {
font-size: .7rem;
font-weight: 300;
padding-bottom: 0;
border-bottom: 1px solid white;
font-family: "Roboto", sans-serif;
}
.upload-form {
padding: .1rem;
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
position: relative;
.input-bx{
margin-top: 1rem;
position: relative;
width: 300px;
input{
width: 100%;
padding: 10px;
border: 2px solid #7f8fa6;
border-radius: 5px;
outline: none;
font-size: 1rem;
transition: 0.6s;
background-color: transparent;
}
span{
position: absolute;
left: 0;
top: 1px;
padding: 10px;
font-size: 1rem;
color: #7f8fa6;
text-transform: uppercase;
pointer-events: none;
transition: 0.6s;
background-color: transparent;
}
input:valid ~ span,
input:focus ~ span{
color: #fff;
transform: translateX(10px) translateY(-7px);
font-size: 0.65rem;
font-weight: 600;
padding: 0 10px;
background: #1c1c1c;
letter-spacing: 0.1rem;
}
input:valid,
input:focus{
color: #fff;
border: 2px solid #fff;
}
}
.release-date {
margin-top: 1rem;
font-size: 1.2rem;
color: #7f8fa6;
font-family: "Roboto", sans-serif;
display: flex;
align-items: center;
.left {
display: flex;
flex-direction: column;
margin-left: 5px;
margin-right: 10px;
}
span {
font-size: .85rem;
}
input {
padding: 8px;
}
}
.file {
margin-top: .5rem;
display: flex;
align-items: center;
span {
font-size: .9rem;
color: #7f8fa6;
font-family: "Roboto", sans-serif;
margin-left: 5px;
margin-right: 10px;
}
input {
padding: 10px;
}
}
.upload-button {
position: absolute;
bottom: 5px;
width: 100%;
margin-top: 1rem;
padding: 10px;
background-color: #7f8fa6;
color: #fff;
font-size: 1rem;
font-family: "Roboto", sans-serif;
border: none;
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
&:hover {
background-color: #fff;
color: #7f8fa6;
}
}
.has-search {
position: relative;
width: 325px;
.search-results {
display: flex;
flex-direction: column;
border: 1px solid white;
width: 100%;
position: absolute;
top: 75%;
background-color: #1c1c1c;
z-index: 2;
border-radius: 5px;
padding: 0;
.result {
border-bottom: 1px solid white;
padding: 10px;
cursor: pointer;
transition: 0.3s;
&:hover {
background-color: #7f8fa6;
}
}
.result:last-child {
border-bottom: none;
}
}
}
}
.error-msg {
padding-top: 10px;
color: red;
display: flex;
justify-content: center;
align-items: center;
svg {
width: 20px;
height: 20px;
margin-right: 5px;
}
}
}