Compare commits

..

90 Commits

Author SHA1 Message Date
f311994058 fixed state management bug 2024-05-12 14:10:05 -07:00
4d734ef594 added position column to playlist_songs table 2024-05-04 19:43:43 -04:00
9c2cd94955 fixed create_playlist popup 2024-04-19 11:57:11 -04:00
d7a3d4abd3 added play and shuffle non functional buttons 2024-04-19 11:36:54 -04:00
1377743aba added a delete playlist song 2024-04-19 11:04:15 -04:00
f56e13eaa9 added a playlist component and a song component 2024-04-18 19:44:12 -04:00
8d704ac6bd seperated playlist component into different files 2024-04-18 12:08:01 -04:00
c66e04643c started work on playlist ui 2024-04-17 19:50:27 -04:00
ac02fb9bd6 commit to work on laptop. 2024-04-16 14:58:45 -04:00
1e59195aff fixed warnings in palylist and sidebar 2024-04-13 16:22:52 -04:00
2c1df1da3f adding playlist to user now works. 2024-04-13 15:51:24 -04:00
5dd0710eb8 Created Playlist 2024-04-13 15:12:50 -04:00
1a9addefa4 created component to add a playlist 2024-04-13 13:50:31 -04:00
79903c779a added a logout button 2024-04-12 19:48:39 -04:00
8556aa21ff add user session check to profile icon 2024-04-12 19:10:45 -04:00
6c74220458 Merge branch '22-create-home-page-2' into 'main'
Created initial home page outline

Closes #22

See merge request libretunes/libretunes!20
2024-04-12 16:54:50 -04:00
14a8f83fe6 Removed unused leptos_dom import 2024-04-12 16:43:04 -04:00
a4fb055e84 Fix use of old icons crate 2024-04-12 16:33:33 -04:00
8e44a48b18 Merge remote-tracking branch 'origin/main' into 22-create-home-page-2 2024-04-12 16:23:28 -04:00
f23b62de98 fixed google font api 2024-04-12 13:24:30 -04:00
eeeae822a5 Merge branch '24-switch-from-actix-to-axum' into 'main'
Switch from Actix to Axum

Closes #24

See merge request libretunes/libretunes!21
2024-04-11 22:47:41 -04:00
90d645a151 Make axum-login crate optional 2024-04-11 17:54:17 -04:00
a659564c91 Run cargo update 2024-04-09 17:18:13 -04:00
d12ca57094 Merge remote-tracking branch 'origin/main' into 22-create-home-page-2 2024-04-06 15:58:49 -04:00
439dd25b94 Update ahash version 2024-04-06 15:46:47 -04:00
46502d39f6 Upgrade to wasm-bindgen 0.2.92 2024-04-06 00:03:20 -04:00
7a39e18451 Update wasm-bindgen to 0.2.92 2024-04-05 17:14:36 -04:00
5f9140c96d modified: Cargo.toml
modified:   src/components/sidebar.rs
	modified:   style/sidebar.scss
2024-04-05 16:49:09 -04:00
b3621de215 Remove duplicate icondata imports 2024-04-02 16:22:08 -04:00
f99dc250f7 Remove unnecessary server function route 2024-04-02 16:22:08 -04:00
825f1cd8df Add check_auth and require_auth server functions 2024-04-02 16:22:04 -04:00
de4e8eb631 Add axum_login authentication layer to router 2024-04-02 01:56:43 -04:00
e7d0769066 Switch to using axum_login in authentication server functions 2024-04-02 01:56:23 -04:00
8bbb37c1e1 Implement auth backend types for axum_login 2024-04-02 01:55:53 -04:00
5d69705239 Add find_user_by_id function 2024-04-02 01:55:00 -04:00
d6eb05514e Use UserCredentials in place of username/password parameters 2024-04-02 01:51:15 -04:00
7023e27b51 Create UserCredentials struct 2024-04-02 01:33:24 -04:00
3a34e8dada Add axum-login crate
Latest version depends on tower-sessions 0.12.0, which breaks tower-sessions-redis-store
2024-04-02 01:26:37 -04:00
48965bc72d Add async-trait crate 2024-04-02 01:26:37 -04:00
8c6ea8948f Add Redis session store layer 2024-04-02 01:26:37 -04:00
64a1c45dad Add tower-sessions-redis-store crate 2024-03-31 14:40:21 -04:00
37db254f50 Downgrade to tower-sessions 0.11 2024-03-31 14:39:29 -04:00
db0d2c6cb9 Serve files in assets/ 2024-03-31 13:08:48 -04:00
1c9dc4bbe9 Add rt-multi-thread feature to tokio 2024-03-31 12:08:35 -04:00
174b23da1d Fix compilation errors from updating axum 2024-03-31 12:08:20 -04:00
66c66f3f4f Upgrade to tower-http 0.5 2024-03-31 12:05:36 -04:00
d5e16c80ea Remove actix packages
Temporarily comment out login and authentication
2024-03-31 12:04:36 -04:00
2e42cc743c Override gloo-net version
In the git repository for gloo packages, gloo-net has been updated to use http 1.0, but this change is not published with the package yet.
2024-03-31 11:56:38 -04:00
c6e8902aa8 Update ahash version
Fixes "unknown feature stdsimd"
2024-03-31 02:24:27 -04:00
c9f4535284 Update to axum 0.7.5 2024-03-31 01:21:24 -04:00
1454c85d3b Update to leptos_axum 0.6 2024-03-31 01:21:13 -04:00
c4c88a2905 Merge branch '21-upgrade-to-leptos-0-6' into 24-switch-from-actix-to-axum 2024-03-31 01:14:23 -04:00
bc94c60240 Fix unused NoCustomError import 2024-03-31 00:49:06 -04:00
013fb6391d Upgrade to leptos 0.6 2024-03-31 00:46:31 -04:00
901aa2ce01 Update to leptos_icons 0.3.0 2024-03-31 00:46:25 -04:00
6bed5e5c55 Merge branch '28-make-ci-build-fail-on-warnings' into 'main'
Make CI build fail on warnings

Closes #28

See merge request libretunes/libretunes!17
2024-03-30 23:26:37 -04:00
7c5f21791c Added simple popup to profile icon
modified:   src/components/dashboard.rs
	modified:   src/components/personal.rs
	modified:   style/dashboard.scss
	modified:   style/home.scss
	modified:   style/personal.scss
2024-03-30 13:22:09 -04:00
93ea42b727 Fix warnings 2024-03-29 21:24:01 -04:00
6cef7ed36d Set deny warnings Rust flag 2024-03-29 21:18:48 -04:00
827d88ac94 Merge branch '13-create-example-environment-variable-file' into 'main'
Add example environment variable file

Closes #13

See merge request libretunes/libretunes!15
2024-03-29 21:10:27 -04:00
fa17a11557 Merge branch '25-fix-incorrect-copyright-line-in-license' into 'main'
Fix incorrect copyright line in license

Closes #25

See merge request libretunes/libretunes!16
2024-03-29 21:03:56 -04:00
f2b68fd8e3 Add example environment variable file 2024-03-29 20:25:16 -04:00
d09caba44c Update copyright year to include 2023 in LICENSE file 2024-03-29 20:18:11 -04:00
5a62f93ba8 Update copyright year and author in LICENSE file 2024-03-29 20:14:50 -04:00
7b6630447f Merge branch '27-switch-to-new-ci-system' into 'main'
Switch to new CI system

Closes #27

See merge request libretunes/libretunes!14
2024-03-29 20:04:33 -04:00
a783fb4e62 Generate random hex value for Postgres password instead of base64 2024-03-29 19:48:29 -04:00
6fc66336b7 Fix review environment URL 2024-03-29 19:27:11 -04:00
27ef4589bf Fix tunnel config script argument order 2024-03-29 17:08:24 -04:00
c736695cea Add export command for environment variables 2024-03-29 16:53:32 -04:00
eb56957a27 Automatically stop review environment after 1 week 2024-03-29 16:53:32 -04:00
0ed4de8bfd Deploy using Docker compose and Cloudflare for review environments 2024-03-26 16:39:14 -04:00
fd4d823cf5 Add misc CICD scripts and compose file 2024-03-26 16:36:50 -04:00
5e2b41da5d Create Docker base template 2024-03-26 16:19:31 -04:00
e211f476a7 added profile section to homepage 2024-03-22 20:25:52 -04:00
126ee5c366 Use Docker runner and dind service for Docker build 2024-03-22 18:13:49 -04:00
a7368aec30 create dashboard/search toggle.
modified:   Cargo.lock
	modified:   Cargo.toml
	modified:   src/app.rs
	modified:   src/components.rs
	new file:   src/components/search.rs
	modified:   src/components/sidebar.rs
	modified:   src/pages/signup.rs
	modified:   style/dashboard.scss
	modified:   style/main.scss
	new file:   style/search.scss
	modified:   style/sidebar.scss
2024-03-14 10:56:35 -04:00
189fdccd93 initialize all components 2024-03-12 20:56:38 -04:00
d50afbf6e7 Add tower-sessions crate 2024-03-01 18:00:19 -05:00
e1e3fe52d4 Handle server functions 2024-03-01 18:00:16 -05:00
fe465e2246 Properly handle router errors
Fixes file serving, including favicon
2024-03-01 18:00:13 -05:00
dcd08ff46e Remove favicon server 2024-03-01 18:00:10 -05:00
acf6d3fc05 Make http crate non-optional 2024-03-01 18:00:06 -05:00
5aaf602e2c Add thiserror crate 2024-03-01 17:59:54 -05:00
57fd838e10 Add file and error handler 2024-03-01 17:59:50 -05:00
939b14403f Add tower-http crate 2024-03-01 17:59:47 -05:00
37d57eee14 Add tower crate 2024-03-01 17:59:44 -05:00
f587a70155 Switch to axum server 2024-03-01 17:59:38 -05:00
213e43e835 Add axum crate 2024-03-01 17:59:32 -05:00
4f999e7338 Add tokio crate 2024-03-01 17:59:27 -05:00
416a8b693a Add leptos_axum package 2024-03-01 17:59:11 -05:00
51 changed files with 2831 additions and 1623 deletions

17
.env.example Normal file
View File

@ -0,0 +1,17 @@
# 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,17 +2,25 @@
build:
needs: []
image: $CI_REGISTRY/libretunes/ops/docker-leptos:latest
variables:
RUSTFLAGS: "-D warnings"
script:
- 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
docker-build:
needs: ["build"]
image: docker:latest
extends: .docker
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 .
# If running on the default branch, tag as latest
- if [ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]; then docker tag
@ -44,35 +52,50 @@ cargo-doc:
paths:
- 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-review:
extends: .argocd
extends: .docker
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
script:
- argocd app sync argocd/libretunes-review-${CI_COMMIT_SHORT_SHA}
- argocd app wait argocd/libretunes-review-${CI_COMMIT_SHORT_SHA}
- apk add curl openssl
- cd cicd
- 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:
name: review/$CI_COMMIT_SHORT_SHA
url: https://review-$CI_COMMIT_SHORT_SHA.libretunes.mregirouard.com
url: https://review-$CI_COMMIT_SHORT_SHA.libretunes.xyz
on_stop: stop-review
auto_stop_in: 1 week
# Stop the review environment
stop-review:
needs: ["start-review"]
extends: .argocd
extends: .docker
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
script:
- argocd app delete argocd/libretunes-review-${CI_COMMIT_SHORT_SHA} --cascade
- apk add jq curl
- ./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:
name: review/$CI_COMMIT_SHORT_SHA
action: stop

2117
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

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

View File

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

22
cicd/add-dns.sh Executable file
View File

@ -0,0 +1,22 @@
#!/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
}' \

19
cicd/create-tunnel-config.sh Executable file
View File

@ -0,0 +1,19 @@
#!/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

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

22
cicd/remove-dns.sh Executable file
View File

@ -0,0 +1,22 @@
#!/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

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

View File

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

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

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

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

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

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

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

View File

@ -1,12 +1,13 @@
use crate::error_template::{AppError, ErrorTemplate};
use crate::pages::login::*;
use crate::pages::signup::*;
use crate::playbar::PlayBar;
use crate::playstatus::PlayStatus;
use crate::queue::Queue;
use crate::searchbar::SearchBar;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use crate::pages::login::*;
use crate::pages::signup::*;
use leptos::leptos_dom::*;
#[component]
pub fn App() -> impl IntoView {
@ -22,11 +23,17 @@ pub fn App() -> impl IntoView {
<Title text="LibreTunes"/>
// content for this welcome page
<Router>
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
<Route path="/*any" view=NotFound/>
<Route path="/login" view=Login />
<Route path="/signup" view=Signup />
</Routes>
@ -35,18 +42,52 @@ pub fn App() -> impl IntoView {
}
}
use crate::components::dashboard::*;
use crate::components::personal::*;
use crate::components::search::*;
use crate::components::sidebar::*;
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
let mut play_status = PlayStatus::default();
use crate::auth::check_auth;
let play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status);
let (logged_in, set_logged_in) = create_signal(false);
let (dashboard_open, set_dashboard_open) = create_signal(true);
create_effect(move |_| {
spawn_local(async move {
let auth_result = check_auth().await;
if let Err(err) = auth_result {
log!("Error checking auth: {:?}", err);
} else if let Ok(true) = auth_result {
log!("User is logged in");
set_logged_in.update(|value| *value = true);
} else if let Ok(false) = auth_result {
log!("User is not logged in");
set_logged_in.update(|value| *value = false);
}
});
});
view! {
<div class="home">
<PlayBar status=play_status/>
<Queue status=play_status/>
<SearchBar status=play_status/>
</div>
<div class="home-container">
<Sidebar setter=set_dashboard_open active=dashboard_open logged_in=logged_in/>
<Show
when=move || {dashboard_open() == true}
fallback=move || view! { <Search /> }
>
<Dashboard />
</Show>
<Personal logged_in=logged_in/>
<PlayBar status=play_status/>
<Queue status=play_status/>
</div>
}
}
@ -63,8 +104,8 @@ fn NotFound() -> impl IntoView {
{
// this can be done inline because it's synchronous
// if it were async, we'd use a server function
let resp = expect_context::<leptos_actix::ResponseOptions>();
resp.set_status(actix_web::http::StatusCode::NOT_FOUND);
let resp = expect_context::<leptos_axum::ResponseOptions>();
resp.set_status(axum::http::StatusCode::NOT_FOUND);
}
view! {

View File

@ -1,5 +1,18 @@
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::users::UserCredentials;
/// Create a new user and log them in
/// Takes in a NewUser struct, with the password in plaintext
@ -8,10 +21,6 @@ use crate::models::User;
pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
use crate::users::create_user;
use leptos_actix::extract;
use actix_web::{HttpMessage, HttpRequest};
use actix_identity::Identity;
// Ensure the user has no id
let new_user = User {
id: None,
@ -19,53 +28,95 @@ pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
};
create_user(&new_user).await
.map_err(|e| ServerFnError::ServerError(format!("Error creating user: {}", e)))?;
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error creating user: {}", e)))?;
extract(|request: HttpRequest| async move {
Identity::login(&request.extensions(), new_user.username.clone())
}).await??;
let mut auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
Ok(())
let credentials = UserCredentials {
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
/// Takes in a username or email and a password in plaintext
/// Returns a Result with a boolean indicating if the login was successful
#[server(endpoint = "login")]
pub async fn login(username_or_email: String, password: String) -> Result<bool, ServerFnError> {
pub async fn login(credentials: UserCredentials) -> Result<bool, ServerFnError> {
use crate::users::validate_user;
use actix_web::{HttpMessage, HttpRequest};
use actix_identity::Identity;
use leptos_actix::extract;
let possible_user = validate_user(username_or_email, password).await
.map_err(|e| ServerFnError::ServerError(format!("Error validating user: {}", e)))?;
let mut auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
let user = match possible_user {
Some(user) => user,
None => return Ok(false)
};
let user = validate_user(credentials).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error validating user: {}", e)))?;
extract(|request: HttpRequest| async move {
Identity::login(&request.extensions(), user.username.clone())
}).await??;
Ok(true)
if let Some(user) = user {
auth_session.login(&user).await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error logging in user: {}", e)))?;
Ok(true)
} else {
Ok(false)
}
}
/// Log a user out
/// Returns a Result with the error message if the user could not be logged out
#[server(endpoint = "logout")]
pub async fn logout() -> Result<(), ServerFnError> {
use leptos_actix::extract;
use actix_identity::Identity;
let mut auth_session = extract::<AuthSession<AuthBackend>>().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
extract(|user: Option<Identity>| async move {
if let Some(user) = user {
user.logout();
}
}).await?;
auth_session.logout().await
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
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")))
}
})
}

41
src/auth_backend.rs Normal file
View File

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

7
src/components.rs Normal file
View File

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

View File

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

View File

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

View File

@ -0,0 +1,72 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
#[component]
pub fn Personal(logged_in: ReadSignal<bool>) -> impl IntoView {
view! {
<div class=" personal-container">
<Profile logged_in=logged_in/>
</div>
}
}
#[component]
pub fn Profile(logged_in: ReadSignal<bool>) -> impl IntoView {
let (dropdown_open, set_dropdown_open) = create_signal(false);
let open_dropdown = move |_| {
set_dropdown_open.update(|value| *value = !*value);
log!("opened dropdown");
};
view! {
<div class="profile-container">
<div class="profile-icon" on:click=open_dropdown>
<Icon icon=icondata::CgProfile />
</div>
<div class="dropdown-container" style={move || if dropdown_open() {"display: flex"} else {"display: none"}}>
<Show
when=move || {logged_in() == true}
fallback=move || view!{<DropDownNotLoggedIn />}
>
<DropDownLoggedIn/>
</Show>
</div>
</div>
}
}
#[component]
pub fn DropDownNotLoggedIn() -> impl IntoView {
view! {
<div class="dropdown-not-logged">
<h1>Not Logged in!</h1>
<a href="/login"><button class="auth-button">Log In</button></a>
<a href="/signup"><button class="auth-button">Sign up</button></a>
</div>
}
}
#[component]
pub fn DropDownLoggedIn() -> impl IntoView {
use crate::auth::logout;
let logout = move |_ev: leptos::ev::MouseEvent| {
spawn_local(async move {
let _logout_result = logout().await;
if let Err(err) = _logout_result {
log!("Error logging out: {:?}", err);
} else {
log!("Logged out Successfully!");
leptos_router::use_navigate()("/login", Default::default());
}
});
};
view! {
<div class="dropdown-logged-in">
<h1>Logged in!</h1>
<button on:click=logout class="auth-button">Log Out</button>
</div>
}
}

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

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

View File

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

10
src/components/search.rs Normal file
View File

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

42
src/components/sidebar.rs Normal file
View File

@ -0,0 +1,42 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::components::playlists::Playlists;
#[component]
pub fn Sidebar(setter: WriteSignal<bool>, active: ReadSignal<bool>, logged_in:ReadSignal<bool>) -> impl IntoView {
let open_dashboard = move |_| {
setter.update(|value| *value = true);
log!("open dashboard");
};
let open_search = move |_| {
setter.update(|value| *value = false);
log!("open search");
};
view! {
<div class="sidebar-container">
<div class="sidebar-top-container">
<h2 class="header">LibreTunes</h2>
<div class="buttons" on:click=open_dashboard style={move || if active() {"color: #e1e3e1"} else {""}} >
<Icon icon=icondata::OcHomeFillLg />
<h1>Dashboard</h1>
</div>
<div class="buttons" on:click=open_search style={move || if !active() {"color: #e1e3e1"} else {""}}>
<Icon icon=icondata::BiSearchRegular />
<h1>Search</h1>
</div>
</div>
<div class="sidebar-bottom-container">
<Show
when=move || {logged_in() == true}
fallback=move|| view!{<h1>LOG IN PLEASE</h1>}
>
<Playlists />
</Show>
</div>
</div>
}
}

View File

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

73
src/error_template.rs Normal file
View File

@ -0,0 +1,73 @@
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>
}
}
/>
}
}

40
src/fileserv.rs Normal file
View File

@ -0,0 +1,40 @@
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,13 +8,17 @@ pub mod queue;
pub mod song;
pub mod models;
pub mod pages;
pub mod components;
pub mod users;
pub mod search;
pub mod searchbar;
pub mod fileserv;
pub mod error_template;
pub mod api;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
if #[cfg(feature = "ssr")] {
pub mod auth_backend;
pub mod schema;
}
}
@ -27,7 +31,6 @@ if #[cfg(feature = "hydrate")] {
#[wasm_bindgen]
pub fn hydrate() {
use app::*;
use leptos::*;
console_error_panic_hook::set_once();

View File

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

View File

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

View File

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

View File

@ -1,10 +1,7 @@
use crate::auth::signup;
use crate::models::User;
use leptos::ev::input;
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::AiIcon::*;
use leptos_icons::IoIcon::*;
use leptos_icons::*;
#[component]
@ -15,8 +12,6 @@ pub fn Signup() -> impl IntoView {
let (show_password, set_show_password) = create_signal(false);
let navigate = leptos_router::use_navigate();
let toggle_password = move |_| {
set_show_password.update(|show_password| *show_password = !*show_password);
log!("showing password");
@ -49,7 +44,7 @@ pub fn Signup() -> impl IntoView {
view! {
<div class="auth-page-container">
<div class="signup-container">
<a class="return" href="/"><Icon icon=Icon::from(IoReturnUpBackSharp) /></a>
<a class="return" href="/"><Icon icon=icondata::IoReturnUpBackSharp /></a>
<div class="header">
<h1>LibreTunes</h1>
</div>
@ -86,10 +81,10 @@ pub fn Signup() -> impl IntoView {
<i></i>
<Show
when=move || {show_password() == false}
fallback=move || view!{ <button on:click=toggle_password class="password-visibility"> <Icon icon=Icon::from(AiEyeInvisibleFilled) /></button> /> }
fallback=move || view!{ <button on:click=toggle_password class="password-visibility"> <Icon icon=icondata::AiEyeInvisibleFilled /></button> /> }
>
<button on:click=toggle_password class="password-visibility">
<Icon icon=Icon::from(AiEyeFilled) />
<Icon icon=icondata::AiEyeFilled />
</button>
</Show>
</div>

View File

@ -1,12 +1,8 @@
use std::time::Duration;
use crate::playstatus::PlayStatus;
use leptos::ev::MouseEvent;
use leptos::html::{Audio, Div};
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::BsIcon::*;
use leptos_icons::RiIcon::*;
use leptos_icons::*;
/// Width and height of the forward/backward skip buttons
@ -195,9 +191,9 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
let icon = Signal::derive(move || {
status.with(|status| {
if status.playing {
Icon::from(BsPauseFill)
icondata::BsPauseFill
} else {
Icon::from(BsPlayFill)
icondata::BsPlayFill
}
})
});
@ -206,7 +202,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
<div class="playcontrols" align="center">
<button on:click=skip_back on:mousedown=prevent_focus>
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=Icon::from(BsSkipStartFill) />
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=icondata::BsSkipStartFill />
</button>
<button on:click=toggle_play on:mousedown=prevent_focus>
@ -214,7 +210,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
</button>
<button on:click=skip_forward on:mousedown=prevent_focus>
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=Icon::from(BsSkipEndFill) />
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=icondata::BsSkipEndFill />
</button>
</div>
@ -339,7 +335,7 @@ fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
view! {
<div class="queue-toggle">
<button on:click=update_queue on:mousedown=prevent_focus>
<Icon class="controlbtn" width=QUEUE_BTN_SIZE height=QUEUE_BTN_SIZE icon=Icon::from(RiPlayListMediaFill) />
<Icon class="controlbtn" width=QUEUE_BTN_SIZE height=QUEUE_BTN_SIZE icon=icondata::RiPlayListMediaFill />
</button>
</div>
}
@ -350,7 +346,7 @@ fn QueueToggle(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
let _arrow_key_handle = window_event_listener(ev::keydown, move |e: ev::KeyboardEvent| {
if e.key() == "ArrowRight" && status.with_untracked(|status| status.search_active) == false {
if e.key() == "ArrowRight" {
e.prevent_default();
log!("Right arrow key pressed, skipping forward by {} seconds", ARROW_KEY_SKIP_TIME);
@ -363,7 +359,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
error!("Unable to skip forward: Unable to get current duration");
}
} else if e.key() == "ArrowLeft" && status.with_untracked(|status| status.search_active) == false {
} else if e.key() == "ArrowLeft" {
e.prevent_default();
log!("Left arrow key pressed, skipping backward by {} seconds", ARROW_KEY_SKIP_TIME);
@ -380,7 +376,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// Listen for space bar presses to play/pause
let _space_bar_handle = window_event_listener(ev::keypress, move |e: ev::KeyboardEvent| {
if e.key() == " " && status.with_untracked(|status| status.search_active) == false {
if e.key() == " " {
e.prevent_default();
log!("Space bar pressed, toggling play/pause");

View File

@ -11,8 +11,6 @@ pub struct PlayStatus {
pub playing: bool,
/// Whether or not the queue is open
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
pub audio_player: Option<NodeRef<Audio>>,
/// A queue of songs that have been played, ordered from oldest to newest
@ -58,7 +56,6 @@ impl Default for PlayStatus {
Self {
playing: false,
queue_open: false,
search_active: false,
audio_player: None,
history: VecDeque::new(),
queue: VecDeque::new(),

View File

@ -4,7 +4,6 @@ use leptos::ev::MouseEvent;
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use leptos_icons::CgIcon::*;
use leptos::ev::DragEvent;
const RM_BTN_SIZE: &str = "2.5rem";
@ -106,7 +105,7 @@ pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
<p>Playing</p>
}>
<button on:click=move |_| remove_song(index) on:mousedown=prevent_focus>
<Icon class="remove-song" width=RM_BTN_SIZE height=RM_BTN_SIZE icon=Icon::from(CgTrash) />
<Icon class="remove-song" width=RM_BTN_SIZE height=RM_BTN_SIZE icon=icondata::CgTrash />
</button>
</Show>
</div>

View File

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

View File

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

View File

@ -1,154 +0,0 @@
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]
pub fn Song(song_image_path: String, song_title: String, song_artist: String) -> impl IntoView {
view!{
<div class="song">
<div class="queue-song">
<img src={song_image_path} alt={song_title.clone()} />
<div class="song-info">
<div class="queue-song-info">
<h3>{song_title}</h3>
<p>{song_artist}</p>
</div>

View File

@ -14,19 +14,42 @@ cfg_if::cfg_if! {
}
use leptos::*;
use serde::{Serialize, Deserialize};
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
/// 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(username_or_email: String) -> Result<Option<User>, ServerFnError> {
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
let db_con = &mut get_db_conn();
let user = users.filter(username.eq(username_or_email.clone())).or_filter(email.eq(username_or_email))
.first::<User>(db_con).optional()
.map_err(|e| ServerFnError::ServerError(format!("Error getting user from database: {}", e)))?;
.map_err(|e| ServerFnError::<NoCustomError>::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)
}
@ -36,13 +59,14 @@ pub async fn find_user(username_or_email: String) -> Result<Option<User>, Server
#[cfg(feature = "ssr")]
pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> {
use crate::schema::users::dsl::*;
use leptos::server_fn::error::NoCustomError;
let new_password = new_user.password.clone()
.ok_or(ServerFnError::ServerError(format!("No password provided for user {}", new_user.username)))?;
.ok_or(ServerFnError::<NoCustomError>::ServerError(format!("No password provided for user {}", new_user.username)))?;
let salt = SaltString::generate(&mut OsRng);
let password_hash = Pbkdf2.hash_password(new_password.as_bytes(), &salt)
.map_err(|_| ServerFnError::ServerError("Error hashing password".to_string()))?.to_string();
.map_err(|_| ServerFnError::<NoCustomError>::ServerError("Error hashing password".to_string()))?.to_string();
let new_user = User {
password: Some(password_hash),
@ -52,7 +76,7 @@ pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> {
let db_con = &mut get_db_conn();
diesel::insert_into(users).values(&new_user).execute(db_con)
.map_err(|e| ServerFnError::ServerError(format!("Error creating user: {}", e)))?;
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error creating user: {}", e)))?;
Ok(())
}
@ -60,9 +84,11 @@ pub async fn create_user(new_user: &User) -> Result<(), ServerFnError> {
/// 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
#[cfg(feature = "ssr")]
pub async fn validate_user(username_or_email: String, password: String) -> Result<Option<User>, ServerFnError> {
let db_user = find_user(username_or_email.clone()).await
.map_err(|e| ServerFnError::ServerError(format!("Error getting user from database: {}", e)))?;
pub async fn validate_user(credentials: UserCredentials) -> Result<Option<User>, ServerFnError> {
use leptos::server_fn::error::NoCustomError;
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
let db_user = match db_user {
@ -71,18 +97,18 @@ pub async fn validate_user(username_or_email: String, password: String) -> Resul
};
let db_password = db_user.password.clone()
.ok_or(ServerFnError::ServerError(format!("No password found for user {}", db_user.username)))?;
.ok_or(ServerFnError::<NoCustomError>::ServerError(format!("No password found for user {}", db_user.username)))?;
let password_hash = PasswordHash::new(&db_password)
.map_err(|e| ServerFnError::ServerError(format!("Error hashing supplied password: {}", e)))?;
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error hashing supplied password: {}", e)))?;
match Pbkdf2.verify_password(password.as_bytes(), &password_hash) {
match Pbkdf2.verify_password(credentials.password.as_bytes(), &password_hash) {
Ok(()) => {},
Err(Error::Password) => {
return Ok(None);
},
Err(e) => {
return Err(ServerFnError::ServerError(format!("Error verifying password: {}", e)));
return Err(ServerFnError::<NoCustomError>::ServerError(format!("Error verifying password: {}", e)));
}
}

10
style/dashboard.scss Normal file
View File

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

16
style/home.scss Normal file
View File

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

View File

@ -1,20 +1,18 @@
@import 'playbar.scss';
@import 'theme.scss';
@import 'queue.scss';
@import 'login.scss';
@import 'signup.scss';
@import 'song.scss';
@import 'searchbar.scss';
@import "playbar.scss";
@import "theme.scss";
@import "queue.scss";
@import "login.scss";
@import "signup.scss";
@import "sidebar.scss";
@import "dashboard.scss";
@import 'home.scss';
@import 'search.scss';
@import 'personal.scss';
body {
font-family: sans-serif;
background-color: $background-color;
color: $text-controls-color;
margin: 0;
padding: 0;
}
.home {
width: 100%;
height: 100%;
font-family: sans-serif;
background-color: $background-color;
color: $text-controls-color;
margin: 0;
padding: 0;
}

74
style/personal.scss Normal file
View File

@ -0,0 +1,74 @@
@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,12 +5,10 @@
top: 0;
right: 0;
width: 400px;
height: calc(100% - 87px); /* Adjust height to fit the queue */
height: calc(100% - 78.9px); /* Adjust height to fit the queue */
background-color: #424242; /* Queue background color */
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
overflow-y: auto; /* Add scroll bar when queue is too long */
margin: 5px;
border-radius: 5px;
.queue-header {
background-color: #333; /* Header background color */
@ -32,6 +30,31 @@
padding-top: 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 {
background: none;
border: none;

6
style/search.scss Normal file
View File

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

View File

@ -1,99 +0,0 @@
@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;
}
}
}
}
}
}

343
style/sidebar.scss Normal file
View File

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

View File

@ -1,22 +0,0 @@
.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,3 +1,7 @@
@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;
$accent-color: #4032a8;
$text-controls-color: #e0e0e0;
@ -7,12 +11,6 @@ $play-bar-background-color: #212121;
$play-grad-start: #0a0533;
$play-grad-end: $accent-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-containers: white;