Compare commits
261 Commits
32-impleme
...
main
Author | SHA1 | Date | |
---|---|---|---|
504f04784d | |||
f2890825ec | |||
93b0d2dc60 | |||
4e979bac07 | |||
8f61260946 | |||
6aedd7747e | |||
8f096b1ebb | |||
cecd131737 | |||
31f9aa0f96 | |||
7e7127c2a0 | |||
3c18c8c21c | |||
4692c1699d | |||
56d84c8b3a | |||
43c9b659b2 | |||
f5c28d83ce | |||
be861ff1b5 | |||
817529cbcc | |||
832ba7a03b | |||
deca995de1 | |||
3ec25881b9 | |||
5cb0f4a17b | |||
9fb3cd745b | |||
a7905624a6 | |||
aaa9db93fb | |||
fac33bb1f1 | |||
97f50b38c5 | |||
5ecb71ce9d | |||
d1c8615105 | |||
6592d66f87 | |||
51a9e8c4b3 | |||
1a1516ff92 | |||
c9d3053c5a | |||
aced8723c2 | |||
ede248d961 | |||
930618dcad | |||
9b48fc0204 | |||
dfbb217988 | |||
954cc0edce | |||
e5ce0eab76 | |||
45eb7191f0 | |||
21a17a8eb5 | |||
fcd987d433 | |||
dd14aa0b4d | |||
3b6035dd71 | |||
22cee4a265 | |||
b25cb4549c | |||
b1a62ee284 | |||
0c1bab9fbb | |||
190df0edfd | |||
73b4b7674e | |||
3d1dc94b06 | |||
a3b3174306 | |||
f633cffe69 | |||
cf6f7b7db7 | |||
8f01ff24d8 | |||
f0f34d4abe | |||
d42737f856 | |||
47fc35814d | |||
fe21785f2d | |||
c6024a7457 | |||
41327c8ed6 | |||
d09060959a | |||
d8fab0e068 | |||
7f298f75ce | |||
74044f2e17 | |||
568f6ada0e | |||
7a1ffaad47 | |||
b800e4ee47 | |||
6dcbba2588 | |||
820a1d816a | |||
f23430af73 | |||
ef5576ab3f | |||
833393cb3a | |||
39dd8099cd | |||
5011cda8fa | |||
89433df8b6 | |||
ddcb4a5be7 | |||
414489d1be | |||
186c622e6f | |||
35abbe19ee | |||
2b380d7787 | |||
8ac3a87c58 | |||
43a5b519fd | |||
251d567863 | |||
1f70da1747 | |||
a70de76c4d | |||
f1affc66bc | |||
e60243e50c | |||
0335e3d255 | |||
81b1490cce | |||
e66b5e4976 | |||
0453aef37d | |||
4e4c94a189 | |||
23bfb510c1 | |||
ff24f68eed | |||
6aa933be09 | |||
fe1b76e6e4 | |||
acf15961cd | |||
f299254d55 | |||
14aa4d236e | |||
df01bafbd1 | |||
f1e177c7b0 | |||
88e2a229a4 | |||
2d7b91413b | |||
c2ebd8307f | |||
2be665c549 | |||
3cfcacc9ba | |||
f39d93bd0c | |||
f104a14f98 | |||
f78066d7a8 | |||
071dcad0cc | |||
cdffd2c5eb | |||
3149f65a97 | |||
e90ea56d14 | |||
b222b7911f | |||
0550b18d77 | |||
36e7a5827b | |||
134b425ce6 | |||
c678d93661 | |||
c18bf277b9 | |||
097b1fc491 | |||
f02a22d805 | |||
553e24800b | |||
2793391f00 | |||
cce9b946ec | |||
51858593c2 | |||
2bb9b3bdd7 | |||
ab50826d31 | |||
a43955726a | |||
e03853929f | |||
2c71e065b7 | |||
20a3c0c7df | |||
b2f138e7e9 | |||
33aa285deb | |||
4105d0cedb | |||
414c1f0e20 | |||
9927b94d59 | |||
b9551e5bee | |||
73910a087a | |||
236c75492a | |||
ec76269367 | |||
c92d68dddf | |||
8fd064dffc | |||
a83fb9dea5 | |||
bf89838297 | |||
b7e5327903 | |||
8fea5fcec7 | |||
266bba05aa | |||
86f9b6fbb3 | |||
da45a503ac | |||
074f866e5f | |||
cb0936003c | |||
d66849c6cb | |||
b54ecb5b27 | |||
0ee61f288f | |||
8c516e3070 | |||
22f3749ee4 | |||
e55656c0e6 | |||
18cbb0017f | |||
53cde3bed6 | |||
eab011070d | |||
9d6013b8a4 | |||
fa811350ae | |||
7f4108e1c5 | |||
906b5bd9dd | |||
7cb556e5ef | |||
bab819822d | |||
0c54f0aeb8 | |||
afbcc65457 | |||
e5a6e8f44e | |||
d45f102be7 | |||
74b34b1e54 | |||
2ea3979a89 | |||
21bb2d127f | |||
76631126de | |||
f8bbe319bd | |||
ffad799f72 | |||
c72d4aee18 | |||
8a474077da | |||
6202b287f0 | |||
6b8c8d41e4 | |||
4aa90cdefb | |||
ee70b1080e | |||
62def56a41 | |||
0c64865cd9 | |||
cc11de4f3d | |||
81f0b9310f | |||
4513335784 | |||
fa26ee40ed | |||
c27ad19499 | |||
6ae55d5cfc | |||
7bcb5f8c04 | |||
9a462d5ee9 | |||
5cc504b4d6 | |||
eb4dcd4776 | |||
355c791ea7 | |||
b0edd2174e | |||
3978526231 | |||
0adf294cfc | |||
e7e7a8175e | |||
952fb93e1e | |||
1633d8c1a5 | |||
b4054aa2b7 | |||
3934a25900 | |||
26c34e0012 | |||
522658c0dc | |||
3c9ae521b1 | |||
4958d3a881 | |||
965bf5a457 | |||
8ffe09381c | |||
12384b5a75 | |||
bf9067aa43 | |||
7b43906632 | |||
4685861af3 | |||
df78afbe60 | |||
caefc46fcc | |||
94d62ea2d5 | |||
893c411c7f | |||
618b7d65ce | |||
78d8e1243d | |||
955fc84412 | |||
cc4aee4ab4 | |||
5775d3148b | |||
714fbc596a | |||
ff43b3f7e8 | |||
af66381f5f | |||
683f979bc7 | |||
f4908ad3b3 | |||
b1cc0f156c | |||
ec43ab472d | |||
eebd58f5a6 | |||
e411ab9eee | |||
775c7eff3a | |||
2ed67e5545 | |||
08f1b95c18 | |||
7a750b60aa | |||
2b9d849578 | |||
28ff98ab32 | |||
a0da89204c | |||
c07237ad8a | |||
727029b757 | |||
8a959d530d | |||
7abfbaf600 | |||
161ea5f9c2 | |||
353a8e3a9c | |||
5d7ac2bb80 | |||
695f404ba8 | |||
79ba191415 | |||
3338cc2662 | |||
60ad643669 | |||
490772654d | |||
b2fd8dc8e5 | |||
91812f4695 | |||
9b1ea51896 | |||
6bf08b7507 | |||
04e0a66122 | |||
b6066e2d3e | |||
241389e5f7 | |||
557c189a17 | |||
4f6f3f90c1 | |||
7062c75013 |
@ -8,3 +8,7 @@
|
|||||||
!/style
|
!/style
|
||||||
!/Cargo.lock
|
!/Cargo.lock
|
||||||
!/Cargo.toml
|
!/Cargo.toml
|
||||||
|
!/ascii_art.txt
|
||||||
|
!/flake.nix
|
||||||
|
!/flake.lock
|
||||||
|
!/rust-toolchain.toml
|
||||||
|
@ -15,3 +15,7 @@ DATABASE_URL=postgresql://libretunes:password@localhost:5432/libretunes
|
|||||||
# POSTGRES_HOST=localhost
|
# POSTGRES_HOST=localhost
|
||||||
# POSTGRES_PORT=5432
|
# POSTGRES_PORT=5432
|
||||||
# POSTGRES_DB=libretunes
|
# POSTGRES_DB=libretunes
|
||||||
|
|
||||||
|
LIBRETUNES_AUDIO_PATH=assets/audio
|
||||||
|
LIBRETUNES_IMAGE_PATH=assets/images
|
||||||
|
LIBRETUNES_DISABLE_SIGNUP=true
|
||||||
|
101
.gitea/workflows/push.yaml
Normal file
101
.gitea/workflows/push.yaml
Normal file
@ -0,0 +1,101 @@
|
|||||||
|
name: Push Workflows
|
||||||
|
on: push
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: libretunes-cicd
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Use Cache
|
||||||
|
uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Build project
|
||||||
|
run: cargo-leptos build
|
||||||
|
|
||||||
|
docker-build:
|
||||||
|
runs-on: ubuntu-latest-docker
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v3
|
||||||
|
with:
|
||||||
|
endpoint: ${{ env.docker_endpoint }}
|
||||||
|
- name: Login to Gitea container registry
|
||||||
|
uses: docker/login-action@v3
|
||||||
|
with:
|
||||||
|
registry: ${{ env.registry }}
|
||||||
|
username: ${{ env.actions_user }}
|
||||||
|
password: ${{ secrets.CONTAINER_REGISTRY_TOKEN }}
|
||||||
|
- name: Get Image Name
|
||||||
|
id: get-image-name
|
||||||
|
run: |
|
||||||
|
echo "IMAGE_NAME=$(echo ${{ env.registry }}/${{ gitea.repository }} | tr '[:upper:]' '[:lower:]')" >> $GITHUB_OUTPUT
|
||||||
|
- name: Build and push Docker image
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
with:
|
||||||
|
push: true
|
||||||
|
tags: "${{ steps.get-image-name.outputs.IMAGE_NAME }}:${{ gitea.sha }}"
|
||||||
|
cache-to: mode=max
|
||||||
|
- name: Build and push Docker image with "latest" tag
|
||||||
|
uses: docker/build-push-action@v5
|
||||||
|
if: gitea.ref == 'refs/heads/main'
|
||||||
|
with:
|
||||||
|
push: true
|
||||||
|
tags: "${{ steps.get-image-name.outputs.IMAGE_NAME }}:latest"
|
||||||
|
cache-to: mode=max
|
||||||
|
|
||||||
|
test:
|
||||||
|
runs-on: libretunes-cicd
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Use Cache
|
||||||
|
uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Test project
|
||||||
|
run: cargo test --all-targets --all-features
|
||||||
|
|
||||||
|
leptos-test:
|
||||||
|
runs-on: libretunes-cicd
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Use Cache
|
||||||
|
uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Run Leptos tests
|
||||||
|
run: cargo-leptos test
|
||||||
|
|
||||||
|
docs:
|
||||||
|
runs-on: libretunes-cicd
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
- name: Use Cache
|
||||||
|
uses: Swatinem/rust-cache@v2
|
||||||
|
- name: Generate docs
|
||||||
|
run: cargo doc --no-deps
|
||||||
|
- name: Upload docs
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: docs
|
||||||
|
path: target/doc
|
||||||
|
|
||||||
|
nix-build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Update Package Lists
|
||||||
|
run: apt update
|
||||||
|
- name: Install Nix
|
||||||
|
run: apt install -y nix-bin
|
||||||
|
- name: Restore and cache Nix store
|
||||||
|
uses: nix-community/cache-nix-action@v5
|
||||||
|
with:
|
||||||
|
primary-key: nix-build
|
||||||
|
- name: Build project with Nix
|
||||||
|
run: nix build --experimental-features 'nix-command flakes' git+$GITHUB_SERVER_URL/$GITHUB_REPOSITORY.git?ref=$GITHUB_REF_NAME#default --no-write-lock-file
|
||||||
|
|
||||||
|
env:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: Print Environment
|
||||||
|
run: env
|
5
.gitignore
vendored
5
.gitignore
vendored
@ -24,9 +24,14 @@ playwright/.cache/
|
|||||||
*.jpeg
|
*.jpeg
|
||||||
*.png
|
*.png
|
||||||
*.gif
|
*.gif
|
||||||
|
*.webp
|
||||||
|
|
||||||
# Environment variables
|
# Environment variables
|
||||||
.env
|
.env
|
||||||
|
|
||||||
# Sass cache
|
# Sass cache
|
||||||
.sass-cache
|
.sass-cache
|
||||||
|
|
||||||
|
# Nix-related files
|
||||||
|
.direnv/
|
||||||
|
result/
|
||||||
|
101
.gitlab-ci.yml
101
.gitlab-ci.yml
@ -1,101 +0,0 @@
|
|||||||
# Build the project
|
|
||||||
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"]
|
|
||||||
extends: .docker
|
|
||||||
script:
|
|
||||||
- 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
|
|
||||||
$CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA
|
|
||||||
$CI_REGISTRY_IMAGE:latest; fi
|
|
||||||
- docker push $CI_REGISTRY_IMAGE --all-tags
|
|
||||||
|
|
||||||
# Run leptos tests
|
|
||||||
leptos-tests:
|
|
||||||
needs: ["build"]
|
|
||||||
image: $CI_REGISTRY/libretunes/ops/docker-leptos:latest
|
|
||||||
script:
|
|
||||||
- cargo-leptos test
|
|
||||||
|
|
||||||
# Run all tests
|
|
||||||
tests:
|
|
||||||
needs: ["build"]
|
|
||||||
image: $CI_REGISTRY/libretunes/ops/docker-leptos:latest
|
|
||||||
script:
|
|
||||||
- cargo test --all-targets --all-features
|
|
||||||
|
|
||||||
# Generate docs
|
|
||||||
cargo-doc:
|
|
||||||
needs: []
|
|
||||||
image: rust:slim
|
|
||||||
script:
|
|
||||||
- cargo doc --no-deps
|
|
||||||
artifacts:
|
|
||||||
paths:
|
|
||||||
- target/doc
|
|
||||||
|
|
||||||
# Start the review environment
|
|
||||||
start-review:
|
|
||||||
extends: .docker
|
|
||||||
rules:
|
|
||||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
|
||||||
when: manual
|
|
||||||
script:
|
|
||||||
- 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.xyz
|
|
||||||
on_stop: stop-review
|
|
||||||
auto_stop_in: 1 week
|
|
||||||
|
|
||||||
# Stop the review environment
|
|
||||||
stop-review:
|
|
||||||
needs: ["start-review"]
|
|
||||||
extends: .docker
|
|
||||||
rules:
|
|
||||||
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
|
|
||||||
when: manual
|
|
||||||
allow_failure: true
|
|
||||||
script:
|
|
||||||
- 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
|
|
700
Cargo.lock
generated
700
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
57
Cargo.toml
57
Cargo.toml
@ -8,59 +8,74 @@ build = "src/build.rs"
|
|||||||
crate-type = ["cdylib", "rlib"]
|
crate-type = ["cdylib", "rlib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
console_error_panic_hook = "0.1"
|
console_error_panic_hook = { version = "0.1", optional = true }
|
||||||
cfg-if = "1"
|
cfg-if = "1"
|
||||||
http = "1.0"
|
http = { version = "1.0", default-features = false }
|
||||||
leptos = { version = "0.6", features = ["nightly"] }
|
leptos = { version = "0.6", default-features = false, features = ["nightly"] }
|
||||||
leptos_meta = { version = "0.6", features = ["nightly"] }
|
leptos_meta = { version = "0.6", features = ["nightly"] }
|
||||||
leptos_axum = { version = "0.6", optional = true }
|
leptos_axum = { version = "0.6", optional = true }
|
||||||
leptos_router = { version = "0.6", features = ["nightly"] }
|
leptos_router = { version = "0.6", features = ["nightly"] }
|
||||||
wasm-bindgen = "=0.2.92"
|
wasm-bindgen = { version = "=0.2.96", default-features = false, optional = true }
|
||||||
leptos_icons = { version = "0.3.0" }
|
leptos_icons = { version = "0.3.0" }
|
||||||
icondata = { version = "0.3.0" }
|
icondata = { version = "0.3.0" }
|
||||||
dotenv = { version = "0.15.0", optional = true }
|
diesel = { version = "2.1.4", features = ["postgres", "r2d2", "chrono"], 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 = { versions = "1.0.195", features = ["derive"] }
|
serde = { version = "1.0.195", features = ["derive"], default-features = false }
|
||||||
openssl = { version = "0.10.63", optional = true }
|
openssl = { version = "0.10.63", optional = true }
|
||||||
time = { version = "0.3.34", features = ["serde"] }
|
|
||||||
diesel_migrations = { version = "2.1.0", optional = true }
|
diesel_migrations = { version = "2.1.0", optional = true }
|
||||||
pbkdf2 = { version = "0.12.2", features = ["simple"], optional = true }
|
pbkdf2 = { version = "0.12.2", features = ["simple"], optional = true }
|
||||||
futures = { version = "0.3.30", default-features = false, optional = true }
|
|
||||||
tokio = { version = "1", optional = true, features = ["rt-multi-thread"] }
|
tokio = { version = "1", optional = true, features = ["rt-multi-thread"] }
|
||||||
axum = { version = "0.7.5", optional = true }
|
axum = { version = "0.7.5", features = ["tokio", "http1"], default-features = false, optional = true }
|
||||||
tower = { veresion = "0.4.13", optional = true }
|
tower = { version = "0.5.1", optional = true, features = ["util"] }
|
||||||
tower-http = { version = "0.5", optional = true, features = ["fs"] }
|
tower-http = { version = "0.6.1", optional = true, features = ["fs"] }
|
||||||
thiserror = "1.0.57"
|
thiserror = "1.0.57"
|
||||||
tower-sessions = { version = "0.11", default-features = false }
|
|
||||||
tower-sessions-redis-store = { version = "0.11", optional = true }
|
tower-sessions-redis-store = { version = "0.11", optional = true }
|
||||||
async-trait = "0.1.79"
|
async-trait = { version = "0.1.79", optional = true }
|
||||||
axum-login = { version = "0.14.0", optional = true }
|
axum-login = { version = "0.14.0", optional = true }
|
||||||
|
server_fn = { version = "0.6.11", features = ["multipart"] }
|
||||||
[patch.crates-io]
|
symphonia = { version = "0.5.4", default-features = false, features = ["mp3"], optional = true }
|
||||||
gloo-net = { git = "https://github.com/rustwasm/gloo.git", rev = "a823fab7ecc4068e9a28bd669da5eaf3f0a56380" }
|
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"
|
||||||
|
leptos-use = "0.13.5"
|
||||||
|
image-convert = { version = "0.18.0", optional = true, default-features = false }
|
||||||
|
chrono = { version = "0.4.38", default-features = false, features = ["serde", "clock"] }
|
||||||
|
dotenvy = { version = "0.15.7", optional = true }
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
|
hydrate = [
|
||||||
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
|
"leptos/hydrate",
|
||||||
|
"leptos_meta/hydrate",
|
||||||
|
"leptos_router/hydrate",
|
||||||
|
"console_error_panic_hook",
|
||||||
|
"wasm-bindgen",
|
||||||
|
"chrono/wasmbind",
|
||||||
|
]
|
||||||
ssr = [
|
ssr = [
|
||||||
"dep:leptos_axum",
|
"dep:leptos_axum",
|
||||||
"leptos/ssr",
|
"leptos/ssr",
|
||||||
"leptos_meta/ssr",
|
"leptos_meta/ssr",
|
||||||
"leptos_router/ssr",
|
"leptos_router/ssr",
|
||||||
"dotenv",
|
"dotenvy",
|
||||||
"diesel",
|
"diesel",
|
||||||
"lazy_static",
|
"lazy_static",
|
||||||
"openssl",
|
"openssl",
|
||||||
"diesel_migrations",
|
"diesel_migrations",
|
||||||
"pbkdf2",
|
"pbkdf2",
|
||||||
"futures",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
"axum",
|
"axum",
|
||||||
"tower",
|
"tower",
|
||||||
"tower-http",
|
"tower-http",
|
||||||
"tower-sessions-redis-store",
|
"tower-sessions-redis-store",
|
||||||
|
"async-trait",
|
||||||
"axum-login",
|
"axum-login",
|
||||||
|
"symphonia",
|
||||||
|
"multer",
|
||||||
|
"log",
|
||||||
|
"flexi_logger",
|
||||||
|
"leptos-use/ssr",
|
||||||
|
"image-convert",
|
||||||
]
|
]
|
||||||
|
|
||||||
# Defines a size-optimized profile for the WASM bundle in release mode
|
# Defines a size-optimized profile for the WASM bundle in release mode
|
||||||
|
46
Dockerfile
46
Dockerfile
@ -1,22 +1,37 @@
|
|||||||
FROM registry.mregirouard.com/libretunes/ops/docker-leptos/musl:latest as builder
|
FROM rust:slim AS builder
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
|
RUN rustup default nightly
|
||||||
|
RUN rustup target add wasm32-unknown-unknown
|
||||||
|
RUN cargo install cargo-leptos
|
||||||
|
|
||||||
# Install a few dependencies
|
# Install a few dependencies
|
||||||
RUN set -eux; \
|
RUN set -eux; \
|
||||||
apt-get update; \
|
apt-get update; \
|
||||||
apt-get install -y --no-install-recommends \
|
apt-get install -y --no-install-recommends \
|
||||||
npm; \
|
pkg-config \
|
||||||
|
clang \
|
||||||
|
build-essential \
|
||||||
|
libssl-dev \
|
||||||
|
libpq-dev \
|
||||||
|
wget; \
|
||||||
rm -rf /var/lib/apt/lists/*
|
rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
RUN npm install tailwindcss@3.1.8 -g
|
# Install ImageMagick
|
||||||
|
RUN cd / && \
|
||||||
|
wget https://github.com/ImageMagick/ImageMagick/archive/refs/tags/7.1.1-38.tar.gz && \
|
||||||
|
tar xf 7.1.1-38.tar.gz && \
|
||||||
|
rm 7.1.1-38.tar.gz && \
|
||||||
|
cd ImageMagick-7.1.1-38 && \
|
||||||
|
./configure && \
|
||||||
|
make install -j $(nproc) && \
|
||||||
|
cd .. && \
|
||||||
|
rm -rf ImageMagick-7.1.1-38
|
||||||
|
|
||||||
# Copy project dependency manifests
|
# Copy project dependency manifests
|
||||||
COPY Cargo.toml Cargo.lock /app/
|
COPY Cargo.toml Cargo.lock /app/
|
||||||
|
|
||||||
# Add the target to Cargo.toml so we can statically link:
|
|
||||||
RUN echo 'bin-target-triple = "x86_64-unknown-linux-musl"' >> Cargo.toml
|
|
||||||
|
|
||||||
# Create dummy files to force cargo to build the dependencies
|
# Create dummy files to force cargo to build the dependencies
|
||||||
RUN mkdir /app/src && mkdir /app/style && mkdir /app/assets && \
|
RUN mkdir /app/src && mkdir /app/style && mkdir /app/assets && \
|
||||||
echo "fn main() {}" | tee /app/src/build.rs > /app/src/main.rs && \
|
echo "fn main() {}" | tee /app/src/build.rs > /app/src/main.rs && \
|
||||||
@ -27,14 +42,12 @@ RUN mkdir /app/src && mkdir /app/style && mkdir /app/assets && \
|
|||||||
RUN cargo-leptos build --release --precompress
|
RUN cargo-leptos build --release --precompress
|
||||||
|
|
||||||
RUN rm -rf /app/src /app/style /app/assets
|
RUN rm -rf /app/src /app/style /app/assets
|
||||||
COPY style /app/style
|
|
||||||
|
|
||||||
# Minify CSS
|
|
||||||
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
|
||||||
|
COPY style /app/style
|
||||||
|
|
||||||
# Touch files to force rebuild
|
# Touch files to force rebuild
|
||||||
RUN touch /app/src/main.rs && touch /app/src/lib.rs && touch /app/src/build.rs
|
RUN touch /app/src/main.rs && touch /app/src/lib.rs && touch /app/src/build.rs
|
||||||
@ -42,6 +55,11 @@ RUN touch /app/src/main.rs && touch /app/src/lib.rs && touch /app/src/build.rs
|
|||||||
# Actually build the binary
|
# Actually build the binary
|
||||||
RUN cargo-leptos build --release --precompress
|
RUN cargo-leptos build --release --precompress
|
||||||
|
|
||||||
|
# Use ldd to list all dependencies of /app/target/release/libretunes, then copy them to /app/libs
|
||||||
|
# Setting LD_LIBRARY_PATH is necessary to find the ImageMagick libraries
|
||||||
|
RUN mkdir /app/libs && LD_LIBRARY_PATH=/usr/local/lib ldd /app/target/release/libretunes | grep "=> /" | \
|
||||||
|
awk '{print $3}' | xargs -I '{}' cp '{}' /app/libs
|
||||||
|
|
||||||
# Build the final image
|
# Build the final image
|
||||||
FROM scratch
|
FROM scratch
|
||||||
|
|
||||||
@ -50,9 +68,15 @@ LABEL description="LibreTunes, an open-source browser audio player and \
|
|||||||
library manager built for collaborative listening."
|
library manager built for collaborative listening."
|
||||||
|
|
||||||
# Copy the binary and the compressed assets to the "site root"
|
# Copy the binary and the compressed assets to the "site root"
|
||||||
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/libretunes /libretunes
|
COPY --from=builder /app/target/release/libretunes /libretunes
|
||||||
COPY --from=builder /app/target/site /site
|
COPY --from=builder /app/target/site /site
|
||||||
|
|
||||||
|
# Copy libraries to /lib64
|
||||||
|
COPY --from=builder /app/libs /lib64
|
||||||
|
COPY --from=builder /lib/x86_64-linux-gnu/ld-linux-x86-64.so.2 /lib64/ld-linux-x86-64.so.2
|
||||||
|
|
||||||
|
ENV LD_LIBRARY_PATH=/lib64
|
||||||
|
|
||||||
# Configure Leptos settings
|
# Configure Leptos settings
|
||||||
ENV LEPTOS_SITE_ADDR=0.0.0.0:3000
|
ENV LEPTOS_SITE_ADDR=0.0.0.0:3000
|
||||||
ENV LEPTOS_SITE_ROOT=/site
|
ENV LEPTOS_SITE_ROOT=/site
|
||||||
|
10
ascii_art.txt
Normal file
10
ascii_art.txt
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
.-=. =+==-.
|
||||||
|
.=++++. =+++++=.
|
||||||
|
_ _ _ _______ =++++++= :*++++++=
|
||||||
|
| | (_) | |__ __| -++++**+. -+**++++-
|
||||||
|
| | _| |__ _ __ ___| |_ _ _ __ ___ ___ *+++**+ +**+++*
|
||||||
|
| | | | '_ \| '__/ _ \ | | | | '_ \ / _ \/ __| *+++**+ +**+++*
|
||||||
|
| |____| | |_) | | | __/ | |_| | | | | __/\__ \ -++++**+-: +**++++-
|
||||||
|
|______|_|_.__/|_| \___|_|\__,_|_| |_|\___||___/ =++++++**+ -+++++=
|
||||||
|
.=+++++++=.+++=.
|
||||||
|
.-==++++---.
|
1
assets/images/placeholders/MusicPlaceholder.svg
Normal file
1
assets/images/placeholders/MusicPlaceholder.svg
Normal file
@ -0,0 +1 @@
|
|||||||
|
<svg version="1.1" viewBox="0.0 0.0 960.0 960.0" fill="none" stroke="none" stroke-linecap="square" stroke-miterlimit="10" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://www.w3.org/2000/svg"><clipPath id="p.0"><path d="m0 0l960.0 0l0 960.0l-960.0 0l0 -960.0z" clip-rule="nonzero"/></clipPath><g clip-path="url(#p.0)"><path fill="#4032a8" d="m0 0l960.0 0l0 960.0l-960.0 0z" fill-rule="evenodd"/><path fill="#ffffff" d="m290.11365 265.52475l35.496063 0l0 471.3386l-35.496063 0z" fill-rule="evenodd"/><path fill="#ffffff" d="m115.68951 737.6639l0 0c0 -36.946594 46.99247 -66.897644 104.960625 -66.897644l0 0c57.968155 0 104.96065 29.95105 104.96065 66.897644l0 0c0 36.946533 -46.992493 66.897644 -104.96065 66.897644l0 0c-57.968155 0 -104.960625 -29.95111 -104.960625 -66.897644z" fill-rule="evenodd"/><path fill="#ffffff" d="m723.79346 175.86597l35.496033 0l0 471.33856l-35.496033 0z" fill-rule="evenodd"/><path fill="#ffffff" d="m549.3693 648.00507l0 0c0 -36.946533 46.99243 -66.897644 104.96063 -66.897644l0 0c57.96814 0 104.96057 29.95111 104.96057 66.897644l0 0c0 36.946533 -46.99243 66.897644 -104.96057 66.897644l0 0c-57.9682 0 -104.96063 -29.95111 -104.96063 -66.897644z" fill-rule="evenodd"/><path fill="#ffffff" d="m759.2711 155.4385l-0.01727295 94.79588l-427.05206 100.14052l-42.09601 -84.920654z" fill-rule="evenodd"/><path fill="#ffffff" d="m421.49164 234.64502l21.039368 89.85828l-131.40158 30.803131l-21.039368 -89.85828z" fill-rule="evenodd"/></g></svg>
|
After Width: | Height: | Size: 1.4 KiB |
@ -3,7 +3,7 @@ name: libretunes
|
|||||||
services:
|
services:
|
||||||
libretunes:
|
libretunes:
|
||||||
container_name: libretunes
|
container_name: libretunes
|
||||||
# image: registry.mregirouard.com/libretunes/libretunes:latest
|
# image: git.libretunes.xyz/libretunes/libretunes:latest
|
||||||
build: .
|
build: .
|
||||||
ports:
|
ports:
|
||||||
- "3000:3000"
|
- "3000:3000"
|
||||||
@ -13,8 +13,12 @@ services:
|
|||||||
POSTGRES_USER: ${POSTGRES_USER}
|
POSTGRES_USER: ${POSTGRES_USER}
|
||||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
|
||||||
POSTGRES_DB: ${POSTGRES_DB}
|
POSTGRES_DB: ${POSTGRES_DB}
|
||||||
|
LIBRETUNES_AUDIO_PATH: /assets/audio
|
||||||
|
LIBRETUNES_IMAGE_PATH: /assets/images
|
||||||
|
LIBRETUNES_DISABLE_SIGNUP: "true"
|
||||||
volumes:
|
volumes:
|
||||||
- libretunes-audio:/site/audio
|
- libretunes-audio:/assets/audio
|
||||||
|
- libretunes-images:/assets/images
|
||||||
depends_on:
|
depends_on:
|
||||||
- redis
|
- redis
|
||||||
- postgres
|
- postgres
|
||||||
@ -50,5 +54,6 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
libretunes-audio:
|
libretunes-audio:
|
||||||
|
libretunes-images:
|
||||||
libretunes-redis:
|
libretunes-redis:
|
||||||
libretunes-postgres:
|
libretunes-postgres:
|
||||||
|
114
flake.lock
generated
Normal file
114
flake.lock
generated
Normal file
@ -0,0 +1,114 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"cargo-leptos": {
|
||||||
|
"flake": false,
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1730677835,
|
||||||
|
"narHash": "sha256-Oe65m9io7ihymUjylaWHQM/x7r0y/xXqD313H3oyjN8=",
|
||||||
|
"owner": "leptos-rs",
|
||||||
|
"repo": "cargo-leptos",
|
||||||
|
"rev": "ff6b19a5f9fd4e433774b6a9c57922ea5a1634cc",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "leptos-rs",
|
||||||
|
"ref": "v0.2.21",
|
||||||
|
"repo": "cargo-leptos",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"flake-utils": {
|
||||||
|
"inputs": {
|
||||||
|
"systems": "systems"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1731533236,
|
||||||
|
"narHash": "sha256-l0KFg5HjrsfsO/JpG+r7fRrqm12kzFHyUHqHCVpMMbI=",
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"rev": "11707dc2f618dd54ca8739b309ec4fc024de578b",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "numtide",
|
||||||
|
"repo": "flake-utils",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1733940404,
|
||||||
|
"narHash": "sha256-Pj39hSoUA86ZePPF/UXiYHHM7hMIkios8TYG29kQT4g=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "5d67ea6b4b63378b9c13be21e2ec9d1afc921713",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"nixpkgs_2": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1728538411,
|
||||||
|
"narHash": "sha256-f0SBJz1eZ2yOuKUr5CA9BHULGXVSn6miBuUWdTyhUhU=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "b69de56fac8c2b6f8fd27f2eca01dcda8e0a4221",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixpkgs-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"cargo-leptos": "cargo-leptos",
|
||||||
|
"flake-utils": "flake-utils",
|
||||||
|
"nixpkgs": "nixpkgs",
|
||||||
|
"rust-overlay": "rust-overlay"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"rust-overlay": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs_2"
|
||||||
|
},
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1734230139,
|
||||||
|
"narHash": "sha256-zsp0Mz8VgyIAnU8UhP/YT1g+zlsl+NIJTBMAbY+RifQ=",
|
||||||
|
"owner": "oxalica",
|
||||||
|
"repo": "rust-overlay",
|
||||||
|
"rev": "150fbc8aa2bc501041810bbc1dbfe73694a861be",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "oxalica",
|
||||||
|
"repo": "rust-overlay",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"systems": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1681028828,
|
||||||
|
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "nix-systems",
|
||||||
|
"repo": "default",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
102
flake.nix
Normal file
102
flake.nix
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
{
|
||||||
|
description = "LibreTunes build and development environment";
|
||||||
|
|
||||||
|
inputs = {
|
||||||
|
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
rust-overlay.url = "github:oxalica/rust-overlay";
|
||||||
|
flake-utils.url = "github:numtide/flake-utils";
|
||||||
|
cargo-leptos = {
|
||||||
|
url = "github:leptos-rs/cargo-leptos?ref=v0.2.22";
|
||||||
|
flake = false;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
outputs = { self, nixpkgs, rust-overlay, flake-utils, cargo-leptos, ... }:
|
||||||
|
flake-utils.lib.eachDefaultSystem (system:
|
||||||
|
let
|
||||||
|
overlays = [ (import rust-overlay) ];
|
||||||
|
pkgs = import nixpkgs {
|
||||||
|
inherit system overlays;
|
||||||
|
};
|
||||||
|
|
||||||
|
# Build a specific version of cargo-leptos
|
||||||
|
cargo-leptos-build = pkgs.rustPlatform.buildRustPackage {
|
||||||
|
name = "cargo-leptos";
|
||||||
|
buildFeatures = ["no_downloads"];
|
||||||
|
src = cargo-leptos;
|
||||||
|
cargoHash = "sha256-4v6sCTPRxe7bO7uV3HwUC8P1UsG8ydIvZ4rG2kU22zA=";
|
||||||
|
|
||||||
|
nativeBuildInputs = with pkgs; [
|
||||||
|
pkg-config
|
||||||
|
openssl
|
||||||
|
];
|
||||||
|
|
||||||
|
doCheck = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
buildPkgs = with pkgs; [
|
||||||
|
(rust-bin.fromRustupToolchainFile ./rust-toolchain.toml)
|
||||||
|
cargo-leptos-build
|
||||||
|
clang
|
||||||
|
sass
|
||||||
|
openssl
|
||||||
|
postgresql
|
||||||
|
imagemagick
|
||||||
|
pkg-config
|
||||||
|
];
|
||||||
|
in
|
||||||
|
{
|
||||||
|
devShells.default = pkgs.mkShell {
|
||||||
|
LIBCLANG_PATH = pkgs.lib.makeLibraryPath [ pkgs.llvmPackages_latest.libclang.lib ];
|
||||||
|
|
||||||
|
buildInputs = with pkgs; buildPkgs ++ [
|
||||||
|
diesel-cli
|
||||||
|
];
|
||||||
|
|
||||||
|
shellHook = ''
|
||||||
|
set -a
|
||||||
|
[[ -f .env ]] && source .env
|
||||||
|
set +a
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
|
||||||
|
packages.default = pkgs.rustPlatform.buildRustPackage {
|
||||||
|
name = "libretunes";
|
||||||
|
src = ./.;
|
||||||
|
|
||||||
|
cargoLock = {
|
||||||
|
lockFile = ./Cargo.lock;
|
||||||
|
};
|
||||||
|
|
||||||
|
LIBCLANG_PATH = pkgs.lib.makeLibraryPath [ pkgs.llvmPackages_latest.libclang.lib ];
|
||||||
|
|
||||||
|
nativeBuildInputs = with pkgs; buildPkgs ++ [
|
||||||
|
makeWrapper
|
||||||
|
];
|
||||||
|
|
||||||
|
buildInputs = with pkgs; [
|
||||||
|
openssl
|
||||||
|
imagemagick
|
||||||
|
];
|
||||||
|
|
||||||
|
# TODO enable --release builds
|
||||||
|
# Creates an issue with cargo-leptos trying to create cache directories
|
||||||
|
# See https://github.com/leptos-rs/cargo-leptos/issues/79
|
||||||
|
buildPhase = ''
|
||||||
|
cargo-leptos build --precompress #--release
|
||||||
|
'';
|
||||||
|
|
||||||
|
installPhase = ''
|
||||||
|
mkdir -p $out/bin
|
||||||
|
install -t $out target/debug/libretunes
|
||||||
|
cp -r target/site $out/site
|
||||||
|
|
||||||
|
makeWrapper $out/libretunes $out/bin/libretunes \
|
||||||
|
--set LEPTOS_SITE_ROOT $out/site
|
||||||
|
'';
|
||||||
|
|
||||||
|
doCheck = false;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
@ -0,0 +1,2 @@
|
|||||||
|
DROP TABLE song_likes;
|
||||||
|
DROP TABLE song_dislikes;
|
@ -0,0 +1,11 @@
|
|||||||
|
CREATE TABLE song_likes (
|
||||||
|
song_id INTEGER REFERENCES songs(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
PRIMARY KEY (song_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE song_dislikes (
|
||||||
|
song_id INTEGER REFERENCES songs(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
PRIMARY KEY (song_id, user_id)
|
||||||
|
);
|
1
migrations/2024-05-16-220659_add_album_images/down.sql
Normal file
1
migrations/2024-05-16-220659_add_album_images/down.sql
Normal file
@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE albums DROP COLUMN image_path;
|
1
migrations/2024-05-16-220659_add_album_images/up.sql
Normal file
1
migrations/2024-05-16-220659_add_album_images/up.sql
Normal file
@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE albums ADD COLUMN image_path VARCHAR;
|
1
migrations/2024-05-18-231505_add_user_admin/down.sql
Normal file
1
migrations/2024-05-18-231505_add_user_admin/down.sql
Normal file
@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE users DROP COLUMN admin;
|
1
migrations/2024-05-18-231505_add_user_admin/up.sql
Normal file
1
migrations/2024-05-18-231505_add_user_admin/up.sql
Normal file
@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE users ADD COLUMN admin BOOLEAN DEFAULT FALSE NOT NULL;
|
2
migrations/2024-05-19-163229_add_song_history/down.sql
Normal file
2
migrations/2024-05-19-163229_add_song_history/down.sql
Normal file
@ -0,0 +1,2 @@
|
|||||||
|
DROP INDEX song_history_user_id_idx;
|
||||||
|
DROP TABLE song_history;
|
8
migrations/2024-05-19-163229_add_song_history/up.sql
Normal file
8
migrations/2024-05-19-163229_add_song_history/up.sql
Normal file
@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE song_history (
|
||||||
|
id SERIAL PRIMARY KEY UNIQUE NOT NULL,
|
||||||
|
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
date TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||||
|
song_id INTEGER REFERENCES songs(id) ON DELETE CASCADE NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX song_history_user_id_idx ON song_history(user_id);
|
7
migrations/2024-05-20-154208_add_friends/down.sql
Normal file
7
migrations/2024-05-20-154208_add_friends/down.sql
Normal file
@ -0,0 +1,7 @@
|
|||||||
|
DROP INDEX friendships_friend_2_idx;
|
||||||
|
DROP INDEX friendships_friend_1_idx;
|
||||||
|
DROP TABLE friendships;
|
||||||
|
|
||||||
|
DROP INDEX incoming_friend_requests_idx;
|
||||||
|
DROP INDEX outgoing_friend_requests_idx;
|
||||||
|
DROP TABLE friend_requests;
|
19
migrations/2024-05-20-154208_add_friends/up.sql
Normal file
19
migrations/2024-05-20-154208_add_friends/up.sql
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
CREATE TABLE friend_requests (
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||||
|
from_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
to_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
PRIMARY KEY (from_id, to_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX outgoing_friend_requests_idx ON friend_requests(from_id);
|
||||||
|
CREATE INDEX incoming_friend_requests_idx ON friend_requests(to_id);
|
||||||
|
|
||||||
|
CREATE TABLE friendships (
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||||
|
friend_1_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
friend_2_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
PRIMARY KEY (friend_1_id, friend_2_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX friendships_friend_1_idx ON friendships(friend_1_id);
|
||||||
|
CREATE INDEX friendships_friend_2_idx ON friendships(friend_2_id);
|
@ -0,0 +1,5 @@
|
|||||||
|
DROP INDEX playlists_owner_idx;
|
||||||
|
DROP TABLE playlists;
|
||||||
|
|
||||||
|
DROP INDEX playlist_songs_playlist_idx;
|
||||||
|
DROP TABLE playlist_songs;
|
17
migrations/2024-10-22-212759_create_playlist_tables/up.sql
Normal file
17
migrations/2024-10-22-212759_create_playlist_tables/up.sql
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
CREATE TABLE playlists (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
||||||
|
owner_id INTEGER REFERENCES users(id) ON DELETE CASCADE NOT NULL,
|
||||||
|
name TEXT NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX playlists_owner_idx ON playlists(owner_id);
|
||||||
|
|
||||||
|
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,
|
||||||
|
PRIMARY KEY (playlist_id, song_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX playlist_songs_playlist_idx ON playlist_songs(playlist_id);
|
@ -1,3 +1,4 @@
|
|||||||
|
|
||||||
[toolchain]
|
[toolchain]
|
||||||
channel = "nightly"
|
channel = "nightly"
|
||||||
|
targets = ["wasm32-unknown-unknown"]
|
||||||
|
|
||||||
|
42
src/albumdata.rs
Normal file
42
src/albumdata.rs
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
use crate::models::Artist;
|
||||||
|
use crate::components::dashboard_tile::DashboardTile;
|
||||||
|
use serde::{Serialize, Deserialize};
|
||||||
|
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
|
||||||
|
/// Holds information about an album
|
||||||
|
///
|
||||||
|
/// Intended to be used in the front-end
|
||||||
|
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
|
pub struct AlbumData {
|
||||||
|
/// Album id
|
||||||
|
pub id: i32,
|
||||||
|
/// Album title
|
||||||
|
pub title: String,
|
||||||
|
/// Album artists
|
||||||
|
pub artists: Vec<Artist>,
|
||||||
|
/// Album release date
|
||||||
|
pub release_date: Option<NaiveDate>,
|
||||||
|
/// Path to album image, relative to the root of the web server.
|
||||||
|
/// For example, `"/assets/images/Album.jpg"`
|
||||||
|
pub image_path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DashboardTile for AlbumData {
|
||||||
|
fn image_path(&self) -> String {
|
||||||
|
self.image_path.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self) -> String {
|
||||||
|
self.title.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link(&self) -> String {
|
||||||
|
format!("/album/{}", self.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> Option<String> {
|
||||||
|
Some(format!("Album • {}", Artist::display_list(&self.artists)))
|
||||||
|
}
|
||||||
|
}
|
33
src/api/album.rs
Normal file
33
src/api/album.rs
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use crate::albumdata::AlbumData;
|
||||||
|
use crate::songdata::SongData;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
if #[cfg(feature = "ssr")] {
|
||||||
|
use leptos::server_fn::error::NoCustomError;
|
||||||
|
use crate::database::get_db_conn;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[server(endpoint = "album/get")]
|
||||||
|
pub async fn get_album(id: i32) -> Result<AlbumData, ServerFnError> {
|
||||||
|
use crate::models::Album;
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
let album = Album::get_album_data(id,db_con)
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting album: {}", e)))?;
|
||||||
|
Ok(album)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[server(endpoint = "album/get_songs")]
|
||||||
|
pub async fn get_songs(id: i32) -> Result<Vec<SongData>, ServerFnError> {
|
||||||
|
use crate::models::Album;
|
||||||
|
use crate::auth::get_logged_in_user;
|
||||||
|
let user = get_logged_in_user().await?;
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
// TODO: NEEDS SONG DATA QUERIES
|
||||||
|
let songdata = Album::get_song_data(id,user,db_con)
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting song data: {}", e)))?;
|
||||||
|
Ok(songdata)
|
||||||
|
}
|
44
src/api/history.rs
Normal file
44
src/api/history.rs
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
use chrono::NaiveDateTime;
|
||||||
|
use leptos::*;
|
||||||
|
use crate::models::HistoryEntry;
|
||||||
|
use crate::models::Song;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
if #[cfg(feature = "ssr")] {
|
||||||
|
use leptos::server_fn::error::NoCustomError;
|
||||||
|
use crate::database::get_db_conn;
|
||||||
|
use crate::auth::get_user;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the history of the current user.
|
||||||
|
#[server(endpoint = "history/get")]
|
||||||
|
pub async fn get_history(limit: Option<i64>) -> Result<Vec<HistoryEntry>, ServerFnError> {
|
||||||
|
let user = get_user().await?;
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
let history = user.get_history(limit, db_con)
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting history: {}", e)))?;
|
||||||
|
Ok(history)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the listen dates and songs of the current user.
|
||||||
|
#[server(endpoint = "history/get_songs")]
|
||||||
|
pub async fn get_history_songs(limit: Option<i64>) -> Result<Vec<(NaiveDateTime, Song)>, ServerFnError> {
|
||||||
|
let user = get_user().await?;
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
let songs = user.get_history_songs(limit, db_con)
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting history songs: {}", e)))?;
|
||||||
|
Ok(songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a song to the history of the current user.
|
||||||
|
#[server(endpoint = "history/add")]
|
||||||
|
pub async fn add_history(song_id: i32) -> Result<(), ServerFnError> {
|
||||||
|
let user = get_user().await?;
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
user.add_history(song_id, db_con)
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error adding history: {}", e)))?;
|
||||||
|
Ok(())
|
||||||
|
}
|
4
src/api/mod.rs
Normal file
4
src/api/mod.rs
Normal file
@ -0,0 +1,4 @@
|
|||||||
|
pub mod history;
|
||||||
|
pub mod profile;
|
||||||
|
pub mod songs;
|
||||||
|
pub mod album;
|
300
src/api/profile.rs
Normal file
300
src/api/profile.rs
Normal file
@ -0,0 +1,300 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use server_fn::codec::{MultipartData, MultipartFormData};
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
use crate::songdata::SongData;
|
||||||
|
use crate::artistdata::ArtistData;
|
||||||
|
|
||||||
|
use chrono::NaiveDateTime;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
if #[cfg(feature = "ssr")] {
|
||||||
|
use crate::auth::get_user;
|
||||||
|
use server_fn::error::NoCustomError;
|
||||||
|
|
||||||
|
use crate::database::get_db_conn;
|
||||||
|
use diesel::prelude::*;
|
||||||
|
use diesel::dsl::count;
|
||||||
|
use crate::models::*;
|
||||||
|
use crate::schema::*;
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handle a user uploading a profile picture. Converts the image to webp and saves it to the server.
|
||||||
|
#[server(input = MultipartFormData, endpoint = "/profile/upload_picture")]
|
||||||
|
pub async fn upload_picture(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 field = data.next_field().await
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting field: {}", e)))?
|
||||||
|
.ok_or_else(|| ServerFnError::<NoCustomError>::ServerError("No field found".to_string()))?;
|
||||||
|
|
||||||
|
if field.name() != Some("picture") {
|
||||||
|
return Err(ServerFnError::ServerError("Field name is not 'picture'".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get user id from session
|
||||||
|
let user = get_user().await
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting user: {}", e)))?;
|
||||||
|
|
||||||
|
let user_id = user.id.ok_or_else(|| ServerFnError::<NoCustomError>::ServerError("User has no id".to_string()))?;
|
||||||
|
|
||||||
|
// Read the image, and convert it to webp
|
||||||
|
use image_convert::{to_webp, WEBPConfig, ImageResource};
|
||||||
|
|
||||||
|
let bytes = field.bytes().await
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting field bytes: {}", e)))?;
|
||||||
|
|
||||||
|
let reader = std::io::Cursor::new(bytes);
|
||||||
|
let image_source = ImageResource::from_reader(reader)
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error creating image resource: {}", e)))?;
|
||||||
|
|
||||||
|
let profile_picture_path = format!("assets/images/profile/{}.webp", user_id);
|
||||||
|
let mut image_target = ImageResource::from_path(&profile_picture_path);
|
||||||
|
to_webp(&mut image_target, &image_source, &WEBPConfig::new())
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error converting image to webp: {}", e)))?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a user's recent songs listened to
|
||||||
|
/// Optionally takes a limit parameter to limit the number of songs returned.
|
||||||
|
/// If not provided, all songs ever listend to are returned.
|
||||||
|
/// Returns a list of tuples with the date the song was listened to
|
||||||
|
/// and the song data, sorted by date (most recent first).
|
||||||
|
#[server(endpoint = "/profile/recent_songs")]
|
||||||
|
pub async fn recent_songs(for_user_id: i32, limit: Option<i64>) -> Result<Vec<(NaiveDateTime, SongData)>, ServerFnError> {
|
||||||
|
let mut db_con = get_db_conn();
|
||||||
|
|
||||||
|
// Get the ids of the most recent songs listened to
|
||||||
|
let history_items: Vec<i32> =
|
||||||
|
if let Some(limit) = limit {
|
||||||
|
song_history::table
|
||||||
|
.filter(song_history::user_id.eq(for_user_id))
|
||||||
|
.order(song_history::date.desc())
|
||||||
|
.limit(limit)
|
||||||
|
.select(song_history::id)
|
||||||
|
.load(&mut db_con)?
|
||||||
|
} else {
|
||||||
|
song_history::table
|
||||||
|
.filter(song_history::user_id.eq(for_user_id))
|
||||||
|
.order(song_history::date.desc())
|
||||||
|
.select(song_history::id)
|
||||||
|
.load(&mut db_con)?
|
||||||
|
};
|
||||||
|
|
||||||
|
// Take the history ids and get the song data for them
|
||||||
|
let history: Vec<(HistoryEntry, Song, Option<Album>, Option<Artist>, Option<(i32, i32)>, Option<(i32, i32)>)>
|
||||||
|
= song_history::table
|
||||||
|
.filter(song_history::id.eq_any(history_items))
|
||||||
|
.inner_join(songs::table)
|
||||||
|
.left_join(albums::table.on(songs::album_id.eq(albums::id.nullable())))
|
||||||
|
.left_join(song_artists::table.inner_join(artists::table).on(songs::id.eq(song_artists::song_id)))
|
||||||
|
.left_join(song_likes::table.on(songs::id.eq(song_likes::song_id).and(song_likes::user_id.eq(for_user_id))))
|
||||||
|
.left_join(song_dislikes::table.on(
|
||||||
|
songs::id.eq(song_dislikes::song_id).and(song_dislikes::user_id.eq(for_user_id))))
|
||||||
|
.select((
|
||||||
|
song_history::all_columns,
|
||||||
|
songs::all_columns,
|
||||||
|
albums::all_columns.nullable(),
|
||||||
|
artists::all_columns.nullable(),
|
||||||
|
song_likes::all_columns.nullable(),
|
||||||
|
song_dislikes::all_columns.nullable(),
|
||||||
|
))
|
||||||
|
.load(&mut db_con)?;
|
||||||
|
|
||||||
|
// Process the history data into a map of song ids to song data
|
||||||
|
let mut history_songs: HashMap<i32, (NaiveDateTime, SongData)> = HashMap::with_capacity(history.len());
|
||||||
|
|
||||||
|
for (history, song, album, artist, like, dislike) in history {
|
||||||
|
let song_id = history.song_id;
|
||||||
|
|
||||||
|
if let Some((_, stored_songdata)) = history_songs.get_mut(&song_id) {
|
||||||
|
// If the song is already in the map, update the artists
|
||||||
|
if let Some(artist) = artist {
|
||||||
|
stored_songdata.artists.push(artist);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let like_dislike = match (like, dislike) {
|
||||||
|
(Some(_), Some(_)) => Some((true, true)),
|
||||||
|
(Some(_), None) => Some((true, false)),
|
||||||
|
(None, Some(_)) => Some((false, true)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let image_path = song.image_path.unwrap_or(
|
||||||
|
album.as_ref().map(|album| album.image_path.clone()).flatten()
|
||||||
|
.unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string()));
|
||||||
|
|
||||||
|
let songdata = SongData {
|
||||||
|
id: song_id,
|
||||||
|
title: song.title,
|
||||||
|
artists: artist.map(|artist| vec![artist]).unwrap_or_default(),
|
||||||
|
album: album,
|
||||||
|
track: song.track,
|
||||||
|
duration: song.duration,
|
||||||
|
release_date: song.release_date,
|
||||||
|
song_path: song.storage_path,
|
||||||
|
image_path: image_path,
|
||||||
|
like_dislike: like_dislike,
|
||||||
|
};
|
||||||
|
|
||||||
|
history_songs.insert(song_id, (history.date, songdata));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort the songs by date
|
||||||
|
let mut history_songs: Vec<(NaiveDateTime, SongData)> = history_songs.into_values().collect();
|
||||||
|
history_songs.sort_by(|a, b| b.0.cmp(&a.0));
|
||||||
|
Ok(history_songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a user's top songs by play count from a date range
|
||||||
|
/// Optionally takes a limit parameter to limit the number of songs returned.
|
||||||
|
/// If not provided, all songs listened to in the date range are returned.
|
||||||
|
/// Returns a list of tuples with the play count and the song data, sorted by play count (most played first).
|
||||||
|
#[server(endpoint = "/profile/top_songs")]
|
||||||
|
pub async fn top_songs(for_user_id: i32, start_date: NaiveDateTime, end_date: NaiveDateTime, limit: Option<i64>)
|
||||||
|
-> Result<Vec<(i64, SongData)>, ServerFnError>
|
||||||
|
{
|
||||||
|
let mut db_con = get_db_conn();
|
||||||
|
|
||||||
|
// Get the play count and ids of the songs listened to in the date range
|
||||||
|
let history_counts: Vec<(i32, i64)> =
|
||||||
|
if let Some(limit) = limit {
|
||||||
|
song_history::table
|
||||||
|
.filter(song_history::date.between(start_date, end_date))
|
||||||
|
.filter(song_history::user_id.eq(for_user_id))
|
||||||
|
.group_by(song_history::song_id)
|
||||||
|
.select((song_history::song_id, count(song_history::song_id)))
|
||||||
|
.order(count(song_history::song_id).desc())
|
||||||
|
.limit(limit)
|
||||||
|
.load(&mut db_con)?
|
||||||
|
} else {
|
||||||
|
song_history::table
|
||||||
|
.filter(song_history::date.between(start_date, end_date))
|
||||||
|
.filter(song_history::user_id.eq(for_user_id))
|
||||||
|
.group_by(song_history::song_id)
|
||||||
|
.select((song_history::song_id, count(song_history::song_id)))
|
||||||
|
.load(&mut db_con)?
|
||||||
|
};
|
||||||
|
|
||||||
|
let history_counts: HashMap<i32, i64> = history_counts.into_iter().collect();
|
||||||
|
let history_song_ids = history_counts.iter().map(|(song_id, _)| *song_id).collect::<Vec<i32>>();
|
||||||
|
|
||||||
|
// Get the song data for the songs listened to in the date range
|
||||||
|
let history_songs: Vec<(Song, Option<Album>, Option<Artist>, Option<(i32, i32)>, Option<(i32, i32)>)>
|
||||||
|
= songs::table
|
||||||
|
.filter(songs::id.eq_any(history_song_ids))
|
||||||
|
.left_join(albums::table.on(songs::album_id.eq(albums::id.nullable())))
|
||||||
|
.left_join(song_artists::table.inner_join(artists::table).on(songs::id.eq(song_artists::song_id)))
|
||||||
|
.left_join(song_likes::table.on(songs::id.eq(song_likes::song_id).and(song_likes::user_id.eq(for_user_id))))
|
||||||
|
.left_join(song_dislikes::table.on(
|
||||||
|
songs::id.eq(song_dislikes::song_id).and(song_dislikes::user_id.eq(for_user_id))))
|
||||||
|
.select((
|
||||||
|
songs::all_columns,
|
||||||
|
albums::all_columns.nullable(),
|
||||||
|
artists::all_columns.nullable(),
|
||||||
|
song_likes::all_columns.nullable(),
|
||||||
|
song_dislikes::all_columns.nullable(),
|
||||||
|
))
|
||||||
|
.load(&mut db_con)?;
|
||||||
|
|
||||||
|
// Process the history data into a map of song ids to song data
|
||||||
|
let mut history_songs_map: HashMap<i32, (i64, SongData)> = HashMap::with_capacity(history_counts.len());
|
||||||
|
|
||||||
|
for (song, album, artist, like, dislike) in history_songs {
|
||||||
|
let song_id = song.id
|
||||||
|
.ok_or(ServerFnError::ServerError::<NoCustomError>("Song id not found in database".to_string()))?;
|
||||||
|
|
||||||
|
if let Some((_, stored_songdata)) = history_songs_map.get_mut(&song_id) {
|
||||||
|
// If the song is already in the map, update the artists
|
||||||
|
if let Some(artist) = artist {
|
||||||
|
stored_songdata.artists.push(artist);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let like_dislike = match (like, dislike) {
|
||||||
|
(Some(_), Some(_)) => Some((true, true)),
|
||||||
|
(Some(_), None) => Some((true, false)),
|
||||||
|
(None, Some(_)) => Some((false, true)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let image_path = song.image_path.unwrap_or(
|
||||||
|
album.as_ref().map(|album| album.image_path.clone()).flatten()
|
||||||
|
.unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string()));
|
||||||
|
|
||||||
|
let songdata = SongData {
|
||||||
|
id: song_id,
|
||||||
|
title: song.title,
|
||||||
|
artists: artist.map(|artist| vec![artist]).unwrap_or_default(),
|
||||||
|
album: album,
|
||||||
|
track: song.track,
|
||||||
|
duration: song.duration,
|
||||||
|
release_date: song.release_date,
|
||||||
|
song_path: song.storage_path,
|
||||||
|
image_path: image_path,
|
||||||
|
like_dislike: like_dislike,
|
||||||
|
};
|
||||||
|
|
||||||
|
let plays = history_counts.get(&song_id)
|
||||||
|
.ok_or(ServerFnError::ServerError::<NoCustomError>("Song id not found in history counts".to_string()))?;
|
||||||
|
|
||||||
|
history_songs_map.insert(song_id, (*plays, songdata));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort the songs by play count
|
||||||
|
let mut history_songs: Vec<(i64, SongData)> = history_songs_map.into_values().collect();
|
||||||
|
history_songs.sort_by(|a, b| b.0.cmp(&a.0));
|
||||||
|
Ok(history_songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get a user's top artists by play count from a date range
|
||||||
|
/// Optionally takes a limit parameter to limit the number of artists returned.
|
||||||
|
/// If not provided, all artists listened to in the date range are returned.
|
||||||
|
/// Returns a list of tuples with the play count and the artist data, sorted by play count (most played first).
|
||||||
|
#[server(endpoint = "/profile/top_artists")]
|
||||||
|
pub async fn top_artists(for_user_id: i32, start_date: NaiveDateTime, end_date: NaiveDateTime, limit: Option<i64>)
|
||||||
|
-> Result<Vec<(i64, ArtistData)>, ServerFnError>
|
||||||
|
{
|
||||||
|
let mut db_con = get_db_conn();
|
||||||
|
|
||||||
|
let artist_counts: Vec<(i64, Artist)> =
|
||||||
|
if let Some(limit) = limit {
|
||||||
|
song_history::table
|
||||||
|
.filter(song_history::date.between(start_date, end_date))
|
||||||
|
.filter(song_history::user_id.eq(for_user_id))
|
||||||
|
.inner_join(song_artists::table.on(song_history::song_id.eq(song_artists::song_id)))
|
||||||
|
.inner_join(artists::table.on(song_artists::artist_id.eq(artists::id)))
|
||||||
|
.group_by(artists::id)
|
||||||
|
.select((count(artists::id), artists::all_columns))
|
||||||
|
.order(count(artists::id).desc())
|
||||||
|
.limit(limit)
|
||||||
|
.load(&mut db_con)?
|
||||||
|
} else {
|
||||||
|
song_history::table
|
||||||
|
.filter(song_history::date.between(start_date, end_date))
|
||||||
|
.filter(song_history::user_id.eq(for_user_id))
|
||||||
|
.inner_join(song_artists::table.on(song_history::song_id.eq(song_artists::song_id)))
|
||||||
|
.inner_join(artists::table.on(song_artists::artist_id.eq(artists::id)))
|
||||||
|
.group_by(artists::id)
|
||||||
|
.select((count(artists::id), artists::all_columns))
|
||||||
|
.order(count(artists::id).desc())
|
||||||
|
.load(&mut db_con)?
|
||||||
|
};
|
||||||
|
|
||||||
|
let artist_data: Vec<(i64, ArtistData)> = artist_counts.into_iter().map(|(plays, artist)| {
|
||||||
|
(plays, ArtistData {
|
||||||
|
id: artist.id.unwrap(),
|
||||||
|
name: artist.name,
|
||||||
|
image_path: format!("/assets/images/artists/{}.webp", artist.id.unwrap()),
|
||||||
|
})
|
||||||
|
}).collect();
|
||||||
|
|
||||||
|
Ok(artist_data)
|
||||||
|
}
|
55
src/api/songs.rs
Normal file
55
src/api/songs.rs
Normal file
@ -0,0 +1,55 @@
|
|||||||
|
use leptos::*;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
if #[cfg(feature = "ssr")] {
|
||||||
|
use leptos::server_fn::error::NoCustomError;
|
||||||
|
use crate::database::get_db_conn;
|
||||||
|
use crate::auth::get_user;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like or unlike a song
|
||||||
|
#[server(endpoint = "songs/set_like")]
|
||||||
|
pub async fn set_like_song(song_id: i32, like: bool) -> Result<(), ServerFnError> {
|
||||||
|
let user = get_user().await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error getting user: {}", e)))?;
|
||||||
|
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
|
||||||
|
user.set_like_song(song_id, like, db_con).await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error liking song: {}", e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dislike or remove dislike from a song
|
||||||
|
#[server(endpoint = "songs/set_dislike")]
|
||||||
|
pub async fn set_dislike_song(song_id: i32, dislike: bool) -> Result<(), ServerFnError> {
|
||||||
|
let user = get_user().await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error getting user: {}", e)))?;
|
||||||
|
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
|
||||||
|
user.set_dislike_song(song_id, dislike, db_con).await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error disliking song: {}", e)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the like and dislike status of a song
|
||||||
|
#[server(endpoint = "songs/get_like_dislike")]
|
||||||
|
pub async fn get_like_dislike_song(song_id: i32) -> Result<(bool, bool), ServerFnError> {
|
||||||
|
let user = get_user().await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error getting user: {}", e)))?;
|
||||||
|
|
||||||
|
let db_con = &mut get_db_conn();
|
||||||
|
|
||||||
|
// TODO this could probably be done more efficiently with a tokio::try_join, but
|
||||||
|
// doing so is much more complicated than it would initially seem
|
||||||
|
|
||||||
|
let like = user.get_like_song(song_id, db_con).await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error getting song liked: {}", e)))?;
|
||||||
|
let dislike = user.get_dislike_song(song_id, db_con).await.map_err(|e| ServerFnError::<NoCustomError>::
|
||||||
|
ServerError(format!("Error getting song disliked: {}", e)))?;
|
||||||
|
|
||||||
|
Ok((like, dislike))
|
||||||
|
}
|
46
src/app.rs
46
src/app.rs
@ -1,26 +1,32 @@
|
|||||||
use crate::playbar::PlayBar;
|
use crate::playbar::PlayBar;
|
||||||
use crate::playstatus::PlayStatus;
|
use crate::playbar::CustomTitle;
|
||||||
use crate::queue::Queue;
|
use crate::queue::Queue;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_meta::*;
|
use leptos_meta::*;
|
||||||
use leptos_router::*;
|
use leptos_router::*;
|
||||||
use crate::pages::login::*;
|
use crate::pages::login::*;
|
||||||
use crate::pages::signup::*;
|
use crate::pages::signup::*;
|
||||||
|
use crate::pages::profile::*;
|
||||||
|
use crate::pages::albumpage::*;
|
||||||
use crate::error_template::{AppError, ErrorTemplate};
|
use crate::error_template::{AppError, ErrorTemplate};
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
|
|
||||||
#[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();
|
||||||
|
|
||||||
|
provide_context(GlobalState::new());
|
||||||
|
|
||||||
|
let upload_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
|
||||||
<Stylesheet id="leptos" href="/pkg/libretunes.css"/>
|
<Stylesheet id="leptos" href="/pkg/libretunes.css"/>
|
||||||
|
|
||||||
// sets the document title
|
// sets the document title
|
||||||
<Title text="LibreTunes"/>
|
<CustomTitle />
|
||||||
|
|
||||||
// content for this welcome page
|
// content for this welcome page
|
||||||
<Router fallback=|| {
|
<Router fallback=|| {
|
||||||
@ -33,7 +39,14 @@ pub fn App() -> impl IntoView {
|
|||||||
}>
|
}>
|
||||||
<main>
|
<main>
|
||||||
<Routes>
|
<Routes>
|
||||||
<Route path="" view=HomePage/>
|
<Route path="" view=move || view! { <HomePage upload_open=upload_open/> }>
|
||||||
|
<Route path="" view=Dashboard />
|
||||||
|
<Route path="dashboard" view=Dashboard />
|
||||||
|
<Route path="search" view=Search />
|
||||||
|
<Route path="user/:id" view=Profile />
|
||||||
|
<Route path="user" view=Profile />
|
||||||
|
<Route path="album/:id" view=AlbumPage />
|
||||||
|
</Route>
|
||||||
<Route path="/login" view=Login />
|
<Route path="/login" view=Login />
|
||||||
<Route path="/signup" view=Signup />
|
<Route path="/signup" view=Signup />
|
||||||
</Routes>
|
</Routes>
|
||||||
@ -45,28 +58,21 @@ pub fn App() -> impl IntoView {
|
|||||||
use crate::components::sidebar::*;
|
use crate::components::sidebar::*;
|
||||||
use crate::components::dashboard::*;
|
use crate::components::dashboard::*;
|
||||||
use crate::components::search::*;
|
use crate::components::search::*;
|
||||||
use crate::components::personal::*;
|
use crate::components::personal::Personal;
|
||||||
|
use crate::components::upload::*;
|
||||||
|
|
||||||
/// Renders the home page of your application.
|
/// Renders the home page of your application.
|
||||||
#[component]
|
#[component]
|
||||||
fn HomePage() -> impl IntoView {
|
fn HomePage(upload_open: RwSignal<bool>) -> impl IntoView {
|
||||||
let play_status = PlayStatus::default();
|
|
||||||
let play_status = create_rw_signal(play_status);
|
|
||||||
|
|
||||||
let (dashboard_open, set_dashboard_open) = create_signal(true);
|
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<div class="home-container">
|
<div class="home-container">
|
||||||
<Sidebar setter=set_dashboard_open active=dashboard_open />
|
<Upload open=upload_open/>
|
||||||
<Show
|
<Sidebar upload_open=upload_open/>
|
||||||
when=move || {dashboard_open() == true}
|
// This <Outlet /> will render the child route components
|
||||||
fallback=move || view! { <Search /> }
|
<Outlet />
|
||||||
>
|
|
||||||
<Dashboard />
|
|
||||||
</Show>
|
|
||||||
<Personal />
|
<Personal />
|
||||||
<PlayBar status=play_status/>
|
<PlayBar />
|
||||||
<Queue status=play_status/>
|
<Queue />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
34
src/artistdata.rs
Normal file
34
src/artistdata.rs
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
use crate::components::dashboard_tile::DashboardTile;
|
||||||
|
use serde::{Serialize, Deserialize};
|
||||||
|
|
||||||
|
/// Holds information about an artist
|
||||||
|
///
|
||||||
|
/// Intended to be used in the front-end
|
||||||
|
#[derive(Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ArtistData {
|
||||||
|
/// Artist id
|
||||||
|
pub id: i32,
|
||||||
|
/// Artist name
|
||||||
|
pub name: String,
|
||||||
|
/// Path to artist image, relative to the root of the web server.
|
||||||
|
/// For example, `"/assets/images/Artist.jpg"`
|
||||||
|
pub image_path: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DashboardTile for ArtistData {
|
||||||
|
fn image_path(&self) -> String {
|
||||||
|
self.image_path.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self) -> String {
|
||||||
|
self.name.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link(&self) -> String {
|
||||||
|
format!("/artist/{}", self.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> Option<String> {
|
||||||
|
Some("Artist".to_string())
|
||||||
|
}
|
||||||
|
}
|
89
src/auth.rs
89
src/auth.rs
@ -19,11 +19,17 @@ use crate::users::UserCredentials;
|
|||||||
/// Returns a Result with the error message if the user could not be created
|
/// Returns a Result with the error message if the user could not be created
|
||||||
#[server(endpoint = "signup")]
|
#[server(endpoint = "signup")]
|
||||||
pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
|
pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
|
||||||
|
// Check LIBRETUNES_DISABLE_SIGNUP env var
|
||||||
|
if std::env::var("LIBRETUNES_DISABLE_SIGNUP").is_ok_and(|v| v == "true") {
|
||||||
|
return Err(ServerFnError::<NoCustomError>::ServerError("Signup is disabled".to_string()));
|
||||||
|
}
|
||||||
|
|
||||||
use crate::users::create_user;
|
use crate::users::create_user;
|
||||||
|
|
||||||
// Ensure the user has no id
|
// Ensure the user has no id, and is not a self-proclaimed admin
|
||||||
let new_user = User {
|
let new_user = User {
|
||||||
id: None,
|
id: None,
|
||||||
|
admin: false,
|
||||||
..new_user
|
..new_user
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -56,7 +62,7 @@ pub async fn signup(new_user: User) -> Result<(), ServerFnError> {
|
|||||||
/// 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(credentials: UserCredentials) -> Result<Option<User>, ServerFnError> {
|
||||||
use crate::users::validate_user;
|
use crate::users::validate_user;
|
||||||
|
|
||||||
let mut auth_session = extract::<AuthSession<AuthBackend>>().await
|
let mut auth_session = extract::<AuthSession<AuthBackend>>().await
|
||||||
@ -65,12 +71,14 @@ pub async fn login(credentials: UserCredentials) -> Result<bool, ServerFnError>
|
|||||||
let user = validate_user(credentials).await
|
let user = validate_user(credentials).await
|
||||||
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error validating user: {}", e)))?;
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error validating user: {}", e)))?;
|
||||||
|
|
||||||
if let Some(user) = user {
|
if let Some(mut user) = user {
|
||||||
auth_session.login(&user).await
|
auth_session.login(&user).await
|
||||||
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error logging in user: {}", e)))?;
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error logging in user: {}", e)))?;
|
||||||
Ok(true)
|
|
||||||
|
user.password = None;
|
||||||
|
Ok(Some(user))
|
||||||
} else {
|
} else {
|
||||||
Ok(false)
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -84,6 +92,7 @@ pub async fn logout() -> Result<(), ServerFnError> {
|
|||||||
auth_session.logout().await
|
auth_session.logout().await
|
||||||
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
|
||||||
|
|
||||||
|
leptos_axum::redirect("/login");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -120,3 +129,73 @@ pub async fn require_auth() -> Result<(), ServerFnError> {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the current logged-in user
|
||||||
|
/// Returns a Result with the user if they are logged in
|
||||||
|
/// Returns an error if the user is not logged in, or if there is an error getting the user
|
||||||
|
/// Intended to be used in a route to get the current user:
|
||||||
|
/// ```rust
|
||||||
|
/// use leptos::*;
|
||||||
|
/// use libretunes::auth::get_user;
|
||||||
|
/// #[server(endpoint = "user_route")]
|
||||||
|
/// pub async fn user_route() -> Result<(), ServerFnError> {
|
||||||
|
/// let user = get_user().await?;
|
||||||
|
/// println!("Logged in as: {}", user.username);
|
||||||
|
/// // Do something with the user
|
||||||
|
/// Ok(())
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn get_user() -> Result<User, ServerFnError> {
|
||||||
|
let auth_session = extract::<AuthSession<AuthBackend>>().await
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
|
||||||
|
|
||||||
|
auth_session.user.ok_or(ServerFnError::<NoCustomError>::ServerError("User not logged in".to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[server(endpoint = "get_logged_in_user")]
|
||||||
|
pub async fn get_logged_in_user() -> Result<Option<User>, ServerFnError> {
|
||||||
|
let auth_session = extract::<AuthSession<AuthBackend>>().await
|
||||||
|
.map_err(|e| ServerFnError::<NoCustomError>::ServerError(format!("Error getting auth session: {}", e)))?;
|
||||||
|
|
||||||
|
let user = auth_session.user.map(|mut user| {
|
||||||
|
user.password = None;
|
||||||
|
user
|
||||||
|
});
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if a user is an admin
|
||||||
|
/// Returns a Result with a boolean indicating if the user is logged in and an admin
|
||||||
|
#[server(endpoint = "check_admin")]
|
||||||
|
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(())
|
||||||
|
} else {
|
||||||
|
Err(ServerFnError::<NoCustomError>::ServerError(format!("Unauthorized")))
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
@ -1,10 +1,17 @@
|
|||||||
use async_trait::async_trait;
|
|
||||||
use axum_login::{AuthnBackend, AuthUser, UserId};
|
use axum_login::{AuthnBackend, AuthUser, UserId};
|
||||||
use crate::users::UserCredentials;
|
use crate::users::UserCredentials;
|
||||||
use leptos::server_fn::error::ServerFnErrorErr;
|
use leptos::server_fn::error::ServerFnErrorErr;
|
||||||
|
|
||||||
use crate::models::User;
|
use crate::models::User;
|
||||||
|
|
||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
if #[cfg(feature = "ssr")] {
|
||||||
|
use async_trait::async_trait;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl AuthUser for User {
|
impl AuthUser for User {
|
||||||
type Id = i32;
|
type Id = i32;
|
||||||
|
|
||||||
|
@ -2,3 +2,10 @@ pub mod sidebar;
|
|||||||
pub mod dashboard;
|
pub mod dashboard;
|
||||||
pub mod search;
|
pub mod search;
|
||||||
pub mod personal;
|
pub mod personal;
|
||||||
|
pub mod dashboard_tile;
|
||||||
|
pub mod dashboard_row;
|
||||||
|
pub mod upload;
|
||||||
|
pub mod song_list;
|
||||||
|
pub mod loading;
|
||||||
|
pub mod error;
|
||||||
|
pub mod album_info;
|
25
src/components/album_info.rs
Normal file
25
src/components/album_info.rs
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
use leptos::leptos_dom::*;
|
||||||
|
use leptos::*;
|
||||||
|
use crate::albumdata::AlbumData;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn AlbumInfo(albumdata: AlbumData) -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<div class="album-info">
|
||||||
|
<img class="album-image" src={albumdata.image_path} alt="dashboard-tile" />
|
||||||
|
<div class="album-body">
|
||||||
|
<p class="album-title">{albumdata.title}</p>
|
||||||
|
<div class="album-artists">
|
||||||
|
{
|
||||||
|
albumdata.artists.iter().map(|artist| {
|
||||||
|
view! {
|
||||||
|
<a class="album-artist" href={format!("/artist/{}", artist.id.unwrap())}>{artist.name.clone()}</a>
|
||||||
|
}
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
}.into_view()
|
||||||
|
}
|
||||||
|
|
118
src/components/dashboard_row.rs
Normal file
118
src/components/dashboard_row.rs
Normal file
@ -0,0 +1,118 @@
|
|||||||
|
use leptos::html::Ul;
|
||||||
|
use leptos::leptos_dom::*;
|
||||||
|
use leptos::*;
|
||||||
|
use leptos_use::{use_element_size, UseElementSizeReturn, use_scroll, UseScrollReturn};
|
||||||
|
use crate::components::dashboard_tile::DashboardTile;
|
||||||
|
use leptos_icons::*;
|
||||||
|
|
||||||
|
/// A row of dashboard tiles, with a title
|
||||||
|
pub struct DashboardRow {
|
||||||
|
pub title: String,
|
||||||
|
pub tiles: Vec<Box<dyn DashboardTile>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DashboardRow {
|
||||||
|
pub fn new(title: String, tiles: Vec<Box<dyn DashboardTile>>) -> Self {
|
||||||
|
Self {
|
||||||
|
title,
|
||||||
|
tiles,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoView for DashboardRow {
|
||||||
|
fn into_view(self) -> View {
|
||||||
|
let list_ref = create_node_ref::<Ul>();
|
||||||
|
|
||||||
|
// Scroll functions attempt to align the left edge of the scroll area with the left edge of a tile
|
||||||
|
// This is done by scrolling to the nearest multiple of the tile width, plus some for padding
|
||||||
|
|
||||||
|
let scroll_left = move |_| {
|
||||||
|
if let Some(scroll_element) = list_ref.get_untracked() {
|
||||||
|
let client_width = scroll_element.client_width() as f64;
|
||||||
|
let current_pos = scroll_element.scroll_left() as f64;
|
||||||
|
let desired_pos = current_pos - client_width;
|
||||||
|
|
||||||
|
if let Some(first_tile) = scroll_element.first_element_child() {
|
||||||
|
let tile_width = first_tile.client_width() as f64;
|
||||||
|
let scroll_pos = desired_pos + (tile_width - (desired_pos % tile_width));
|
||||||
|
scroll_element.scroll_to_with_x_and_y(scroll_pos, 0.0);
|
||||||
|
} else {
|
||||||
|
warn!("Could not get first tile to scroll left");
|
||||||
|
// Fall back to scrolling by the client width if we can't get the tile width
|
||||||
|
scroll_element.scroll_to_with_x_and_y(desired_pos, 0.0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
warn!("Could not get scroll element to scroll left");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let scroll_right = move |_| {
|
||||||
|
if let Some(scroll_element) = list_ref.get_untracked() {
|
||||||
|
let client_width = scroll_element.client_width() as f64;
|
||||||
|
let current_pos = scroll_element.scroll_left() as f64;
|
||||||
|
let desired_pos = current_pos + client_width;
|
||||||
|
|
||||||
|
if let Some(first_tile) = scroll_element.first_element_child() {
|
||||||
|
let tile_width = first_tile.client_width() as f64;
|
||||||
|
let scroll_pos = desired_pos - (desired_pos % tile_width);
|
||||||
|
scroll_element.scroll_to_with_x_and_y(scroll_pos, 0.0);
|
||||||
|
} else {
|
||||||
|
warn!("Could not get first tile to scroll right");
|
||||||
|
// Fall back to scrolling by the client width if we can't get the tile width
|
||||||
|
scroll_element.scroll_to_with_x_and_y(desired_pos, 0.0);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
warn!("Could not get scroll element to scroll right");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let UseElementSizeReturn { width: scroll_element_width, .. } = use_element_size(list_ref);
|
||||||
|
let UseScrollReturn { x: scroll_x, .. } = use_scroll(list_ref);
|
||||||
|
|
||||||
|
let scroll_right_hidden = Signal::derive(move || {
|
||||||
|
if let Some(scroll_element) = list_ref.get() {
|
||||||
|
if scroll_element.scroll_width() as f64 - scroll_element_width.get() <= scroll_x.get() {
|
||||||
|
"visibility: hidden"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let scroll_left_hidden = Signal::derive(move || {
|
||||||
|
if scroll_x.get() <= 0.0 {
|
||||||
|
"visibility: hidden"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="dashboard-tile-row">
|
||||||
|
<div class="dashboard-tile-row-title-row">
|
||||||
|
<h2>{self.title}</h2>
|
||||||
|
<div class="dashboard-tile-row-scroll-btn">
|
||||||
|
<button on:click=scroll_left tabindex=-1 style=scroll_left_hidden>
|
||||||
|
<Icon class="dashboard-tile-row-scroll" icon=icondata::FiChevronLeft />
|
||||||
|
</button>
|
||||||
|
<button on:click=scroll_right tabindex=-1 style=scroll_right_hidden>
|
||||||
|
<Icon class="dashboard-tile-row-scroll" icon=icondata::FiChevronRight />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<ul _ref={list_ref}>
|
||||||
|
{self.tiles.into_iter().map(|tile_info| {
|
||||||
|
view! {
|
||||||
|
<li>
|
||||||
|
{ tile_info.into_view() }
|
||||||
|
</li>
|
||||||
|
}
|
||||||
|
}).collect::<Vec<_>>()}
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
}.into_view()
|
||||||
|
}
|
||||||
|
}
|
27
src/components/dashboard_tile.rs
Normal file
27
src/components/dashboard_tile.rs
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
use leptos::leptos_dom::*;
|
||||||
|
use leptos::*;
|
||||||
|
|
||||||
|
pub trait DashboardTile {
|
||||||
|
fn image_path(&self) -> String;
|
||||||
|
fn title(&self) -> String;
|
||||||
|
fn link(&self) -> String;
|
||||||
|
fn description(&self) -> Option<String> { None }
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IntoView for &dyn DashboardTile {
|
||||||
|
fn into_view(self) -> View {
|
||||||
|
let link = self.link();
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="dashboard-tile">
|
||||||
|
<a href={link}>
|
||||||
|
<img src={self.image_path()} alt="dashboard-tile" />
|
||||||
|
<p class="dashboard-tile-title">{self.title()}</p>
|
||||||
|
<p class="dashboard-tile-description">
|
||||||
|
{self.description().unwrap_or_default()}
|
||||||
|
</p>
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
}.into_view()
|
||||||
|
}
|
||||||
|
}
|
45
src/components/error.rs
Normal file
45
src/components/error.rs
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use leptos_icons::*;
|
||||||
|
use std::fmt::Display;
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn ServerError<E: Display + 'static>(
|
||||||
|
#[prop(optional, into, default="An Error Occurred".into())]
|
||||||
|
title: TextProp,
|
||||||
|
#[prop(optional, into)]
|
||||||
|
message: TextProp,
|
||||||
|
#[prop(optional, into)]
|
||||||
|
error: Option<ServerFnError<E>>,
|
||||||
|
) -> impl IntoView {
|
||||||
|
view!{
|
||||||
|
<div class="error-container">
|
||||||
|
<div class="error-header">
|
||||||
|
<Icon icon=icondata::BiErrorSolid />
|
||||||
|
<h1>{title}</h1>
|
||||||
|
</div>
|
||||||
|
<p>{message}</p>
|
||||||
|
<p>{error.map(|error| format!("{}", error))}</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn Error<E: Display + 'static>(
|
||||||
|
#[prop(optional, into, default="An Error Occurred".into())]
|
||||||
|
title: TextProp,
|
||||||
|
#[prop(optional, into)]
|
||||||
|
message: TextProp,
|
||||||
|
#[prop(optional, into)]
|
||||||
|
error: Option<E>,
|
||||||
|
) -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<div class="error-container">
|
||||||
|
<div class="error-header">
|
||||||
|
<Icon icon=icondata::BiErrorSolid />
|
||||||
|
<h1>{title}</h1>
|
||||||
|
</div>
|
||||||
|
<p>{message}</p>
|
||||||
|
<p>{error.map(|error| format!("{}", error))}</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
19
src/components/loading.rs
Normal file
19
src/components/loading.rs
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
use leptos::*;
|
||||||
|
|
||||||
|
/// A loading indicator
|
||||||
|
#[component]
|
||||||
|
pub fn Loading() -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<div class="loading"></div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A full page, centered loading indicator
|
||||||
|
#[component]
|
||||||
|
pub fn LoadingPage() -> impl IntoView {
|
||||||
|
view!{
|
||||||
|
<div class="loading-page">
|
||||||
|
<Loading />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,8 @@
|
|||||||
use leptos::leptos_dom::*;
|
use leptos::leptos_dom::*;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_icons::*;
|
use leptos_icons::*;
|
||||||
|
use crate::auth::logout;
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Personal() -> impl IntoView {
|
pub fn Personal() -> impl IntoView {
|
||||||
@ -14,18 +16,66 @@ pub fn Personal() -> impl IntoView {
|
|||||||
#[component]
|
#[component]
|
||||||
pub fn Profile() -> impl IntoView {
|
pub fn Profile() -> impl IntoView {
|
||||||
let (dropdown_open, set_dropdown_open) = create_signal(false);
|
let (dropdown_open, set_dropdown_open) = create_signal(false);
|
||||||
|
let user = GlobalState::logged_in_user();
|
||||||
|
|
||||||
let open_dropdown = move |_| {
|
let open_dropdown = move |_| {
|
||||||
set_dropdown_open.update(|value| *value = !*value);
|
set_dropdown_open.update(|value| *value = !*value);
|
||||||
log!("opened dropdown");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let user_profile_picture = move || {
|
||||||
|
user.get().and_then(|user| {
|
||||||
|
if let Some(user) = user {
|
||||||
|
if user.id.is_none() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(format!("/assets/images/profile/{}.webp", user.id.unwrap()))
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
}
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<div class="profile-container">
|
<div class="profile-container">
|
||||||
|
<div class="profile-name">
|
||||||
|
<Suspense
|
||||||
|
fallback=|| view!{
|
||||||
|
<h1>Not Logged In</h1>
|
||||||
|
}>
|
||||||
|
<Show
|
||||||
|
when=move || user.get().map(|user| user.is_some()).unwrap_or(false)
|
||||||
|
fallback=|| view!{
|
||||||
|
<h1>Not Logged In</h1>
|
||||||
|
}>
|
||||||
|
<h1>{move || user.get().map(|user| user.map(|user| user.username))}</h1>
|
||||||
|
</Show>
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
<div class="profile-icon" on:click=open_dropdown>
|
<div class="profile-icon" on:click=open_dropdown>
|
||||||
<Icon icon=icondata::CgProfile />
|
<Suspense fallback=|| view! { <Icon icon=icondata::CgProfile width="45" height="45"/> }>
|
||||||
|
<Show
|
||||||
|
when=move || user.get().map(|user| user.is_some()).unwrap_or(false)
|
||||||
|
fallback=|| view! { <Icon icon=icondata::CgProfile width="45" height="45"/> }
|
||||||
|
>
|
||||||
|
<object class="profile-image" data={user_profile_picture} type="image/webp">
|
||||||
|
<Icon class="profile-image" icon=icondata::CgProfile width="45" height="45"/>
|
||||||
|
</object>
|
||||||
|
</Show>
|
||||||
|
</Suspense>
|
||||||
</div>
|
</div>
|
||||||
<div class="dropdown-container" style={move || if dropdown_open() {"display: flex"} else {"display: none"}}>
|
<div class="dropdown-container" style={move || if dropdown_open() {"display: flex"} else {"display: none"}}>
|
||||||
|
<Suspense
|
||||||
|
fallback=|| view!{
|
||||||
<DropDownNotLoggedIn />
|
<DropDownNotLoggedIn />
|
||||||
|
}>
|
||||||
|
<Show
|
||||||
|
when=move || user.get().map(|user| user.is_some()).unwrap_or(false)
|
||||||
|
fallback=|| view!{
|
||||||
|
<DropDownNotLoggedIn />
|
||||||
|
}>
|
||||||
|
<DropDownLoggedIn />
|
||||||
|
</Show>
|
||||||
|
</Suspense>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
@ -33,10 +83,33 @@ pub fn Profile() -> impl IntoView {
|
|||||||
#[component]
|
#[component]
|
||||||
pub fn DropDownNotLoggedIn() -> impl IntoView {
|
pub fn DropDownNotLoggedIn() -> impl IntoView {
|
||||||
view! {
|
view! {
|
||||||
<div class="dropdown-not-logged">
|
<div class="dropdown-logged">
|
||||||
<h1>Not Logged in!</h1>
|
<h1>Not Logged In</h1>
|
||||||
<a href="/login"><button class="auth-button">Log In</button></a>
|
<a href="/login"><button class="auth-button">Log In</button></a>
|
||||||
<a href="/signup"><button class="auth-button">Sign up</button></a>
|
<a href="/signup"><button class="auth-button">Sign Up</button></a>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#[component]
|
||||||
|
pub fn DropDownLoggedIn() -> impl IntoView {
|
||||||
|
|
||||||
|
let logout = move |_| {
|
||||||
|
spawn_local(async move {
|
||||||
|
let result = logout().await;
|
||||||
|
if let Err(err) = result {
|
||||||
|
log!("Error logging out: {:?}", err);
|
||||||
|
} else {
|
||||||
|
let user = GlobalState::logged_in_user();
|
||||||
|
user.refetch();
|
||||||
|
log!("Logged out successfully");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="dropdown-logged">
|
||||||
|
<h1>"Logged In"</h1>
|
||||||
|
<button on:click=logout class="auth-button">Log Out</button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,30 +1,34 @@
|
|||||||
use leptos::leptos_dom::*;
|
use leptos::leptos_dom::*;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_icons::*;
|
use leptos_icons::*;
|
||||||
|
use crate::components::upload::*;
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Sidebar(setter: WriteSignal<bool>, active: ReadSignal<bool>) -> impl IntoView {
|
pub fn Sidebar(upload_open: RwSignal<bool>) -> impl IntoView {
|
||||||
let open_dashboard = move |_| {
|
use leptos_router::use_location;
|
||||||
setter.update(|value| *value = true);
|
let location = use_location();
|
||||||
log!("open dashboard");
|
|
||||||
};
|
let on_dashboard = Signal::derive(
|
||||||
let open_search = move |_| {
|
move || location.pathname.get().starts_with("/dashboard") || location.pathname.get() == "/",
|
||||||
setter.update(|value| *value = false);
|
);
|
||||||
log!("open search");
|
|
||||||
};
|
let on_search = Signal::derive(
|
||||||
|
move || location.pathname.get().starts_with("/search"),
|
||||||
|
);
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<div class="sidebar-container">
|
<div class="sidebar-container">
|
||||||
<div class="sidebar-top-container">
|
<div class="sidebar-top-container">
|
||||||
<h2 class="header">LibreTunes</h2>
|
<h2 class="header">LibreTunes</h2>
|
||||||
<div class="buttons" on:click=open_dashboard style={move || if active() {"color: #e1e3e1"} else {""}} >
|
<UploadBtn dialog_open=upload_open />
|
||||||
|
<a class="buttons" href="/dashboard" style={move || if on_dashboard() {"color: #e1e3e1"} else {""}} >
|
||||||
<Icon icon=icondata::OcHomeFillLg />
|
<Icon icon=icondata::OcHomeFillLg />
|
||||||
<h1>Dashboard</h1>
|
<h1>Dashboard</h1>
|
||||||
</div>
|
</a>
|
||||||
<div class="buttons" on:click=open_search style={move || if !active() {"color: #e1e3e1"} else {""}}>
|
<a class="buttons" href="/search" style={move || if on_search() {"color: #e1e3e1"} else {""}}>
|
||||||
<Icon icon=icondata::BiSearchRegular />
|
<Icon icon=icondata::BiSearchRegular />
|
||||||
<h1>Search</h1>
|
<h1>Search</h1>
|
||||||
</div>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<Bottom />
|
<Bottom />
|
||||||
|
|
||||||
|
270
src/components/song_list.rs
Normal file
270
src/components/song_list.rs
Normal file
@ -0,0 +1,270 @@
|
|||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use leptos::*;
|
||||||
|
use leptos::logging::*;
|
||||||
|
use leptos_icons::*;
|
||||||
|
|
||||||
|
use crate::api::songs::*;
|
||||||
|
use crate::songdata::SongData;
|
||||||
|
use crate::models::{Album, Artist};
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
|
|
||||||
|
const LIKE_DISLIKE_BTN_SIZE: &str = "2em";
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn SongList(songs: Vec<SongData>) -> impl IntoView {
|
||||||
|
__SongListInner(songs.into_iter().map(|song| (song, ())).collect::<Vec<_>>(), false)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn SongListExtra<T>(songs: Vec<(SongData, T)>) -> impl IntoView where
|
||||||
|
T: Clone + IntoView + 'static
|
||||||
|
{
|
||||||
|
__SongListInner(songs, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
fn SongListInner<T>(songs: Vec<(SongData, T)>, show_extra: bool) -> impl IntoView where
|
||||||
|
T: Clone + IntoView + 'static
|
||||||
|
{
|
||||||
|
let songs = Rc::new(songs);
|
||||||
|
let songs_2 = songs.clone();
|
||||||
|
|
||||||
|
// Signal that acts as a callback for a song list item to queue songs after it in the list
|
||||||
|
let (handle_queue_remaining, do_queue_remaining) = create_signal(None);
|
||||||
|
create_effect(move |_| {
|
||||||
|
let clicked_index = handle_queue_remaining.get();
|
||||||
|
|
||||||
|
if let Some(index) = clicked_index {
|
||||||
|
GlobalState::play_status().update(|status| {
|
||||||
|
let song: &(SongData, T) = songs.get(index).expect("Invalid song list item index");
|
||||||
|
|
||||||
|
if status.queue.front().map(|song| song.id) == Some(song.0.id) {
|
||||||
|
// If the clicked song is already at the front of the queue, just play it
|
||||||
|
status.playing = true;
|
||||||
|
} else {
|
||||||
|
// Otherwise, add the currently playing song to the history,
|
||||||
|
// clear the queue, and queue the clicked song and other after it
|
||||||
|
if let Some(last_playing) = status.queue.pop_front() {
|
||||||
|
status.history.push_back(last_playing);
|
||||||
|
}
|
||||||
|
|
||||||
|
status.queue.clear();
|
||||||
|
status.queue.extend(songs.iter().skip(index).map(|(song, _)| song.clone()));
|
||||||
|
status.playing = true;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<table class="song-list">
|
||||||
|
{
|
||||||
|
songs_2.iter().enumerate().map(|(list_index, (song, extra))| {
|
||||||
|
let song_id = song.id;
|
||||||
|
let playing = create_rw_signal(false);
|
||||||
|
|
||||||
|
create_effect(move |_| {
|
||||||
|
GlobalState::play_status().with(|status| {
|
||||||
|
playing.set(status.queue.front().map(|song| song.id) == Some(song_id) && status.playing);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<SongListItem song={song.clone()} song_playing=playing.into()
|
||||||
|
extra={if show_extra { Some(extra.clone()) } else { None }} list_index do_queue_remaining/>
|
||||||
|
}
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
</table>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn SongListItem<T>(song: SongData, song_playing: MaybeSignal<bool>, extra: Option<T>,
|
||||||
|
list_index: usize, do_queue_remaining: WriteSignal<Option<usize>>) -> impl IntoView where
|
||||||
|
T: IntoView + 'static
|
||||||
|
{
|
||||||
|
let liked = create_rw_signal(song.like_dislike.map(|(liked, _)| liked).unwrap_or(false));
|
||||||
|
let disliked = create_rw_signal(song.like_dislike.map(|(_, disliked)| disliked).unwrap_or(false));
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<tr class="song-list-item">
|
||||||
|
<td class="song-image"><SongImage image_path=song.image_path song_playing
|
||||||
|
list_index do_queue_remaining /></td>
|
||||||
|
<td class="song-title"><p>{song.title}</p></td>
|
||||||
|
<td class="song-list-spacer"></td>
|
||||||
|
<td class="song-artists"><SongArtists artists=song.artists /></td>
|
||||||
|
<td class="song-list-spacer"></td>
|
||||||
|
<td class="song-album"><SongAlbum album=song.album /></td>
|
||||||
|
<td class="song-list-spacer-big"></td>
|
||||||
|
<td class="song-like-dislike"><SongLikeDislike song_id=song.id liked disliked/></td>
|
||||||
|
<td>{format!("{}:{:02}", song.duration / 60, song.duration % 60)}</td>
|
||||||
|
{extra.map(|extra| view! {
|
||||||
|
<td class="song-list-spacer"></td>
|
||||||
|
<td>{extra}</td>
|
||||||
|
})}
|
||||||
|
</tr>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Display the song's image, with an overlay if the song is playing
|
||||||
|
/// When the song list item is hovered, the overlay will show the play button
|
||||||
|
#[component]
|
||||||
|
fn SongImage(image_path: String, song_playing: MaybeSignal<bool>, list_index: usize,
|
||||||
|
do_queue_remaining: WriteSignal<Option<usize>>) -> impl IntoView
|
||||||
|
{
|
||||||
|
let play_song = move |_| {
|
||||||
|
do_queue_remaining.set(Some(list_index));
|
||||||
|
};
|
||||||
|
|
||||||
|
let pause_song = move |_| {
|
||||||
|
GlobalState::play_status().update(|status| {
|
||||||
|
status.playing = false;
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<img class="song-image" src={image_path}/>
|
||||||
|
{move || if song_playing.get() {
|
||||||
|
view! { <Icon class="song-image-overlay song-playing-overlay"
|
||||||
|
icon=icondata::BsPauseFill on:click=pause_song /> }.into_view()
|
||||||
|
} else {
|
||||||
|
view! { <Icon class="song-image-overlay hide-until-hover"
|
||||||
|
icon=icondata::BsPlayFill on:click=play_song /> }.into_view()
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Displays a song's artists, with links to their artist pages
|
||||||
|
#[component]
|
||||||
|
fn SongArtists(artists: Vec<Artist>) -> impl IntoView {
|
||||||
|
let num_artists = artists.len() as isize;
|
||||||
|
|
||||||
|
artists.iter().enumerate().map(|(i, artist)| {
|
||||||
|
let i = i as isize;
|
||||||
|
|
||||||
|
view! {
|
||||||
|
{
|
||||||
|
if let Some(id) = artist.id {
|
||||||
|
view! { <a href={format!("/artist/{}", id)}>{artist.name.clone()}</a> }.into_view()
|
||||||
|
} else {
|
||||||
|
view! { <span>{artist.name.clone()}</span> }.into_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
{if i < num_artists - 2 { ", " } else if i == num_artists - 2 { " & " } else { "" }}
|
||||||
|
}
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Display a song's album, with a link to the album page
|
||||||
|
#[component]
|
||||||
|
fn SongAlbum(album: Option<Album>) -> impl IntoView {
|
||||||
|
album.as_ref().map(|album| {
|
||||||
|
view! {
|
||||||
|
<span>
|
||||||
|
{
|
||||||
|
if let Some(id) = album.id {
|
||||||
|
view! { <a href={format!("/album/{}", id)}>{album.title.clone()}</a> }.into_view()
|
||||||
|
} else {
|
||||||
|
view! { <span>{album.title.clone()}</span> }.into_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</span>
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Display like and dislike buttons for a song, and indicate if the song is liked or disliked
|
||||||
|
#[component]
|
||||||
|
fn SongLikeDislike(
|
||||||
|
#[prop(into)]
|
||||||
|
song_id: MaybeSignal<i32>,
|
||||||
|
liked: RwSignal<bool>,
|
||||||
|
disliked: RwSignal<bool>) -> impl IntoView
|
||||||
|
{
|
||||||
|
let like_icon = Signal::derive(move || {
|
||||||
|
if liked.get() {
|
||||||
|
icondata::TbThumbUpFilled
|
||||||
|
} else {
|
||||||
|
icondata::TbThumbUp
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let dislike_icon = Signal::derive(move || {
|
||||||
|
if disliked.get() {
|
||||||
|
icondata::TbThumbDownFilled
|
||||||
|
} else {
|
||||||
|
icondata::TbThumbDown
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let like_class = MaybeProp::derive(move || {
|
||||||
|
if liked.get() {
|
||||||
|
Some(TextProp::from("controlbtn"))
|
||||||
|
} else {
|
||||||
|
Some(TextProp::from("controlbtn hide-until-hover"))
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let dislike_class = MaybeProp::derive(move || {
|
||||||
|
if disliked.get() {
|
||||||
|
Some(TextProp::from("controlbtn hmirror"))
|
||||||
|
} else {
|
||||||
|
Some(TextProp::from("controlbtn hmirror hide-until-hover"))
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// If an error occurs, check the like/dislike status again to ensure consistency
|
||||||
|
let check_like_dislike = move || {
|
||||||
|
spawn_local(async move {
|
||||||
|
match get_like_dislike_song(song_id.get_untracked()).await {
|
||||||
|
Ok((like, dislike)) => {
|
||||||
|
liked.set(like);
|
||||||
|
disliked.set(dislike);
|
||||||
|
},
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let toggle_like = move |_| {
|
||||||
|
let new_liked = !liked.get_untracked();
|
||||||
|
liked.set(new_liked);
|
||||||
|
disliked.set(disliked.get_untracked() && !liked.get_untracked());
|
||||||
|
|
||||||
|
spawn_local(async move {
|
||||||
|
match set_like_song(song_id.get_untracked(), new_liked).await {
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(e) => {
|
||||||
|
error!("Error setting like: {}", e);
|
||||||
|
check_like_dislike();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let toggle_dislike = move |_| {
|
||||||
|
disliked.set(!disliked.get_untracked());
|
||||||
|
liked.set(liked.get_untracked() && !disliked.get_untracked());
|
||||||
|
|
||||||
|
spawn_local(async move {
|
||||||
|
match set_dislike_song(song_id.get_untracked(), disliked.get_untracked()).await {
|
||||||
|
Ok(_) => {},
|
||||||
|
Err(e) => {
|
||||||
|
error!("Error setting dislike: {}", e);
|
||||||
|
check_like_dislike();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<button on:click=toggle_dislike>
|
||||||
|
<Icon class=dislike_class width=LIKE_DISLIKE_BTN_SIZE height=LIKE_DISLIKE_BTN_SIZE icon=dislike_icon />
|
||||||
|
</button>
|
||||||
|
<button on:click=toggle_like>
|
||||||
|
<Icon class=like_class width=LIKE_DISLIKE_BTN_SIZE height=LIKE_DISLIKE_BTN_SIZE icon=like_icon />
|
||||||
|
</button>
|
||||||
|
}
|
||||||
|
}
|
245
src/components/upload.rs
Normal file
245
src/components/upload.rs
Normal file
@ -0,0 +1,245 @@
|
|||||||
|
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" on:click=open_dialog>
|
||||||
|
<div class="add-sign">
|
||||||
|
<Icon icon=icondata::IoAddSharp />
|
||||||
|
</div>
|
||||||
|
Upload
|
||||||
|
</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>
|
||||||
|
}
|
||||||
|
}
|
@ -12,6 +12,7 @@ cfg_if! { if #[cfg(feature = "ssr")] {
|
|||||||
use tower_http::services::ServeDir;
|
use tower_http::services::ServeDir;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use crate::app::App;
|
use crate::app::App;
|
||||||
|
use std::str::FromStr;
|
||||||
|
|
||||||
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
|
pub async fn file_and_error_handler(uri: Uri, State(options): State<LeptosOptions>, req: Request<Body>) -> AxumResponse {
|
||||||
let root = options.site_root.clone();
|
let root = options.site_root.clone();
|
||||||
@ -27,14 +28,43 @@ cfg_if! { if #[cfg(feature = "ssr")] {
|
|||||||
|
|
||||||
pub async fn get_static_file(uri: Uri, root: &str) -> Result<Response<Body>, (StatusCode, String)> {
|
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();
|
let req = Request::builder().uri(uri.clone()).body(Body::empty()).unwrap();
|
||||||
|
|
||||||
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
|
// `ServeDir` implements `tower::Service` so we can call it with `tower::ServiceExt::oneshot`
|
||||||
// This path is relative to the cargo root
|
// This path is relative to the cargo root
|
||||||
match ServeDir::new(root).oneshot(req).await {
|
match ServeDir::new(root).oneshot(req).await.ok() {
|
||||||
Ok(res) => Ok(res.into_response()),
|
Some(res) => Ok(res.into_response()),
|
||||||
Err(err) => Err((
|
None => Err((
|
||||||
StatusCode::INTERNAL_SERVER_ERROR,
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
format!("Something went wrong: {err}"),
|
format!("Something went wrong"),
|
||||||
)),
|
)),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub enum AssetType {
|
||||||
|
Audio,
|
||||||
|
Image,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_asset_file(filename: String, asset_type: AssetType) -> Result<Response<Body>, (StatusCode, String)> {
|
||||||
|
const DEFAULT_AUDIO_PATH: &str = "assets/audio";
|
||||||
|
const DEFAULT_IMAGE_PATH: &str = "assets/images";
|
||||||
|
|
||||||
|
let root = match asset_type {
|
||||||
|
AssetType::Audio => std::env::var("LIBRETUNES_AUDIO_PATH").unwrap_or(DEFAULT_AUDIO_PATH.to_string()),
|
||||||
|
AssetType::Image => std::env::var("LIBRETUNES_IMAGE_PATH").unwrap_or(DEFAULT_IMAGE_PATH.to_string()),
|
||||||
|
};
|
||||||
|
|
||||||
|
// Create a Uri from the filename
|
||||||
|
// ServeDir expects a leading `/`
|
||||||
|
let uri = Uri::from_str(format!("/{}", filename).as_str());
|
||||||
|
|
||||||
|
match uri {
|
||||||
|
Ok(uri) => get_static_file(uri, root.as_str()).await,
|
||||||
|
Err(_) => Err((
|
||||||
|
StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
format!("Attempted to serve an invalid file"),
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}}
|
}}
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
pub mod app;
|
pub mod app;
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod songdata;
|
pub mod songdata;
|
||||||
|
pub mod albumdata;
|
||||||
|
pub mod artistdata;
|
||||||
pub mod playstatus;
|
pub mod playstatus;
|
||||||
pub mod playbar;
|
pub mod playbar;
|
||||||
pub mod database;
|
pub mod database;
|
||||||
@ -13,6 +15,10 @@ pub mod users;
|
|||||||
pub mod search;
|
pub mod search;
|
||||||
pub mod fileserv;
|
pub mod fileserv;
|
||||||
pub mod error_template;
|
pub mod error_template;
|
||||||
|
pub mod api;
|
||||||
|
pub mod upload;
|
||||||
|
pub mod util;
|
||||||
|
|
||||||
use cfg_if::cfg_if;
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
cfg_if! {
|
cfg_if! {
|
||||||
|
48
src/main.rs
48
src/main.rs
@ -1,10 +1,10 @@
|
|||||||
// Needed for building in Docker container
|
// Needed for building in Docker container
|
||||||
// See https://github.com/clux/muslrust?tab=readme-ov-file#diesel-and-pq-builds
|
// See https://github.com/clux/muslrust?tab=readme-ov-file#diesel-and-pq-builds
|
||||||
// See https://github.com/sgrif/pq-sys/issues/25
|
// See https://github.com/sgrif/pq-sys/issues/25
|
||||||
#[cfg(target = "x86_64-unknown-linux-musl")]
|
#[cfg(target_env = "musl")]
|
||||||
extern crate openssl;
|
extern crate openssl;
|
||||||
|
|
||||||
#[cfg(target = "x86_64-unknown-linux-musl")]
|
#[cfg(target_env = "musl")]
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate diesel;
|
extern crate diesel;
|
||||||
|
|
||||||
@ -14,22 +14,33 @@ extern crate diesel_migrations;
|
|||||||
#[cfg(feature = "ssr")]
|
#[cfg(feature = "ssr")]
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() {
|
async fn main() {
|
||||||
use axum::{routing::get, Router};
|
use axum::{routing::get, Router, extract::Path, middleware::from_fn};
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_axum::{generate_route_list, LeptosRoutes};
|
use leptos_axum::{generate_route_list, LeptosRoutes};
|
||||||
use libretunes::app::*;
|
use libretunes::app::*;
|
||||||
use libretunes::fileserv::{file_and_error_handler, get_static_file};
|
use libretunes::util::require_auth::require_auth_middleware;
|
||||||
use tower_sessions::SessionManagerLayer;
|
use libretunes::fileserv::{file_and_error_handler, get_asset_file, get_static_file, AssetType};
|
||||||
|
use axum_login::tower_sessions::SessionManagerLayer;
|
||||||
use tower_sessions_redis_store::{fred::prelude::*, RedisStore};
|
use tower_sessions_redis_store::{fred::prelude::*, RedisStore};
|
||||||
use axum_login::AuthManagerLayerBuilder;
|
use axum_login::AuthManagerLayerBuilder;
|
||||||
use libretunes::auth_backend::AuthBackend;
|
use libretunes::auth_backend::AuthBackend;
|
||||||
|
use log::*;
|
||||||
|
|
||||||
use dotenv::dotenv;
|
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 dotenvy::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 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_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");
|
let redis_pool = RedisPool::new(redis_config, None, None, None, 1).expect("Unable to create Redis pool");
|
||||||
@ -50,35 +61,24 @@ async fn main() {
|
|||||||
|
|
||||||
let app = Router::new()
|
let app = Router::new()
|
||||||
.leptos_routes(&leptos_options, routes, App)
|
.leptos_routes(&leptos_options, routes, App)
|
||||||
|
.route("/assets/audio/:song", get(|Path(song) : Path<String>| get_asset_file(song, AssetType::Audio)))
|
||||||
|
.route("/assets/images/:image", get(|Path(image) : Path<String>| get_asset_file(image, AssetType::Image)))
|
||||||
.route("/assets/*uri", get(|uri| get_static_file(uri, "")))
|
.route("/assets/*uri", get(|uri| get_static_file(uri, "")))
|
||||||
|
.layer(from_fn(require_auth_middleware))
|
||||||
.layer(auth_layer)
|
.layer(auth_layer)
|
||||||
.fallback(file_and_error_handler)
|
.fallback(file_and_error_handler)
|
||||||
.with_state(leptos_options);
|
.with_state(leptos_options);
|
||||||
|
|
||||||
println!("listening on http://{}", &addr);
|
|
||||||
|
|
||||||
let listener = tokio::net::TcpListener::bind(&addr).await.expect(&format!("Could not bind to {}", &addr));
|
let listener = tokio::net::TcpListener::bind(&addr).await.expect(&format!("Could not bind to {}", &addr));
|
||||||
|
|
||||||
|
info!("Listening on http://{}", &addr);
|
||||||
|
|
||||||
axum::serve(listener, app.into_make_service()).await.expect("Server failed");
|
axum::serve(listener, app.into_make_service()).await.expect("Server failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(any(feature = "ssr", feature = "csr")))]
|
#[cfg(not(feature = "ssr"))]
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
519
src/models.rs
519
src/models.rs
@ -1,5 +1,4 @@
|
|||||||
use std::time::SystemTime;
|
use chrono::{NaiveDate, NaiveDateTime};
|
||||||
use time::Date;
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
use cfg_if::cfg_if;
|
use cfg_if::cfg_if;
|
||||||
@ -7,8 +6,10 @@ use cfg_if::cfg_if;
|
|||||||
cfg_if! {
|
cfg_if! {
|
||||||
if #[cfg(feature = "ssr")] {
|
if #[cfg(feature = "ssr")] {
|
||||||
use diesel::prelude::*;
|
use diesel::prelude::*;
|
||||||
use crate::database::PgPooledConn;
|
use crate::database::*;
|
||||||
use std::error::Error;
|
use std::error::Error;
|
||||||
|
use crate::songdata::SongData;
|
||||||
|
use crate::albumdata::AlbumData;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -39,15 +40,286 @@ pub struct User {
|
|||||||
#[cfg_attr(feature = "ssr", diesel(deserialize_as = String))]
|
#[cfg_attr(feature = "ssr", diesel(deserialize_as = String))]
|
||||||
pub password: Option<String>,
|
pub password: Option<String>,
|
||||||
/// 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 = NaiveDateTime))]
|
||||||
pub created_at: Option<SystemTime>,
|
pub created_at: Option<NaiveDateTime>,
|
||||||
|
/// Whether the user is an admin
|
||||||
|
pub admin: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl User {
|
||||||
|
/// Get the history of songs listened to by this user from the database
|
||||||
|
///
|
||||||
|
/// The returned history will be ordered by date in descending order,
|
||||||
|
/// and a limit of N will select the N most recent entries.
|
||||||
|
/// The `id` field of this user must be present (Some) to get history
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `limit` - An optional limit on the number of history entries to return
|
||||||
|
/// * `conn` - A mutable reference to a database connection
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// * `Result<Vec<HistoryEntry>, Box<dyn Error>>` -
|
||||||
|
/// A result indicating success with a vector of history entries, or an error
|
||||||
|
///
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub fn get_history(self: &Self, limit: Option<i64>, conn: &mut PgPooledConn) ->
|
||||||
|
Result<Vec<HistoryEntry>, Box<dyn Error>> {
|
||||||
|
use crate::schema::song_history::dsl::*;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("Artist id must be present (Some) to get history")?;
|
||||||
|
|
||||||
|
let my_history =
|
||||||
|
if let Some(limit) = limit {
|
||||||
|
song_history
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.order(date.desc())
|
||||||
|
.limit(limit)
|
||||||
|
.load(conn)?
|
||||||
|
} else {
|
||||||
|
song_history
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.load(conn)?
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(my_history)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the history of songs listened to by this user from the database
|
||||||
|
///
|
||||||
|
/// The returned history will be ordered by date in descending order,
|
||||||
|
/// and a limit of N will select the N most recent entries.
|
||||||
|
/// The `id` field of this user must be present (Some) to get history
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `limit` - An optional limit on the number of history entries to return
|
||||||
|
/// * `conn` - A mutable reference to a database connection
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// * `Result<Vec<(SystemTime, Song)>, Box<dyn Error>>` -
|
||||||
|
/// A result indicating success with a vector of listen dates and songs, or an error
|
||||||
|
///
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub fn get_history_songs(self: &Self, limit: Option<i64>, conn: &mut PgPooledConn) ->
|
||||||
|
Result<Vec<(NaiveDateTime, Song)>, Box<dyn Error>> {
|
||||||
|
use crate::schema::songs::dsl::*;
|
||||||
|
use crate::schema::song_history::dsl::*;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("Artist id must be present (Some) to get history")?;
|
||||||
|
|
||||||
|
let my_history =
|
||||||
|
if let Some(limit) = limit {
|
||||||
|
song_history
|
||||||
|
.inner_join(songs)
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.order(date.desc())
|
||||||
|
.limit(limit)
|
||||||
|
.select((date, songs::all_columns()))
|
||||||
|
.load(conn)?
|
||||||
|
} else {
|
||||||
|
song_history
|
||||||
|
.inner_join(songs)
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.order(date.desc())
|
||||||
|
.select((date, songs::all_columns()))
|
||||||
|
.load(conn)?
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(my_history)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Add a song to this user's history in the database
|
||||||
|
///
|
||||||
|
/// The date of the history entry will be the current time
|
||||||
|
/// The `id` field of this user must be present (Some) to add history
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `song_id` - The id of the song to add to this user's history
|
||||||
|
/// * `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_history(self: &Self, song_id: i32, conn: &mut PgPooledConn) -> Result<(), Box<dyn Error>> {
|
||||||
|
use crate::schema::song_history;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("Artist id must be present (Some) to add history")?;
|
||||||
|
|
||||||
|
diesel::insert_into(song_history::table)
|
||||||
|
.values((song_history::user_id.eq(my_id), song_history::song_id.eq(song_id)))
|
||||||
|
.execute(conn)?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if this user has listened to a song
|
||||||
|
///
|
||||||
|
/// The `id` field of this user must be present (Some) to check history
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `song_id` - The id of the song to check if this user has listened to
|
||||||
|
/// * `conn` - A mutable reference to a database connection
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// * `Result<bool, Box<dyn Error>>` - A result indicating success with a boolean value, or an error
|
||||||
|
///
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub fn has_listened_to(self: &Self, song_id: i32, conn: &mut PgPooledConn) -> Result<bool, Box<dyn Error>> {
|
||||||
|
use crate::schema::song_history::{self, user_id};
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("Artist id must be present (Some) to check history")?;
|
||||||
|
|
||||||
|
let has_listened = song_history::table
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.filter(song_history::song_id.eq(song_id))
|
||||||
|
.first::<HistoryEntry>(conn)
|
||||||
|
.optional()?
|
||||||
|
.is_some();
|
||||||
|
|
||||||
|
Ok(has_listened)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Like or unlike a song for this user
|
||||||
|
/// If likeing a song, remove dislike if it exists
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn set_like_song(self: &Self, song_id: i32, like: bool, conn: &mut PgPooledConn) ->
|
||||||
|
Result<(), Box<dyn Error>> {
|
||||||
|
use log::*;
|
||||||
|
debug!("Setting like for song {} to {}", song_id, like);
|
||||||
|
|
||||||
|
use crate::schema::song_likes;
|
||||||
|
use crate::schema::song_dislikes;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("User id must be present (Some) to like/un-like a song")?;
|
||||||
|
|
||||||
|
if like {
|
||||||
|
diesel::insert_into(song_likes::table)
|
||||||
|
.values((song_likes::song_id.eq(song_id), song_likes::user_id.eq(my_id)))
|
||||||
|
.execute(conn)?;
|
||||||
|
|
||||||
|
// Remove dislike if it exists
|
||||||
|
diesel::delete(song_dislikes::table.filter(song_dislikes::song_id.eq(song_id)
|
||||||
|
.and(song_dislikes::user_id.eq(my_id))))
|
||||||
|
.execute(conn)?;
|
||||||
|
} else {
|
||||||
|
diesel::delete(song_likes::table.filter(song_likes::song_id.eq(song_id).and(song_likes::user_id.eq(my_id))))
|
||||||
|
.execute(conn)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the like status of a song for this user
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn get_like_song(self: &Self, song_id: i32, conn: &mut PgPooledConn) -> Result<bool, Box<dyn Error>> {
|
||||||
|
use crate::schema::song_likes;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("User id must be present (Some) to get like status of a song")?;
|
||||||
|
|
||||||
|
let like = song_likes::table
|
||||||
|
.filter(song_likes::song_id.eq(song_id).and(song_likes::user_id.eq(my_id)))
|
||||||
|
.first::<(i32, i32)>(conn)
|
||||||
|
.optional()?
|
||||||
|
.is_some();
|
||||||
|
|
||||||
|
Ok(like)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get songs liked by this user
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn get_liked_songs(self: &Self, conn: &mut PgPooledConn) -> Result<Vec<Song>, Box<dyn Error>> {
|
||||||
|
use crate::schema::songs::dsl::*;
|
||||||
|
use crate::schema::song_likes::dsl::*;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("User id must be present (Some) to get liked songs")?;
|
||||||
|
|
||||||
|
let my_songs = songs
|
||||||
|
.inner_join(song_likes)
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.select(songs::all_columns())
|
||||||
|
.load(conn)?;
|
||||||
|
|
||||||
|
Ok(my_songs)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Dislike or remove dislike from a song for this user
|
||||||
|
/// If disliking a song, remove like if it exists
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn set_dislike_song(self: &Self, song_id: i32, dislike: bool, conn: &mut PgPooledConn) ->
|
||||||
|
Result<(), Box<dyn Error>> {
|
||||||
|
use log::*;
|
||||||
|
debug!("Setting dislike for song {} to {}", song_id, dislike);
|
||||||
|
|
||||||
|
use crate::schema::song_likes;
|
||||||
|
use crate::schema::song_dislikes;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("User id must be present (Some) to dislike/un-dislike a song")?;
|
||||||
|
|
||||||
|
if dislike {
|
||||||
|
diesel::insert_into(song_dislikes::table)
|
||||||
|
.values((song_dislikes::song_id.eq(song_id), song_dislikes::user_id.eq(my_id)))
|
||||||
|
.execute(conn)?;
|
||||||
|
|
||||||
|
// Remove like if it exists
|
||||||
|
diesel::delete(song_likes::table.filter(song_likes::song_id.eq(song_id)
|
||||||
|
.and(song_likes::user_id.eq(my_id))))
|
||||||
|
.execute(conn)?;
|
||||||
|
} else {
|
||||||
|
diesel::delete(song_dislikes::table.filter(song_dislikes::song_id.eq(song_id)
|
||||||
|
.and(song_dislikes::user_id.eq(my_id))))
|
||||||
|
.execute(conn)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get the dislike status of a song for this user
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn get_dislike_song(self: &Self, song_id: i32, conn: &mut PgPooledConn) -> Result<bool, Box<dyn Error>> {
|
||||||
|
use crate::schema::song_dislikes;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("User id must be present (Some) to get dislike status of a song")?;
|
||||||
|
|
||||||
|
let dislike = song_dislikes::table
|
||||||
|
.filter(song_dislikes::song_id.eq(song_id).and(song_dislikes::user_id.eq(my_id)))
|
||||||
|
.first::<(i32, i32)>(conn)
|
||||||
|
.optional()?
|
||||||
|
.is_some();
|
||||||
|
|
||||||
|
Ok(dislike)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get songs disliked by this user
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub async fn get_disliked_songs(self: &Self, conn: &mut PgPooledConn) -> Result<Vec<Song>, Box<dyn Error>> {
|
||||||
|
use crate::schema::songs::dsl::*;
|
||||||
|
use crate::schema::song_likes::dsl::*;
|
||||||
|
|
||||||
|
let my_id = self.id.ok_or("User id must be present (Some) to get disliked songs")?;
|
||||||
|
|
||||||
|
let my_songs = songs
|
||||||
|
.inner_join(song_likes)
|
||||||
|
.filter(user_id.eq(my_id))
|
||||||
|
.select(songs::all_columns())
|
||||||
|
.load(conn)?;
|
||||||
|
|
||||||
|
Ok(my_songs)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Model for an artist
|
/// Model for an artist
|
||||||
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
|
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable, Identifiable))]
|
||||||
#[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)]
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
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))]
|
||||||
@ -162,13 +434,33 @@ impl Artist {
|
|||||||
|
|
||||||
Ok(my_songs)
|
Ok(my_songs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Display a list of artists as a string.
|
||||||
|
///
|
||||||
|
/// For one artist, displays [artist1]. For two artists, displays [artist1] & [artist2].
|
||||||
|
/// For three or more artists, displays [artist1], [artist2], & [artist3].
|
||||||
|
pub fn display_list(artists: &Vec<Artist>) -> String {
|
||||||
|
let mut artist_list = String::new();
|
||||||
|
|
||||||
|
for (i, artist) in artists.iter().enumerate() {
|
||||||
|
if i == 0 {
|
||||||
|
artist_list.push_str(&artist.name);
|
||||||
|
} else if i == artists.len() - 1 {
|
||||||
|
artist_list.push_str(&format!(" & {}", artist.name));
|
||||||
|
} else {
|
||||||
|
artist_list.push_str(&format!(", {}", artist.name));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
artist_list
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Model for an album
|
/// Model for an album
|
||||||
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
|
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable, Identifiable))]
|
||||||
#[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)]
|
#[derive(Serialize, Deserialize, Clone, Debug)]
|
||||||
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))]
|
||||||
@ -176,7 +468,9 @@ pub struct Album {
|
|||||||
/// The album's title
|
/// The album's title
|
||||||
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<NaiveDate>,
|
||||||
|
/// The path to the album's image file
|
||||||
|
pub image_path: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Album {
|
impl Album {
|
||||||
@ -206,7 +500,7 @@ impl Album {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get songs by this artist from the database
|
/// Get songs by this album from the database
|
||||||
///
|
///
|
||||||
/// The `id` field of this album must be present (Some) to get songs
|
/// The `id` field of this album must be present (Some) to get songs
|
||||||
///
|
///
|
||||||
@ -233,6 +527,143 @@ impl Album {
|
|||||||
|
|
||||||
Ok(my_songs)
|
Ok(my_songs)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Obtain an album from its albumid
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `album_id` - The id of the album to select
|
||||||
|
/// * `conn` - A mutable reference to a database connection
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// * `Result<Album, Box<dyn Error>>` - A result indicating success with the desired album, or an error
|
||||||
|
///
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub fn get_album_data(album_id: i32, conn: &mut PgPooledConn) -> Result<AlbumData, Box<dyn Error>> {
|
||||||
|
use crate::schema::*;
|
||||||
|
|
||||||
|
let artist_list: Vec<Artist> = album_artists::table
|
||||||
|
.filter(album_artists::album_id.eq(album_id))
|
||||||
|
.inner_join(artists::table.on(album_artists::artist_id.eq(artists::id)))
|
||||||
|
.select(
|
||||||
|
artists::all_columns
|
||||||
|
)
|
||||||
|
.load(conn)?;
|
||||||
|
|
||||||
|
// Get info of album
|
||||||
|
let albuminfo = albums::table
|
||||||
|
.filter(albums::id.eq(album_id))
|
||||||
|
.first::<Album>(conn)?;
|
||||||
|
|
||||||
|
let img = albuminfo.image_path.unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string());
|
||||||
|
|
||||||
|
let albumdata = AlbumData {
|
||||||
|
id: albuminfo.id.unwrap(),
|
||||||
|
title: albuminfo.title,
|
||||||
|
artists: artist_list,
|
||||||
|
release_date: albuminfo.release_date,
|
||||||
|
image_path: img
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(albumdata)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Obtain an album from its albumid
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `album_id` - The id of the album to select
|
||||||
|
/// * `conn` - A mutable reference to a database connection
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// * `Result<Album, Box<dyn Error>>` - A result indicating success with the desired album, or an error
|
||||||
|
///
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub fn get_song_data(album_id: i32, user_like_dislike: Option<User>, conn: &mut PgPooledConn) -> Result<Vec<SongData>, Box<dyn Error>> {
|
||||||
|
use crate::schema::*;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
let song_list = if let Some(user_like_dislike) = user_like_dislike {
|
||||||
|
let user_like_dislike_id = user_like_dislike.id.unwrap();
|
||||||
|
let song_list: Vec<(Album, Option<Song>, Option<Artist>, Option<(i32, i32)>, Option<(i32, i32)>)> =
|
||||||
|
albums::table
|
||||||
|
.find(album_id)
|
||||||
|
.left_join(songs::table.on(albums::id.nullable().eq(songs::album_id)))
|
||||||
|
.left_join(song_artists::table.inner_join(artists::table).on(songs::id.eq(song_artists::song_id)))
|
||||||
|
.left_join(song_likes::table.on(songs::id.eq(song_likes::song_id).and(song_likes::user_id.eq(user_like_dislike_id))))
|
||||||
|
.left_join(song_dislikes::table.on(songs::id.eq(song_dislikes::song_id).and(song_dislikes::user_id.eq(user_like_dislike_id))))
|
||||||
|
.select((
|
||||||
|
albums::all_columns,
|
||||||
|
songs::all_columns.nullable(),
|
||||||
|
artists::all_columns.nullable(),
|
||||||
|
song_likes::all_columns.nullable(),
|
||||||
|
song_dislikes::all_columns.nullable()
|
||||||
|
))
|
||||||
|
.order(songs::track.asc())
|
||||||
|
.load(conn)?;
|
||||||
|
song_list
|
||||||
|
} else {
|
||||||
|
let song_list: Vec<(Album, Option<Song>, Option<Artist>)> =
|
||||||
|
albums::table
|
||||||
|
.find(album_id)
|
||||||
|
.left_join(songs::table.on(albums::id.nullable().eq(songs::album_id)))
|
||||||
|
.left_join(song_artists::table.inner_join(artists::table).on(songs::id.eq(song_artists::song_id)))
|
||||||
|
.select((
|
||||||
|
albums::all_columns,
|
||||||
|
songs::all_columns.nullable(),
|
||||||
|
artists::all_columns.nullable()
|
||||||
|
))
|
||||||
|
.order(songs::track.asc())
|
||||||
|
.load(conn)?;
|
||||||
|
|
||||||
|
let song_list: Vec<(Album, Option<Song>, Option<Artist>, Option<(i32, i32)>, Option<(i32, i32)>)> =
|
||||||
|
song_list.into_iter().map( |(album, song, artist)| (album, song, artist, None, None) ).collect();
|
||||||
|
song_list
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut album_songs: HashMap<i32, SongData> = HashMap::with_capacity(song_list.len());
|
||||||
|
|
||||||
|
for (album, song, artist, like, dislike) in song_list {
|
||||||
|
if let Some(song) = song {
|
||||||
|
if let Some(stored_songdata) = album_songs.get_mut(&song.id.unwrap()) {
|
||||||
|
// If the song is already in the map, update the artists
|
||||||
|
if let Some(artist) = artist {
|
||||||
|
stored_songdata.artists.push(artist);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let like_dislike = match (like, dislike) {
|
||||||
|
(Some(_), Some(_)) => Some((true, true)),
|
||||||
|
(Some(_), None) => Some((true, false)),
|
||||||
|
(None, Some(_)) => Some((false, true)),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
|
||||||
|
let image_path = song.image_path.unwrap_or(
|
||||||
|
album.image_path.clone().unwrap_or("/assets/images/placeholders/MusicPlaceholder.svg".to_string()));
|
||||||
|
|
||||||
|
let songdata = SongData {
|
||||||
|
id: song.id.unwrap(),
|
||||||
|
title: song.title,
|
||||||
|
artists: artist.map(|artist| vec![artist]).unwrap_or_default(),
|
||||||
|
album: Some(album),
|
||||||
|
track: song.track,
|
||||||
|
duration: song.duration,
|
||||||
|
release_date: song.release_date,
|
||||||
|
song_path: song.storage_path,
|
||||||
|
image_path: image_path,
|
||||||
|
like_dislike: like_dislike,
|
||||||
|
};
|
||||||
|
|
||||||
|
album_songs.insert(song.id.unwrap(), songdata);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sort the songs by date
|
||||||
|
let mut songdata: Vec<SongData> = album_songs.into_values().collect();
|
||||||
|
songdata.sort_by(|a, b| a.track.cmp(&b.track));
|
||||||
|
Ok(songdata)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Model for a song
|
/// Model for a song
|
||||||
@ -253,7 +684,7 @@ pub struct Song {
|
|||||||
/// The duration of the song in seconds
|
/// The duration of the song in seconds
|
||||||
pub duration: i32,
|
pub duration: i32,
|
||||||
/// The song's release date
|
/// The song's release date
|
||||||
pub release_date: Option<Date>,
|
pub release_date: Option<NaiveDate>,
|
||||||
/// The path to the song's audio file
|
/// The path to the song's audio file
|
||||||
pub storage_path: String,
|
pub storage_path: String,
|
||||||
/// The path to the song's image file
|
/// The path to the song's image file
|
||||||
@ -289,4 +720,68 @@ impl Song {
|
|||||||
|
|
||||||
Ok(my_artists)
|
Ok(my_artists)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Get the album for this song from the database
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `conn` - A mutable reference to a database connection
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// * `Result<Option<Album>, Box<dyn Error>>` - A result indicating success with an album, or None if
|
||||||
|
/// the song does not have an album, or an error
|
||||||
|
///
|
||||||
|
#[cfg(feature = "ssr")]
|
||||||
|
pub fn get_album(self: &Self, conn: &mut PgPooledConn) -> Result<Option<Album>, Box<dyn Error>> {
|
||||||
|
use crate::schema::albums::dsl::*;
|
||||||
|
|
||||||
|
if let Some(album_id) = self.album_id {
|
||||||
|
let my_album = albums
|
||||||
|
.filter(id.eq(album_id))
|
||||||
|
.first::<Album>(conn)?;
|
||||||
|
|
||||||
|
Ok(Some(my_album))
|
||||||
|
} else {
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Model for a history entry
|
||||||
|
#[cfg_attr(feature = "ssr", derive(Queryable, Selectable, Insertable))]
|
||||||
|
#[cfg_attr(feature = "ssr", diesel(table_name = crate::schema::song_history))]
|
||||||
|
#[cfg_attr(feature = "ssr", diesel(check_for_backend(diesel::pg::Pg)))]
|
||||||
|
#[derive(Serialize, Deserialize)]
|
||||||
|
pub struct HistoryEntry {
|
||||||
|
/// A unique id for the history entry
|
||||||
|
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
|
||||||
|
pub id: Option<i32>,
|
||||||
|
/// The id of the user who listened to the song
|
||||||
|
pub user_id: i32,
|
||||||
|
/// The date the song was listened to
|
||||||
|
pub date: NaiveDateTime,
|
||||||
|
/// The id of the song that was listened to
|
||||||
|
pub song_id: i32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Model for a 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)]
|
||||||
|
pub struct Playlist {
|
||||||
|
/// A unique id for the playlist
|
||||||
|
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
|
||||||
|
pub id: Option<i32>,
|
||||||
|
/// The time the playlist was created
|
||||||
|
#[cfg_attr(feature = "ssr", diesel(deserialize_as = NaiveDateTime))]
|
||||||
|
pub created_at: Option<NaiveDateTime>,
|
||||||
|
/// The time the playlist was last updated
|
||||||
|
#[cfg_attr(feature = "ssr", diesel(deserialize_as = NaiveDateTime))]
|
||||||
|
pub updated_at: Option<NaiveDateTime>,
|
||||||
|
/// The id of the user who owns the playlist
|
||||||
|
pub owner_id: i32,
|
||||||
|
/// The name of the playlist
|
||||||
|
pub name: String,
|
||||||
}
|
}
|
||||||
|
@ -1,2 +1,4 @@
|
|||||||
pub mod login;
|
pub mod login;
|
||||||
pub mod signup;
|
pub mod signup;
|
||||||
|
pub mod profile;
|
||||||
|
pub mod albumpage;
|
||||||
|
87
src/pages/albumpage.rs
Normal file
87
src/pages/albumpage.rs
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
use leptos::leptos_dom::*;
|
||||||
|
use leptos::*;
|
||||||
|
use leptos_router::*;
|
||||||
|
use crate::components::song_list::*;
|
||||||
|
use crate::api::album::*;
|
||||||
|
use crate::components::album_info::*;
|
||||||
|
|
||||||
|
|
||||||
|
#[derive(Params, PartialEq)]
|
||||||
|
struct AlbumParams {
|
||||||
|
id: i32
|
||||||
|
}
|
||||||
|
|
||||||
|
#[component]
|
||||||
|
pub fn AlbumPage() -> impl IntoView {
|
||||||
|
let params = use_params::<AlbumParams>();
|
||||||
|
|
||||||
|
let id = move || {params.with(|params| {
|
||||||
|
params.as_ref()
|
||||||
|
.map(|params| params.id)
|
||||||
|
.map_err(|e| e.clone())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
|
||||||
|
let song_list = create_resource(
|
||||||
|
id,
|
||||||
|
|value| async move {
|
||||||
|
match value {
|
||||||
|
Ok(v) => {get_songs(v).await},
|
||||||
|
Err(e) => {Err(ServerFnError::Request(format!("Error getting song data: {}", e).into()))},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
let albumdata = create_resource(
|
||||||
|
id,
|
||||||
|
|value| async move {
|
||||||
|
match value {
|
||||||
|
Ok(v) => {get_album(v).await},
|
||||||
|
Err(e) => {Err(ServerFnError::Request(format!("Error getting song data: {}", e).into()))},
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="album-page-container">
|
||||||
|
<div class="album-header">
|
||||||
|
<Suspense
|
||||||
|
fallback=move || view! { <p class="loading">"Loading..."</p> }
|
||||||
|
>
|
||||||
|
{move || {
|
||||||
|
albumdata.with( |albumdata| {
|
||||||
|
match albumdata {
|
||||||
|
Some(Ok(s)) => {
|
||||||
|
view! { <AlbumInfo albumdata=(*s).clone() /> }
|
||||||
|
},
|
||||||
|
Some(Err(e)) => {
|
||||||
|
view! { <div class="error">{format!("Error loading album : {}",e)}</div> }.into_view()
|
||||||
|
},
|
||||||
|
None => {view! { }.into_view()}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Suspense
|
||||||
|
fallback=move || view! { <p class="loading">"Loading..."</p> }
|
||||||
|
>
|
||||||
|
{move || {
|
||||||
|
song_list.with( |song_list| {
|
||||||
|
match song_list {
|
||||||
|
Some(Ok(s)) => {
|
||||||
|
view! { <SongList songs=(*s).clone()/> }
|
||||||
|
},
|
||||||
|
Some(Err(e)) => {
|
||||||
|
view! { <div class="error">{format!("Error loading albums: : {}",e)}</div> }.into_view()
|
||||||
|
},
|
||||||
|
None => {view! { }.into_view()}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}}
|
||||||
|
</Suspense>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -1,8 +1,10 @@
|
|||||||
use crate::auth::login;
|
use crate::auth::login;
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
use leptos::leptos_dom::*;
|
use leptos::leptos_dom::*;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_icons::*;
|
use leptos_icons::*;
|
||||||
use crate::users::UserCredentials;
|
use crate::users::UserCredentials;
|
||||||
|
use crate::components::loading::Loading;
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Login() -> impl IntoView {
|
pub fn Login() -> impl IntoView {
|
||||||
@ -11,6 +13,9 @@ pub fn Login() -> impl IntoView {
|
|||||||
|
|
||||||
let (show_password, set_show_password) = create_signal(false);
|
let (show_password, set_show_password) = create_signal(false);
|
||||||
|
|
||||||
|
let loading = create_rw_signal(false);
|
||||||
|
let error_msg = create_rw_signal(None);
|
||||||
|
|
||||||
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");
|
||||||
@ -23,23 +28,41 @@ pub fn Login() -> impl IntoView {
|
|||||||
let password1 = password.get();
|
let password1 = password.get();
|
||||||
|
|
||||||
spawn_local(async move {
|
spawn_local(async move {
|
||||||
|
loading.set(true);
|
||||||
|
error_msg.set(None);
|
||||||
|
|
||||||
let user_credentials = UserCredentials {
|
let user_credentials = UserCredentials {
|
||||||
username_or_email: username_or_email1,
|
username_or_email: username_or_email1,
|
||||||
password: password1
|
password: password1
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let user = GlobalState::logged_in_user();
|
||||||
|
|
||||||
let login_result = login(user_credentials).await;
|
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);
|
||||||
} else if let Ok(true) = login_result {
|
error_msg.set(Some(err.to_string()));
|
||||||
|
|
||||||
|
// Since we're not sure what the state is, manually refetch the user
|
||||||
|
user.refetch();
|
||||||
|
} else if let Ok(Some(login_user)) = login_result {
|
||||||
|
// Manually set the user to the new user, avoiding a refetch
|
||||||
|
user.set(Some(login_user));
|
||||||
|
|
||||||
// Redirect to the login page
|
// Redirect to the login page
|
||||||
log!("Logged in Successfully!");
|
log!("Logged in Successfully!");
|
||||||
leptos_router::use_navigate()("/", Default::default());
|
leptos_router::use_navigate()("/", Default::default());
|
||||||
log!("Navigated to home page after login");
|
log!("Navigated to home page after login");
|
||||||
} else if let Ok(false) = login_result {
|
} else if let Ok(None) = login_result {
|
||||||
log!("Invalid username or password");
|
log!("Invalid username or password");
|
||||||
|
error_msg.set(Some("Invalid username or password".to_string()));
|
||||||
|
|
||||||
|
// User could be already logged in or not, so refetch the user
|
||||||
|
user.refetch();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
loading.set(false);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -84,7 +107,13 @@ pub fn Login() -> impl IntoView {
|
|||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
<a href="" class="forgot-pw">Forgot Password?</a>
|
<a href="" class="forgot-pw">Forgot Password?</a>
|
||||||
|
<div class="error-msg" >{ move || error_msg.get() }</div>
|
||||||
|
<Show
|
||||||
|
when=move || !loading.get()
|
||||||
|
fallback=move || view! { <Loading /> }
|
||||||
|
>
|
||||||
<input type="submit" value="Login" />
|
<input type="submit" value="Login" />
|
||||||
|
</Show>
|
||||||
<span class="go-to-signup">
|
<span class="go-to-signup">
|
||||||
New here? <a href="/signup">Create an Account</a>
|
New here? <a href="/signup">Create an Account</a>
|
||||||
</span>
|
</span>
|
||||||
|
316
src/pages/profile.rs
Normal file
316
src/pages/profile.rs
Normal file
@ -0,0 +1,316 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use leptos_router::use_params_map;
|
||||||
|
use leptos_icons::*;
|
||||||
|
use server_fn::error::NoCustomError;
|
||||||
|
|
||||||
|
use crate::components::dashboard_row::DashboardRow;
|
||||||
|
use crate::components::dashboard_tile::DashboardTile;
|
||||||
|
use crate::components::song_list::*;
|
||||||
|
use crate::components::loading::*;
|
||||||
|
use crate::components::error::*;
|
||||||
|
|
||||||
|
use crate::api::profile::*;
|
||||||
|
|
||||||
|
use crate::models::User;
|
||||||
|
use crate::users::get_user_by_id;
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
|
|
||||||
|
/// Duration in seconds backwards from now to aggregate history data for
|
||||||
|
const HISTORY_SECS: i64 = 60 * 60 * 24 * 30;
|
||||||
|
const HISTORY_MESSAGE: &str = "Last Month";
|
||||||
|
|
||||||
|
/// How many top songs to show
|
||||||
|
const TOP_SONGS_COUNT: i64 = 10;
|
||||||
|
/// How many recent songs to show
|
||||||
|
const RECENT_SONGS_COUNT: i64 = 5;
|
||||||
|
/// How many recent artists to show
|
||||||
|
const TOP_ARTISTS_COUNT: i64 = 10;
|
||||||
|
|
||||||
|
/// Profile page
|
||||||
|
/// Shows the current user's profile if no id is specified, or a user's profile if an id is specified in the path
|
||||||
|
#[component]
|
||||||
|
pub fn Profile() -> impl IntoView {
|
||||||
|
let params = use_params_map();
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="profile-container home-component">
|
||||||
|
{move || params.with(|params| {
|
||||||
|
match params.get("id").map(|id| id.parse::<i32>()) {
|
||||||
|
None => {
|
||||||
|
// No id specified, show the current user's profile
|
||||||
|
view! { <OwnProfile /> }.into_view()
|
||||||
|
},
|
||||||
|
Some(Ok(id)) => {
|
||||||
|
// Id specified, get the user and show their profile
|
||||||
|
view! { <UserIdProfile id /> }.into_view()
|
||||||
|
},
|
||||||
|
Some(Err(e)) => {
|
||||||
|
// Invalid id, return an error
|
||||||
|
view! {
|
||||||
|
<Error<String>
|
||||||
|
title="Invalid User ID"
|
||||||
|
error=e.to_string()
|
||||||
|
/>
|
||||||
|
}.into_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show the logged in user's profile
|
||||||
|
#[component]
|
||||||
|
fn OwnProfile() -> impl IntoView {
|
||||||
|
view! {
|
||||||
|
<Transition
|
||||||
|
fallback=move || view! { <LoadingPage /> }
|
||||||
|
>
|
||||||
|
{move || GlobalState::logged_in_user().get().map(|user| {
|
||||||
|
match user {
|
||||||
|
Some(user) => {
|
||||||
|
let user_id = user.id.unwrap();
|
||||||
|
view! {
|
||||||
|
<UserProfile user />
|
||||||
|
<TopSongs user_id={user_id} />
|
||||||
|
<RecentSongs user_id={user_id} />
|
||||||
|
<TopArtists user_id={user_id} />
|
||||||
|
}.into_view()
|
||||||
|
},
|
||||||
|
None => view! {
|
||||||
|
<Error<String>
|
||||||
|
title="Not Logged In"
|
||||||
|
message="You must be logged in to view your profile"
|
||||||
|
/>
|
||||||
|
}.into_view(),
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</Transition>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show a user's profile by ID
|
||||||
|
#[component]
|
||||||
|
fn UserIdProfile(#[prop(into)] id: MaybeSignal<i32>) -> impl IntoView {
|
||||||
|
let user_info = create_resource(move || id.get(), move |id| {
|
||||||
|
get_user_by_id(id)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Show the details if the user is found
|
||||||
|
let show_details = create_rw_signal(false);
|
||||||
|
|
||||||
|
view!{
|
||||||
|
<Transition
|
||||||
|
fallback=move || view! { <LoadingPage /> }
|
||||||
|
>
|
||||||
|
{move || user_info.get().map(|user| {
|
||||||
|
match user {
|
||||||
|
Ok(Some(user)) => {
|
||||||
|
show_details.set(true);
|
||||||
|
|
||||||
|
view! { <UserProfile user /> }.into_view()
|
||||||
|
},
|
||||||
|
Ok(None) => {
|
||||||
|
show_details.set(false);
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<Error<String>
|
||||||
|
title="User Not Found"
|
||||||
|
message=format!("User with ID {} not found", id.get())
|
||||||
|
/>
|
||||||
|
}.into_view()
|
||||||
|
},
|
||||||
|
Err(error) => {
|
||||||
|
show_details.set(false);
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<ServerError<NoCustomError>
|
||||||
|
title="Error Getting User"
|
||||||
|
error
|
||||||
|
/>
|
||||||
|
}.into_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})}
|
||||||
|
</Transition>
|
||||||
|
<div hidden={move || !show_details.get()}>
|
||||||
|
<TopSongs user_id={id} />
|
||||||
|
<RecentSongs user_id={id} />
|
||||||
|
<TopArtists user_id={id} />
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show a profile for a User object
|
||||||
|
#[component]
|
||||||
|
fn UserProfile(user: User) -> impl IntoView {
|
||||||
|
let user_id = user.id.unwrap();
|
||||||
|
let profile_image_path = format!("/assets/images/profile/{}.webp", user_id);
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="profile-header">
|
||||||
|
<object class="profile-image" data={profile_image_path.clone()} type="image/webp">
|
||||||
|
<Icon class="profile-image" icon=icondata::CgProfile width="75" height="75"/>
|
||||||
|
</object>
|
||||||
|
<h1>{user.username}</h1>
|
||||||
|
</div>
|
||||||
|
<div class="profile-details">
|
||||||
|
<p>
|
||||||
|
{user.email}
|
||||||
|
{
|
||||||
|
user.created_at.map(|created_at| {
|
||||||
|
format!(" • Joined {}", created_at.format("%B %Y"))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
{
|
||||||
|
if user.admin {
|
||||||
|
" • Admin"
|
||||||
|
} else {
|
||||||
|
""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show a list of top songs for a user
|
||||||
|
#[component]
|
||||||
|
fn TopSongs(#[prop(into)] user_id: MaybeSignal<i32>) -> impl IntoView {
|
||||||
|
let top_songs = create_resource(move || user_id.get(), |user_id| async move {
|
||||||
|
use chrono::{Local, Duration};
|
||||||
|
let now = Local::now();
|
||||||
|
let start = now - Duration::seconds(HISTORY_SECS);
|
||||||
|
let top_songs = top_songs(user_id, start.naive_utc(), now.naive_utc(), Some(TOP_SONGS_COUNT)).await;
|
||||||
|
|
||||||
|
top_songs.map(|top_songs| {
|
||||||
|
top_songs.into_iter().map(|(plays, song)| {
|
||||||
|
let plays = if plays == 1 {
|
||||||
|
format!("{} Play", plays)
|
||||||
|
} else {
|
||||||
|
format!("{} Plays", plays)
|
||||||
|
};
|
||||||
|
|
||||||
|
(song, plays)
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<h2>{format!("Top Songs {}", HISTORY_MESSAGE)}</h2>
|
||||||
|
<Transition
|
||||||
|
fallback=move || view! { <Loading /> }
|
||||||
|
>
|
||||||
|
<ErrorBoundary
|
||||||
|
fallback=|errors| view! {
|
||||||
|
{move || errors.get()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
|
||||||
|
.collect_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{move ||
|
||||||
|
top_songs.get().map(|top_songs| {
|
||||||
|
top_songs.map(|top_songs| {
|
||||||
|
view! {
|
||||||
|
<SongListExtra songs=top_songs />
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</ErrorBoundary>
|
||||||
|
</Transition>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show a list of recently played songs for a user
|
||||||
|
#[component]
|
||||||
|
fn RecentSongs(#[prop(into)] user_id: MaybeSignal<i32>) -> impl IntoView {
|
||||||
|
let recent_songs = create_resource(move || user_id.get(), |user_id| async move {
|
||||||
|
let recent_songs = recent_songs(user_id, Some(RECENT_SONGS_COUNT)).await;
|
||||||
|
|
||||||
|
recent_songs.map(|recent_songs| {
|
||||||
|
recent_songs.into_iter().map(|(_date, song)| {
|
||||||
|
song
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<h2>"Recently Played"</h2>
|
||||||
|
<Transition
|
||||||
|
fallback=move || view! { <Loading /> }
|
||||||
|
>
|
||||||
|
<ErrorBoundary
|
||||||
|
fallback=|errors| view! {
|
||||||
|
{move || errors.get()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
|
||||||
|
.collect_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{move ||
|
||||||
|
recent_songs.get().map(|recent_songs| {
|
||||||
|
recent_songs.map(|recent_songs| {
|
||||||
|
view! {
|
||||||
|
<SongList songs=recent_songs />
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</ErrorBoundary>
|
||||||
|
</Transition>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Show a list of top artists for a user
|
||||||
|
#[component]
|
||||||
|
fn TopArtists(#[prop(into)] user_id: MaybeSignal<i32>) -> impl IntoView {
|
||||||
|
let top_artists = create_resource(move || user_id.get(), |user_id| async move {
|
||||||
|
use chrono::{Local, Duration};
|
||||||
|
|
||||||
|
let now = Local::now();
|
||||||
|
let start = now - Duration::seconds(HISTORY_SECS);
|
||||||
|
let top_artists = top_artists(user_id, start.naive_utc(), now.naive_utc(), Some(TOP_ARTISTS_COUNT)).await;
|
||||||
|
|
||||||
|
top_artists.map(|top_artists| {
|
||||||
|
top_artists.into_iter().map(|(_plays, artist)| {
|
||||||
|
artist
|
||||||
|
}).collect::<Vec<_>>()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<Transition
|
||||||
|
fallback=move || view! {
|
||||||
|
<h2>{format!("Top Artists {}", HISTORY_MESSAGE)}</h2>
|
||||||
|
<Loading />
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<ErrorBoundary
|
||||||
|
fallback=|errors| view! {
|
||||||
|
<h2>{format!("Top Artists {}", HISTORY_MESSAGE)}</h2>
|
||||||
|
{move || errors.get()
|
||||||
|
.into_iter()
|
||||||
|
.map(|(_, e)| view! { <p>{e.to_string()}</p>})
|
||||||
|
.collect_view()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{move ||
|
||||||
|
top_artists.get().map(|top_artists| {
|
||||||
|
top_artists.map(|top_artists| {
|
||||||
|
let tiles = top_artists.into_iter().map(|artist| {
|
||||||
|
Box::new(artist) as Box<dyn DashboardTile>
|
||||||
|
}).collect::<Vec<_>>();
|
||||||
|
|
||||||
|
DashboardRow::new(format!("Top Artists {}", HISTORY_MESSAGE), tiles)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
</ErrorBoundary>
|
||||||
|
</Transition>
|
||||||
|
}
|
||||||
|
}
|
@ -1,8 +1,10 @@
|
|||||||
use crate::auth::signup;
|
use crate::auth::signup;
|
||||||
use crate::models::User;
|
use crate::models::User;
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
use leptos::leptos_dom::*;
|
use leptos::leptos_dom::*;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_icons::*;
|
use leptos_icons::*;
|
||||||
|
use crate::components::loading::Loading;
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Signup() -> impl IntoView {
|
pub fn Signup() -> impl IntoView {
|
||||||
@ -12,6 +14,9 @@ pub fn Signup() -> impl IntoView {
|
|||||||
|
|
||||||
let (show_password, set_show_password) = create_signal(false);
|
let (show_password, set_show_password) = create_signal(false);
|
||||||
|
|
||||||
|
let loading = create_rw_signal(false);
|
||||||
|
let error_msg = create_rw_signal(None);
|
||||||
|
|
||||||
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");
|
||||||
@ -19,25 +24,41 @@ pub fn Signup() -> impl IntoView {
|
|||||||
|
|
||||||
let on_submit = move |ev: leptos::ev::SubmitEvent| {
|
let on_submit = move |ev: leptos::ev::SubmitEvent| {
|
||||||
ev.prevent_default();
|
ev.prevent_default();
|
||||||
let new_user = User {
|
let mut new_user = User {
|
||||||
id: None,
|
id: None,
|
||||||
username: username.get(),
|
username: username.get(),
|
||||||
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);
|
||||||
|
|
||||||
|
loading.set(true);
|
||||||
|
error_msg.set(None);
|
||||||
|
|
||||||
|
let user = GlobalState::logged_in_user();
|
||||||
|
|
||||||
spawn_local(async move {
|
spawn_local(async move {
|
||||||
if let Err(err) = signup(new_user).await {
|
if let Err(err) = signup(new_user.clone()).await {
|
||||||
// Handle the error here, e.g., log it or display to the user
|
// Handle the error here, e.g., log it or display to the user
|
||||||
log!("Error signing up: {:?}", err);
|
log!("Error signing up: {:?}", err);
|
||||||
|
error_msg.set(Some(err.to_string()));
|
||||||
|
|
||||||
|
// Since we're not sure what the state is, manually refetch the user
|
||||||
|
user.refetch();
|
||||||
} else {
|
} else {
|
||||||
|
// Manually set the user to the new user, avoiding a refetch
|
||||||
|
new_user.password = None;
|
||||||
|
user.set(Some(new_user));
|
||||||
|
|
||||||
// Redirect to the login page
|
// Redirect to the login page
|
||||||
log!("Signed up successfully!");
|
log!("Signed up successfully!");
|
||||||
leptos_router::use_navigate()("/", Default::default());
|
leptos_router::use_navigate()("/", Default::default());
|
||||||
log!("Navigated to home page after signup")
|
log!("Navigated to home page after signup")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
loading.set(false);
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -88,7 +109,13 @@ pub fn Signup() -> impl IntoView {
|
|||||||
</button>
|
</button>
|
||||||
</Show>
|
</Show>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="error-msg">{ move || error_msg.get() }</div>
|
||||||
|
<Show
|
||||||
|
when=move || !loading.get()
|
||||||
|
fallback=move || view!{ <Loading /> }
|
||||||
|
>
|
||||||
<input type="submit" value="Sign Up" />
|
<input type="submit" value="Sign Up" />
|
||||||
|
</Show>
|
||||||
<span class="go-to-login">
|
<span class="go-to-login">
|
||||||
Already Have an Account? <a href="/login" class="link" >Go to Login</a>
|
Already Have an Account? <a href="/login" class="link" >Go to Login</a>
|
||||||
</span>
|
</span>
|
||||||
|
285
src/playbar.rs
285
src/playbar.rs
@ -1,9 +1,14 @@
|
|||||||
use crate::playstatus::PlayStatus;
|
use crate::models::Artist;
|
||||||
|
use crate::songdata::SongData;
|
||||||
|
use crate::api::songs;
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
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_meta::Title;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
use leptos_icons::*;
|
use leptos_icons::*;
|
||||||
|
use leptos_use::{utils::Pausable, use_interval_fn};
|
||||||
|
|
||||||
/// Width and height of the forward/backward skip buttons
|
/// Width and height of the forward/backward skip buttons
|
||||||
const SKIP_BTN_SIZE: &str = "3.5em";
|
const SKIP_BTN_SIZE: &str = "3.5em";
|
||||||
@ -19,6 +24,9 @@ const MIN_SKIP_BACK_TIME: f64 = 5.0;
|
|||||||
/// How many seconds to skip forward/backward when the user presses the arrow keys
|
/// How many seconds to skip forward/backward when the user presses the arrow keys
|
||||||
const ARROW_KEY_SKIP_TIME: f64 = 5.0;
|
const ARROW_KEY_SKIP_TIME: f64 = 5.0;
|
||||||
|
|
||||||
|
/// Threshold in seconds for considering when the user has listened to a song, for adding it to the history
|
||||||
|
const HISTORY_LISTEN_THRESHOLD: u64 = MIN_SKIP_BACK_TIME as u64;
|
||||||
|
|
||||||
// TODO Handle errors better, when getting audio HTML element and when playing/pausing audio
|
// TODO Handle errors better, when getting audio HTML element and when playing/pausing audio
|
||||||
|
|
||||||
/// Get the current time and duration of the current song, if available
|
/// Get the current time and duration of the current song, if available
|
||||||
@ -32,8 +40,8 @@ const ARROW_KEY_SKIP_TIME: f64 = 5.0;
|
|||||||
/// * `None` if the audio element is not available
|
/// * `None` if the audio element is not available
|
||||||
/// * `Some((current_time, duration))` if the audio element is available
|
/// * `Some((current_time, duration))` if the audio element is available
|
||||||
///
|
///
|
||||||
pub fn get_song_time_duration(status: impl SignalWithUntracked<Value = PlayStatus>) -> Option<(f64, f64)> {
|
pub fn get_song_time_duration() -> Option<(f64, f64)> {
|
||||||
status.with_untracked(|status| {
|
GlobalState::play_status().with_untracked(|status| {
|
||||||
if let Some(audio) = status.get_audio() {
|
if let Some(audio) = status.get_audio() {
|
||||||
Some((audio.current_time(), audio.duration()))
|
Some((audio.current_time(), audio.duration()))
|
||||||
} else {
|
} else {
|
||||||
@ -53,13 +61,13 @@ pub fn get_song_time_duration(status: impl SignalWithUntracked<Value = PlayStatu
|
|||||||
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
|
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
|
||||||
/// * `time` - The time to skip to, in seconds
|
/// * `time` - The time to skip to, in seconds
|
||||||
///
|
///
|
||||||
pub fn skip_to(status: impl SignalUpdate<Value = PlayStatus>, time: f64) {
|
pub fn skip_to(time: f64) {
|
||||||
if time.is_infinite() || time.is_nan() {
|
if time.is_infinite() || time.is_nan() {
|
||||||
error!("Unable to skip to non-finite time: {}", time);
|
error!("Unable to skip to non-finite time: {}", time);
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
status.update(|status| {
|
GlobalState::play_status().update(|status| {
|
||||||
if let Some(audio) = status.get_audio() {
|
if let Some(audio) = status.get_audio() {
|
||||||
audio.set_current_time(time);
|
audio.set_current_time(time);
|
||||||
log!("Player skipped to time: {}", time);
|
log!("Player skipped to time: {}", time);
|
||||||
@ -77,8 +85,8 @@ pub fn skip_to(status: impl SignalUpdate<Value = PlayStatus>, time: f64) {
|
|||||||
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
|
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
|
||||||
/// * `play` - `true` to play the song, `false` to pause it
|
/// * `play` - `true` to play the song, `false` to pause it
|
||||||
///
|
///
|
||||||
pub fn set_playing(status: impl SignalUpdate<Value = PlayStatus>, play: bool) {
|
pub fn set_playing(play: bool) {
|
||||||
status.update(|status| {
|
GlobalState::play_status().update(|status| {
|
||||||
if let Some(audio) = status.get_audio() {
|
if let Some(audio) = status.get_audio() {
|
||||||
if play {
|
if play {
|
||||||
if let Err(e) = audio.play() {
|
if let Err(e) = audio.play() {
|
||||||
@ -101,8 +109,8 @@ pub fn set_playing(status: impl SignalUpdate<Value = PlayStatus>, play: bool) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
fn toggle_queue(status: impl SignalUpdate<Value = PlayStatus>) {
|
fn toggle_queue() {
|
||||||
status.update(|status| {
|
GlobalState::play_status().update(|status| {
|
||||||
status.queue_open = !status.queue_open;
|
status.queue_open = !status.queue_open;
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -118,8 +126,8 @@ fn toggle_queue(status: impl SignalUpdate<Value = PlayStatus>) {
|
|||||||
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
|
/// * `status` - The `PlayStatus` to get the audio element from, as a signal
|
||||||
/// * `src` - The source to set the audio player to
|
/// * `src` - The source to set the audio player to
|
||||||
///
|
///
|
||||||
fn set_play_src(status: impl SignalUpdate<Value = PlayStatus>, src: String) {
|
fn set_play_src(src: String) {
|
||||||
status.update(|status| {
|
GlobalState::play_status().update(|status| {
|
||||||
if let Some(audio) = status.get_audio() {
|
if let Some(audio) = status.get_audio() {
|
||||||
audio.set_src(&src);
|
audio.set_src(&src);
|
||||||
log!("Player set src to: {}", src);
|
log!("Player set src to: {}", src);
|
||||||
@ -131,11 +139,13 @@ fn set_play_src(status: impl SignalUpdate<Value = PlayStatus>, src: String) {
|
|||||||
|
|
||||||
/// The play, pause, and skip buttons
|
/// The play, pause, and skip buttons
|
||||||
#[component]
|
#[component]
|
||||||
fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
|
fn PlayControls() -> impl IntoView {
|
||||||
|
let status = GlobalState::play_status();
|
||||||
|
|
||||||
// On click handlers for the skip and play/pause buttons
|
// On click handlers for the skip and play/pause buttons
|
||||||
|
|
||||||
let skip_back = move |_| {
|
let skip_back = move |_| {
|
||||||
if let Some(duration) = get_song_time_duration(status) {
|
if let Some(duration) = get_song_time_duration() {
|
||||||
// Skip to previous song if the current song is near the start
|
// Skip to previous song if the current song is near the start
|
||||||
// Also skip to the previous song if we're at the end of the current song
|
// Also skip to the previous song if we're at the end of the current song
|
||||||
// This is because after running out of songs in the queue, the current song will be at the end
|
// This is because after running out of songs in the queue, the current song will be at the end
|
||||||
@ -152,8 +162,8 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
// Push the popped song to the front of the queue, and play it
|
// Push the popped song to the front of the queue, and play it
|
||||||
let next_src = last_played_song.song_path.clone();
|
let next_src = last_played_song.song_path.clone();
|
||||||
status.update(|status| status.queue.push_front(last_played_song));
|
status.update(|status| status.queue.push_front(last_played_song));
|
||||||
set_play_src(status, next_src);
|
set_play_src(next_src);
|
||||||
set_playing(status, true);
|
set_playing(true);
|
||||||
} else {
|
} else {
|
||||||
warn!("Unable to skip back: No previous song");
|
warn!("Unable to skip back: No previous song");
|
||||||
}
|
}
|
||||||
@ -162,14 +172,14 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
|
|
||||||
// Default to skipping to start of current song, and playing
|
// Default to skipping to start of current song, and playing
|
||||||
log!("Skipping to start of current song");
|
log!("Skipping to start of current song");
|
||||||
skip_to(status, 0.0);
|
skip_to(0.0);
|
||||||
set_playing(status, true);
|
set_playing(true);
|
||||||
};
|
};
|
||||||
|
|
||||||
let skip_forward = move |_| {
|
let skip_forward = move |_| {
|
||||||
if let Some(duration) = get_song_time_duration(status) {
|
if let Some(duration) = get_song_time_duration() {
|
||||||
skip_to(status, duration.1);
|
skip_to(duration.1);
|
||||||
set_playing(status, true);
|
set_playing(true);
|
||||||
} else {
|
} else {
|
||||||
error!("Unable to skip forward: Unable to get current duration");
|
error!("Unable to skip forward: Unable to get current duration");
|
||||||
}
|
}
|
||||||
@ -177,7 +187,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
|
|
||||||
let toggle_play = move |_| {
|
let toggle_play = move |_| {
|
||||||
let playing = status.with_untracked(|status| { status.playing });
|
let playing = status.with_untracked(|status| { status.playing });
|
||||||
set_playing(status, !playing);
|
set_playing(!playing);
|
||||||
};
|
};
|
||||||
|
|
||||||
// We use this to prevent the buttons from being focused when clicked
|
// We use this to prevent the buttons from being focused when clicked
|
||||||
@ -240,47 +250,163 @@ fn PlayDuration(elapsed_secs: MaybeSignal<i64>, total_secs: MaybeSignal<i64>) ->
|
|||||||
|
|
||||||
/// The name, artist, and album of the current song
|
/// The name, artist, and album of the current song
|
||||||
#[component]
|
#[component]
|
||||||
fn MediaInfo(status: RwSignal<PlayStatus>) -> impl IntoView {
|
fn MediaInfo() -> impl IntoView {
|
||||||
|
let status = GlobalState::play_status();
|
||||||
|
|
||||||
let name = Signal::derive(move || {
|
let name = Signal::derive(move || {
|
||||||
status.with(|status| {
|
status.with(|status| {
|
||||||
status.queue.front().map_or("No media playing".into(), |song| song.name.clone())
|
status.queue.front().map_or("No media playing".into(), |song| song.title.clone())
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let artist = Signal::derive(move || {
|
let artist = Signal::derive(move || {
|
||||||
status.with(|status| {
|
status.with(|status| {
|
||||||
status.queue.front().map_or("".into(), |song| song.artist.clone())
|
status.queue.front().map_or("".into(), |song| format!("{}", Artist::display_list(&song.artists)))
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let album = Signal::derive(move || {
|
let album = Signal::derive(move || {
|
||||||
status.with(|status| {
|
status.with(|status| {
|
||||||
status.queue.front().map_or("".into(), |song| song.album.clone())
|
status.queue.front().map_or("".into(), |song|
|
||||||
|
song.album.as_ref().map_or("".into(), |album| album.title.clone()))
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let image = Signal::derive(move || {
|
let image = Signal::derive(move || {
|
||||||
status.with(|status| {
|
status.with(|status| {
|
||||||
// TODO Use some default / unknown image?
|
status.queue.front().map_or("/images/placeholders/MusicPlaceholder.svg".into(),
|
||||||
status.queue.front().map_or("".into(), |song| song.image_path.clone())
|
|song| song.image_path.clone())
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
view! {
|
view! {
|
||||||
<div class="media-info">
|
|
||||||
<img class="media-info-img" align="left" src={image}/>
|
<img class="media-info-img" align="left" src={image}/>
|
||||||
<div class="media-info-text">
|
<div class="media-info-text">
|
||||||
{name}
|
{name}
|
||||||
<br/>
|
<br/>
|
||||||
{artist} - {album}
|
{artist} - {album}
|
||||||
</div>
|
</div>
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The like and dislike buttons
|
||||||
|
#[component]
|
||||||
|
fn LikeDislike() -> impl IntoView {
|
||||||
|
let status = GlobalState::play_status();
|
||||||
|
|
||||||
|
let like_icon = Signal::derive(move || {
|
||||||
|
status.with(|status| {
|
||||||
|
match status.queue.front() {
|
||||||
|
Some(SongData { like_dislike: Some((true, _)), .. }) => icondata::TbThumbUpFilled,
|
||||||
|
_ => icondata::TbThumbUp,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let dislike_icon = Signal::derive(move || {
|
||||||
|
status.with(|status| {
|
||||||
|
match status.queue.front() {
|
||||||
|
Some(SongData { like_dislike: Some((_, true)), .. }) => icondata::TbThumbDownFilled,
|
||||||
|
_ => icondata::TbThumbDown,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
let toggle_like = move |_| {
|
||||||
|
status.update(|status| {
|
||||||
|
match status.queue.front_mut() {
|
||||||
|
Some(SongData { id, like_dislike: Some((liked, disliked)), .. }) => {
|
||||||
|
*liked = !*liked;
|
||||||
|
|
||||||
|
if *liked {
|
||||||
|
*disliked = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = *id;
|
||||||
|
let liked = *liked;
|
||||||
|
spawn_local(async move {
|
||||||
|
if let Err(e) = songs::set_like_song(id, liked).await {
|
||||||
|
error!("Error liking song: {:?}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
Some(SongData { id, like_dislike, .. }) => {
|
||||||
|
// This arm should only be reached if like_dislike is None
|
||||||
|
// In this case, the buttons will show up not filled, indicating that the song is not
|
||||||
|
// liked or disliked. Therefore, clicking the like button should like the song.
|
||||||
|
|
||||||
|
*like_dislike = Some((true, false));
|
||||||
|
|
||||||
|
let id = *id;
|
||||||
|
spawn_local(async move {
|
||||||
|
if let Err(e) = songs::set_like_song(id, true).await {
|
||||||
|
error!("Error liking song: {:?}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
log!("Unable to like song: No song in queue");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
let toggle_dislike = move |_| {
|
||||||
|
status.update(|status| {
|
||||||
|
match status.queue.front_mut() {
|
||||||
|
Some(SongData { id, like_dislike: Some((liked, disliked)), .. }) => {
|
||||||
|
*disliked = !*disliked;
|
||||||
|
|
||||||
|
if *disliked {
|
||||||
|
*liked = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
let id = *id;
|
||||||
|
let disliked = *disliked;
|
||||||
|
spawn_local(async move {
|
||||||
|
if let Err(e) = songs::set_dislike_song(id, disliked).await {
|
||||||
|
error!("Error disliking song: {:?}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
Some(SongData { id, like_dislike, .. }) => {
|
||||||
|
// This arm should only be reached if like_dislike is None
|
||||||
|
// In this case, the buttons will show up not filled, indicating that the song is not
|
||||||
|
// liked or disliked. Therefore, clicking the dislike button should dislike the song.
|
||||||
|
|
||||||
|
*like_dislike = Some((false, true));
|
||||||
|
|
||||||
|
let id = *id;
|
||||||
|
spawn_local(async move {
|
||||||
|
if let Err(e) = songs::set_dislike_song(id, true).await {
|
||||||
|
error!("Error disliking song: {:?}", e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
},
|
||||||
|
_ => {
|
||||||
|
log!("Unable to dislike song: No song in queue");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
view! {
|
||||||
|
<div class="like-dislike">
|
||||||
|
<button on:click=toggle_dislike>
|
||||||
|
<Icon class="controlbtn hmirror" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=dislike_icon />
|
||||||
|
</button>
|
||||||
|
<button on:click=toggle_like>
|
||||||
|
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=like_icon />
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The play progress bar, and click handler for skipping to a certain time in the song
|
/// The play progress bar, and click handler for skipping to a certain time in the song
|
||||||
#[component]
|
#[component]
|
||||||
fn ProgressBar(percentage: MaybeSignal<f64>, status: RwSignal<PlayStatus>) -> impl IntoView {
|
fn ProgressBar(percentage: MaybeSignal<f64>) -> impl IntoView {
|
||||||
// Keep a reference to the progress bar div so we can get its width and calculate the time to skip to
|
// Keep a reference to the progress bar div so we can get its width and calculate the time to skip to
|
||||||
let progress_bar_ref = create_node_ref::<Div>();
|
let progress_bar_ref = create_node_ref::<Div>();
|
||||||
|
|
||||||
@ -292,10 +418,10 @@ fn ProgressBar(percentage: MaybeSignal<f64>, status: RwSignal<PlayStatus>) -> im
|
|||||||
let width = progress_bar.offset_width() as f64;
|
let width = progress_bar.offset_width() as f64;
|
||||||
let percentage = x_click_pos / width * 100.0;
|
let percentage = x_click_pos / width * 100.0;
|
||||||
|
|
||||||
if let Some(duration) = get_song_time_duration(status) {
|
if let Some(duration) = get_song_time_duration() {
|
||||||
let time = duration.1 * percentage / 100.0;
|
let time = duration.1 * percentage / 100.0;
|
||||||
skip_to(status, time);
|
skip_to(time);
|
||||||
set_playing(status, true);
|
set_playing(true);
|
||||||
} else {
|
} else {
|
||||||
error!("Unable to skip to time: Unable to get current duration");
|
error!("Unable to skip to time: Unable to get current duration");
|
||||||
}
|
}
|
||||||
@ -318,11 +444,11 @@ fn ProgressBar(percentage: MaybeSignal<f64>, status: RwSignal<PlayStatus>) -> im
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
|
fn QueueToggle() -> impl IntoView {
|
||||||
|
|
||||||
let update_queue = move |_| {
|
let update_queue = move |_| {
|
||||||
toggle_queue(status);
|
toggle_queue();
|
||||||
log!("queue button pressed, queue status: {:?}", status.with_untracked(|status| status.queue_open));
|
log!("queue button pressed, queue status: {:?}",
|
||||||
|
GlobalState::play_status().with_untracked(|status| status.queue_open));
|
||||||
};
|
};
|
||||||
|
|
||||||
// We use this to prevent the buttons from being focused when clicked
|
// We use this to prevent the buttons from being focused when clicked
|
||||||
@ -341,20 +467,37 @@ fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Renders the title of the page based on the currently playing song
|
||||||
|
#[component]
|
||||||
|
pub fn CustomTitle() -> impl IntoView {
|
||||||
|
let title = create_memo(move |_| {
|
||||||
|
GlobalState::play_status().with(|play_status| {
|
||||||
|
play_status.queue.front().map_or("LibreTunes".to_string(), |song_data| {
|
||||||
|
format!("{} - {} | {}",song_data.title.clone(),Artist::display_list(&song_data.artists), "LibreTunes")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
});
|
||||||
|
view! {
|
||||||
|
<Title text=title />
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The main play bar component, containing the progress bar, media info, play controls, and play duration
|
/// The main play bar component, containing the progress bar, media info, play controls, and play duration
|
||||||
#[component]
|
#[component]
|
||||||
pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
pub fn PlayBar() -> impl IntoView {
|
||||||
|
let status = GlobalState::play_status();
|
||||||
|
|
||||||
// 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" {
|
||||||
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);
|
||||||
|
|
||||||
if let Some(duration) = get_song_time_duration(status) {
|
if let Some(duration) = get_song_time_duration() {
|
||||||
let mut time = duration.0 + ARROW_KEY_SKIP_TIME;
|
let mut time = duration.0 + ARROW_KEY_SKIP_TIME;
|
||||||
time = time.clamp(0.0, duration.1);
|
time = time.clamp(0.0, duration.1);
|
||||||
skip_to(status, time);
|
skip_to(time);
|
||||||
set_playing(status, true);
|
set_playing(true);
|
||||||
} else {
|
} else {
|
||||||
error!("Unable to skip forward: Unable to get current duration");
|
error!("Unable to skip forward: Unable to get current duration");
|
||||||
}
|
}
|
||||||
@ -363,11 +506,11 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
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);
|
||||||
|
|
||||||
if let Some(duration) = get_song_time_duration(status) {
|
if let Some(duration) = get_song_time_duration() {
|
||||||
let mut time = duration.0 - ARROW_KEY_SKIP_TIME;
|
let mut time = duration.0 - ARROW_KEY_SKIP_TIME;
|
||||||
time = time.clamp(0.0, duration.1);
|
time = time.clamp(0.0, duration.1);
|
||||||
skip_to(status, time);
|
skip_to(time);
|
||||||
set_playing(status, true);
|
set_playing(true);
|
||||||
} else {
|
} else {
|
||||||
error!("Unable to skip backward: Unable to get current duration");
|
error!("Unable to skip backward: Unable to get current duration");
|
||||||
}
|
}
|
||||||
@ -381,7 +524,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
log!("Space bar pressed, toggling play/pause");
|
log!("Space bar pressed, toggling play/pause");
|
||||||
|
|
||||||
let playing = status.with_untracked(|status| status.playing);
|
let playing = status.with_untracked(|status| status.playing);
|
||||||
set_playing(status, !playing);
|
set_playing(!playing);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -400,7 +543,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
status.with_untracked(|status| {
|
status.with_untracked(|status| {
|
||||||
// Start playing the first song in the queue, if available
|
// Start playing the first song in the queue, if available
|
||||||
if let Some(song) = status.queue.front() {
|
if let Some(song) = status.queue.front() {
|
||||||
log!("Starting playing with song: {}", song.name);
|
log!("Starting playing with song: {}", song.title);
|
||||||
|
|
||||||
// Don't use the set_play_src / set_playing helper function
|
// Don't use the set_play_src / set_playing helper function
|
||||||
// here because we already have access to the audio element
|
// here because we already have access to the audio element
|
||||||
@ -417,6 +560,39 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
let current_song_id = create_memo(move |_| {
|
||||||
|
status.with(|status| {
|
||||||
|
status.queue.front().map(|song| song.id)
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
// Track the last song that was added to the history to prevent duplicates
|
||||||
|
let last_history_song_id = create_rw_signal(None);
|
||||||
|
|
||||||
|
let Pausable {
|
||||||
|
is_active: hist_timeout_pending,
|
||||||
|
resume: resume_hist_timeout,
|
||||||
|
pause: pause_hist_timeout,
|
||||||
|
..
|
||||||
|
} = use_interval_fn(move || {
|
||||||
|
if last_history_song_id.get_untracked() == current_song_id.get_untracked() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(current_song_id) = current_song_id.get_untracked() {
|
||||||
|
last_history_song_id.set(Some(current_song_id));
|
||||||
|
|
||||||
|
spawn_local(async move {
|
||||||
|
if let Err(e) = crate::api::history::add_history(current_song_id).await {
|
||||||
|
error!("Error adding song {} to history: {}", current_song_id, e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, HISTORY_LISTEN_THRESHOLD * 1000);
|
||||||
|
|
||||||
|
// Initially pause the timeout, since the audio starts off paused
|
||||||
|
pause_hist_timeout();
|
||||||
|
|
||||||
let on_play = move |_| {
|
let on_play = move |_| {
|
||||||
log!("Audio playing");
|
log!("Audio playing");
|
||||||
status.update(|status| status.playing = true);
|
status.update(|status| status.playing = true);
|
||||||
@ -425,6 +601,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
let on_pause = move |_| {
|
let on_pause = move |_| {
|
||||||
log!("Audio paused");
|
log!("Audio paused");
|
||||||
status.update(|status| status.playing = false);
|
status.update(|status| status.playing = false);
|
||||||
|
pause_hist_timeout();
|
||||||
};
|
};
|
||||||
|
|
||||||
let on_time_update = move |_| {
|
let on_time_update = move |_| {
|
||||||
@ -442,6 +619,11 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
error!("Unable to update time: Audio element not available");
|
error!("Unable to update time: Audio element not available");
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// If time is updated, audio is playing, so make sure the history timeout is running
|
||||||
|
if !hist_timeout_pending.get_untracked() {
|
||||||
|
resume_hist_timeout();
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let on_end = move |_| {
|
let on_end = move |_| {
|
||||||
@ -453,7 +635,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
let prev_song = status.queue.pop_front();
|
let prev_song = status.queue.pop_front();
|
||||||
|
|
||||||
if let Some(prev_song) = prev_song {
|
if let Some(prev_song) = prev_song {
|
||||||
log!("Adding song to history: {}", prev_song.name);
|
log!("Adding song to history: {}", prev_song.title);
|
||||||
status.history.push_back(prev_song);
|
status.history.push_back(prev_song);
|
||||||
} else {
|
} else {
|
||||||
log!("Queue empty, no previous song to add to history");
|
log!("Queue empty, no previous song to add to history");
|
||||||
@ -485,11 +667,14 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
<audio _ref=audio_ref on:play=on_play on:pause=on_pause
|
<audio _ref=audio_ref on:play=on_play on:pause=on_pause
|
||||||
on:timeupdate=on_time_update on:ended=on_end type="audio/mpeg" />
|
on:timeupdate=on_time_update on:ended=on_end type="audio/mpeg" />
|
||||||
<div class="playbar">
|
<div class="playbar">
|
||||||
<ProgressBar percentage=percentage.into() status=status />
|
<ProgressBar percentage=percentage.into() />
|
||||||
<MediaInfo status=status />
|
<div class="playbar-left-group">
|
||||||
<PlayControls status=status />
|
<MediaInfo />
|
||||||
|
<LikeDislike />
|
||||||
|
</div>
|
||||||
|
<PlayControls />
|
||||||
<PlayDuration elapsed_secs=elapsed_secs.into() total_secs=total_secs.into() />
|
<PlayDuration elapsed_secs=elapsed_secs.into() total_secs=total_secs.into() />
|
||||||
<QueueToggle status=status />
|
<QueueToggle />
|
||||||
</div>
|
</div>
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
14
src/queue.rs
14
src/queue.rs
@ -1,5 +1,6 @@
|
|||||||
use crate::playstatus::PlayStatus;
|
use crate::models::Artist;
|
||||||
use crate::song::Song;
|
use crate::song::Song;
|
||||||
|
use crate::util::state::GlobalState;
|
||||||
use leptos::ev::MouseEvent;
|
use leptos::ev::MouseEvent;
|
||||||
use leptos::leptos_dom::*;
|
use leptos::leptos_dom::*;
|
||||||
use leptos::*;
|
use leptos::*;
|
||||||
@ -8,22 +9,23 @@ use leptos::ev::DragEvent;
|
|||||||
|
|
||||||
const RM_BTN_SIZE: &str = "2.5rem";
|
const RM_BTN_SIZE: &str = "2.5rem";
|
||||||
|
|
||||||
fn remove_song_fn(index: usize, status: RwSignal<PlayStatus>) {
|
fn remove_song_fn(index: usize) {
|
||||||
if index == 0 {
|
if index == 0 {
|
||||||
log!("Error: Trying to remove currently playing song (index 0) from queue");
|
log!("Error: Trying to remove currently playing song (index 0) from queue");
|
||||||
} else {
|
} else {
|
||||||
log!("Remove Song from Queue: Song is not currently playing, deleting song from queue and not adding to history");
|
log!("Remove Song from Queue: Song is not currently playing, deleting song from queue and not adding to history");
|
||||||
status.update(|status| {
|
GlobalState::play_status().update(|status| {
|
||||||
status.queue.remove(index);
|
status.queue.remove(index);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[component]
|
#[component]
|
||||||
pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
|
pub fn Queue() -> impl IntoView {
|
||||||
|
let status = GlobalState::play_status();
|
||||||
|
|
||||||
let remove_song = move |index: usize| {
|
let remove_song = move |index: usize| {
|
||||||
remove_song_fn(index, status);
|
remove_song_fn(index);
|
||||||
log!("Removed song {}", index + 1);
|
log!("Removed song {}", index + 1);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -98,7 +100,7 @@ pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
|
|||||||
on:dragenter=move |e: DragEvent| on_drag_enter(e, index)
|
on:dragenter=move |e: DragEvent| on_drag_enter(e, index)
|
||||||
on:dragover=on_drag_over
|
on:dragover=on_drag_over
|
||||||
>
|
>
|
||||||
<Song song_image_path=song.image_path.clone() song_title=song.name.clone() song_artist=song.artist.clone() />
|
<Song song_image_path=song.image_path.clone() song_title=song.title.clone() song_artist=Artist::display_list(&song.artists) />
|
||||||
<Show
|
<Show
|
||||||
when=move || index != 0
|
when=move || index != 0
|
||||||
fallback=|| view!{
|
fallback=|| view!{
|
||||||
|
@ -12,6 +12,7 @@ diesel::table! {
|
|||||||
id -> Int4,
|
id -> Int4,
|
||||||
title -> Varchar,
|
title -> Varchar,
|
||||||
release_date -> Nullable<Date>,
|
release_date -> Nullable<Date>,
|
||||||
|
image_path -> Nullable<Varchar>,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -22,6 +23,39 @@ diesel::table! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
friend_requests (from_id, to_id) {
|
||||||
|
created_at -> Timestamp,
|
||||||
|
from_id -> Int4,
|
||||||
|
to_id -> Int4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
friendships (friend_1_id, friend_2_id) {
|
||||||
|
created_at -> Timestamp,
|
||||||
|
friend_1_id -> Int4,
|
||||||
|
friend_2_id -> Int4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
playlist_songs (playlist_id, song_id) {
|
||||||
|
playlist_id -> Int4,
|
||||||
|
song_id -> Int4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
playlists (id) {
|
||||||
|
id -> Int4,
|
||||||
|
created_at -> Timestamp,
|
||||||
|
updated_at -> Timestamp,
|
||||||
|
owner_id -> Int4,
|
||||||
|
name -> Text,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
diesel::table! {
|
diesel::table! {
|
||||||
song_artists (song_id, artist_id) {
|
song_artists (song_id, artist_id) {
|
||||||
song_id -> Int4,
|
song_id -> Int4,
|
||||||
@ -29,6 +63,29 @@ diesel::table! {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
song_dislikes (song_id, user_id) {
|
||||||
|
song_id -> Int4,
|
||||||
|
user_id -> Int4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
song_history (id) {
|
||||||
|
id -> Int4,
|
||||||
|
user_id -> Int4,
|
||||||
|
date -> Timestamp,
|
||||||
|
song_id -> Int4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
diesel::table! {
|
||||||
|
song_likes (song_id, user_id) {
|
||||||
|
song_id -> Int4,
|
||||||
|
user_id -> Int4,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
diesel::table! {
|
diesel::table! {
|
||||||
songs (id) {
|
songs (id) {
|
||||||
id -> Int4,
|
id -> Int4,
|
||||||
@ -49,20 +106,37 @@ diesel::table! {
|
|||||||
email -> Varchar,
|
email -> Varchar,
|
||||||
password -> Varchar,
|
password -> Varchar,
|
||||||
created_at -> Timestamp,
|
created_at -> Timestamp,
|
||||||
|
admin -> Bool,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
diesel::joinable!(album_artists -> albums (album_id));
|
diesel::joinable!(album_artists -> albums (album_id));
|
||||||
diesel::joinable!(album_artists -> artists (artist_id));
|
diesel::joinable!(album_artists -> artists (artist_id));
|
||||||
|
diesel::joinable!(playlist_songs -> playlists (playlist_id));
|
||||||
|
diesel::joinable!(playlist_songs -> songs (song_id));
|
||||||
|
diesel::joinable!(playlists -> users (owner_id));
|
||||||
diesel::joinable!(song_artists -> artists (artist_id));
|
diesel::joinable!(song_artists -> artists (artist_id));
|
||||||
diesel::joinable!(song_artists -> songs (song_id));
|
diesel::joinable!(song_artists -> songs (song_id));
|
||||||
|
diesel::joinable!(song_dislikes -> songs (song_id));
|
||||||
|
diesel::joinable!(song_dislikes -> users (user_id));
|
||||||
|
diesel::joinable!(song_history -> songs (song_id));
|
||||||
|
diesel::joinable!(song_history -> users (user_id));
|
||||||
|
diesel::joinable!(song_likes -> songs (song_id));
|
||||||
|
diesel::joinable!(song_likes -> users (user_id));
|
||||||
diesel::joinable!(songs -> albums (album_id));
|
diesel::joinable!(songs -> albums (album_id));
|
||||||
|
|
||||||
diesel::allow_tables_to_appear_in_same_query!(
|
diesel::allow_tables_to_appear_in_same_query!(
|
||||||
album_artists,
|
album_artists,
|
||||||
albums,
|
albums,
|
||||||
artists,
|
artists,
|
||||||
|
friend_requests,
|
||||||
|
friendships,
|
||||||
|
playlist_songs,
|
||||||
|
playlists,
|
||||||
song_artists,
|
song_artists,
|
||||||
|
song_dislikes,
|
||||||
|
song_history,
|
||||||
|
song_likes,
|
||||||
songs,
|
songs,
|
||||||
users,
|
users,
|
||||||
);
|
);
|
||||||
|
@ -102,7 +102,7 @@ pub async fn search(query: String, limit: i64) -> Result<(Vec<Album>, Vec<Artist
|
|||||||
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 futures::join;
|
use tokio::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?))
|
||||||
|
@ -1,16 +1,82 @@
|
|||||||
|
use crate::models::{Album, Artist, Song};
|
||||||
|
use crate::components::dashboard_tile::DashboardTile;
|
||||||
|
|
||||||
|
use serde::{Serialize, Deserialize};
|
||||||
|
use chrono::NaiveDate;
|
||||||
|
|
||||||
/// Holds information about a song
|
/// Holds information about a song
|
||||||
#[derive(Debug, Clone)]
|
///
|
||||||
|
/// Intended to be used in the front-end, as it includes artist and album objects, rather than just their ids.
|
||||||
|
#[derive(Serialize, Deserialize, Clone)]
|
||||||
pub struct SongData {
|
pub struct SongData {
|
||||||
|
/// Song id
|
||||||
|
pub id: i32,
|
||||||
/// Song name
|
/// Song name
|
||||||
pub name: String,
|
pub title: String,
|
||||||
/// Song artist
|
/// Song artists
|
||||||
pub artist: String,
|
pub artists: Vec<Artist>,
|
||||||
/// Song album
|
/// Song album
|
||||||
pub album: String,
|
pub album: Option<Album>,
|
||||||
|
/// The track number of the song on the album
|
||||||
|
pub track: Option<i32>,
|
||||||
|
/// The duration of the song in seconds
|
||||||
|
pub duration: i32,
|
||||||
|
/// The song's release date
|
||||||
|
pub release_date: Option<NaiveDate>,
|
||||||
/// Path to song file, relative to the root of the web server.
|
/// Path to song file, relative to the root of the web server.
|
||||||
/// For example, `"/assets/audio/Song.mp3"`
|
/// For example, `"/assets/audio/Song.mp3"`
|
||||||
pub song_path: String,
|
pub song_path: String,
|
||||||
/// Path to song image, relative to the root of the web server.
|
/// Path to song image, relative to the root of the web server.
|
||||||
/// For example, `"/assets/images/Song.jpg"`
|
/// For example, `"/assets/images/Song.jpg"`
|
||||||
pub image_path: String,
|
pub image_path: String,
|
||||||
|
/// Whether the song is liked by the user
|
||||||
|
pub like_dislike: Option<(bool, bool)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
impl TryInto<Song> for SongData {
|
||||||
|
type Error = Box<dyn std::error::Error>;
|
||||||
|
|
||||||
|
/// Convert a SongData object into a Song object
|
||||||
|
///
|
||||||
|
/// The SongData/Song conversions are also not truly reversible,
|
||||||
|
/// due to the way the image_path data is handled.
|
||||||
|
fn try_into(self) -> Result<Song, Self::Error> {
|
||||||
|
Ok(Song {
|
||||||
|
id: Some(self.id),
|
||||||
|
title: self.title,
|
||||||
|
album_id: self.album.map(|album|
|
||||||
|
album.id.ok_or("Album id must be present (Some) to convert to Song")).transpose()?,
|
||||||
|
track: self.track,
|
||||||
|
duration: self.duration,
|
||||||
|
release_date: self.release_date,
|
||||||
|
storage_path: self.song_path,
|
||||||
|
|
||||||
|
// Note that if the source of the image_path was the album, the image_path
|
||||||
|
// will be set to the album's image_path instead of None
|
||||||
|
image_path: if self.image_path == "/assets/images/placeholder.jpg" {
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
Some(self.image_path)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DashboardTile for SongData {
|
||||||
|
fn image_path(&self) -> String {
|
||||||
|
self.image_path.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn title(&self) -> String {
|
||||||
|
self.title.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn link(&self) -> String {
|
||||||
|
format!("/song/{}", self.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn description(&self) -> Option<String> {
|
||||||
|
Some(format!("Song • {}", Artist::display_list(&self.artists)))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
292
src/upload.rs
Normal file
292
src/upload.rs
Normal file
@ -0,0 +1,292 @@
|
|||||||
|
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 chrono::NaiveDate;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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<NaiveDate>, ServerFnError> {
|
||||||
|
match release_date.text().await {
|
||||||
|
Ok(release_date) => {
|
||||||
|
if release_date.trim().is_empty() {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
|
||||||
|
let release_date = NaiveDate::parse_from_str(&release_date.trim(), "%Y-%m-%d");
|
||||||
|
|
||||||
|
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_str = chrono::Utc::now().format("%Y-%m-%d_%H:%M:%S").to_string();
|
||||||
|
let upload_path = format!("assets/audio/upload-{}_{}.mp3", date_str, clean_title);
|
||||||
|
file_name = Some(format!("upload-{}_{}.mp3", date_str, clean_title));
|
||||||
|
|
||||||
|
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(())
|
||||||
|
}
|
14
src/users.rs
14
src/users.rs
@ -117,7 +117,7 @@ pub async fn validate_user(credentials: UserCredentials) -> Result<Option<User>,
|
|||||||
|
|
||||||
/// 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
|
||||||
#[server(endpoint = "get_user")]
|
#[server(endpoint = "find_user")]
|
||||||
pub async fn get_user(username_or_email: String) -> Result<Option<User>, ServerFnError> {
|
pub async fn get_user(username_or_email: String) -> Result<Option<User>, ServerFnError> {
|
||||||
let mut user = find_user(username_or_email).await?;
|
let mut user = find_user(username_or_email).await?;
|
||||||
|
|
||||||
@ -128,3 +128,15 @@ pub async fn get_user(username_or_email: String) -> Result<Option<User>, ServerF
|
|||||||
|
|
||||||
Ok(user)
|
Ok(user)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[server(endpoint = "get_user_by_id")]
|
||||||
|
pub async fn get_user_by_id(user_id: i32) -> Result<Option<User>, ServerFnError> {
|
||||||
|
let mut user = find_user_by_id(user_id).await?;
|
||||||
|
|
||||||
|
// Remove the password hash before returning the user
|
||||||
|
if let Some(user) = user.as_mut() {
|
||||||
|
user.password = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(user)
|
||||||
|
}
|
||||||
|
37
src/util/audio.rs
Normal file
37
src/util/audio.rs
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
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))
|
||||||
|
}
|
10
src/util/mod.rs
Normal file
10
src/util/mod.rs
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
use cfg_if::cfg_if;
|
||||||
|
|
||||||
|
cfg_if! {
|
||||||
|
if #[cfg(feature = "ssr")] {
|
||||||
|
pub mod audio;
|
||||||
|
pub mod require_auth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub mod state;
|
46
src/util/require_auth.rs
Normal file
46
src/util/require_auth.rs
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
use axum::extract::Request;
|
||||||
|
use axum::response::Response;
|
||||||
|
use axum::body::Body;
|
||||||
|
use axum::middleware::Next;
|
||||||
|
use axum_login::AuthSession;
|
||||||
|
use http::StatusCode;
|
||||||
|
|
||||||
|
use crate::auth_backend::AuthBackend;
|
||||||
|
|
||||||
|
use axum::extract::FromRequestParts;
|
||||||
|
|
||||||
|
// Things in pkg/ are allowed automatically. This includes the CSS/JS/WASM files
|
||||||
|
const ALLOWED_PATHS: [&str; 5] = ["/login", "/signup", "/api/login", "/api/signup", "/favicon.ico"];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Middleware to require authentication for all paths except those in ALLOWED_PATHS
|
||||||
|
*
|
||||||
|
* If a user is not authenticated, they will be redirected to the login page
|
||||||
|
*/
|
||||||
|
pub async fn require_auth_middleware(req: Request, next: Next) -> Result<Response<Body>, (StatusCode, &'static str)> {
|
||||||
|
let path = req.uri().path();
|
||||||
|
|
||||||
|
if !ALLOWED_PATHS.iter().any(|&x| x == path) {
|
||||||
|
let (mut parts, body) = req.into_parts();
|
||||||
|
|
||||||
|
let auth_session = AuthSession::<AuthBackend>::from_request_parts(&mut parts, &())
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
if auth_session.user.is_none() {
|
||||||
|
let response = Response::builder()
|
||||||
|
.status(StatusCode::TEMPORARY_REDIRECT)
|
||||||
|
.header("Location", "/login")
|
||||||
|
.body(Body::empty())
|
||||||
|
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Failed to build response"))?;
|
||||||
|
|
||||||
|
return Ok(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
let req = Request::from_parts(parts, body);
|
||||||
|
let response = next.run(req).await;
|
||||||
|
Ok(response)
|
||||||
|
} else {
|
||||||
|
let response = next.run(req).await;
|
||||||
|
Ok(response)
|
||||||
|
}
|
||||||
|
}
|
49
src/util/state.rs
Normal file
49
src/util/state.rs
Normal file
@ -0,0 +1,49 @@
|
|||||||
|
use leptos::*;
|
||||||
|
use leptos::logging::*;
|
||||||
|
|
||||||
|
use crate::playstatus::PlayStatus;
|
||||||
|
use crate::models::User;
|
||||||
|
use crate::auth::get_logged_in_user;
|
||||||
|
|
||||||
|
/// Global front-end state
|
||||||
|
/// Contains anything frequently needed across multiple components
|
||||||
|
/// Behaves like a singleton, in that provide/expect_context will
|
||||||
|
/// always return the same instance
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct GlobalState {
|
||||||
|
/// A resource that fetches the logged in user
|
||||||
|
/// This will not automatically refetch, so any login/logout related code
|
||||||
|
/// should call `refetch` on this resource
|
||||||
|
pub logged_in_user: Resource<(), Option<User>>,
|
||||||
|
|
||||||
|
/// The current play status
|
||||||
|
pub play_status: RwSignal<PlayStatus>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GlobalState {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
let play_status = create_rw_signal(PlayStatus::default());
|
||||||
|
|
||||||
|
let logged_in_user = create_resource(|| (), |_| async {
|
||||||
|
get_logged_in_user().await
|
||||||
|
.inspect_err(|e| {
|
||||||
|
error!("Error getting logged in user: {:?}", e);
|
||||||
|
})
|
||||||
|
.ok()
|
||||||
|
.flatten()
|
||||||
|
});
|
||||||
|
|
||||||
|
Self {
|
||||||
|
logged_in_user,
|
||||||
|
play_status,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn logged_in_user() -> Resource<(), Option<User>> {
|
||||||
|
expect_context::<Self>().logged_in_user
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn play_status() -> RwSignal<PlayStatus> {
|
||||||
|
expect_context::<Self>().play_status
|
||||||
|
}
|
||||||
|
}
|
80
style/album_page.scss
Normal file
80
style/album_page.scss
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
@import 'theme.scss';
|
||||||
|
|
||||||
|
.album-page-container {
|
||||||
|
width: 90vw;
|
||||||
|
|
||||||
|
.album-header {
|
||||||
|
height: 40vh;
|
||||||
|
width: 65vw;
|
||||||
|
margin: auto;
|
||||||
|
|
||||||
|
|
||||||
|
padding:20px;
|
||||||
|
|
||||||
|
background-image: linear-gradient($accent-color, $background-color);
|
||||||
|
border-radius: 15px;
|
||||||
|
|
||||||
|
.album-info {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.album-info {
|
||||||
|
display: flex;
|
||||||
|
flex-flow: row nowrap;
|
||||||
|
justify-content: space-around;
|
||||||
|
|
||||||
|
.album-image {
|
||||||
|
max-width: 80%;
|
||||||
|
max-height: 80%;
|
||||||
|
box-shadow: 10px 10px 50px -10px $background-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
.album-body {
|
||||||
|
display: flex;
|
||||||
|
flex-flow: column nowrap;
|
||||||
|
justify-content: center;
|
||||||
|
|
||||||
|
.album-title {
|
||||||
|
color: $text-controls-color;
|
||||||
|
font-size: 40px;
|
||||||
|
font-weight: bold;
|
||||||
|
margin:15px;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.album-artists {
|
||||||
|
display: flex;
|
||||||
|
flex-flow: row wrap;
|
||||||
|
justify-content: space-around;
|
||||||
|
align-content: space-around;
|
||||||
|
margin:15px;
|
||||||
|
|
||||||
|
color: $text-controls-color;
|
||||||
|
font-size: 20px;
|
||||||
|
|
||||||
|
.album-artist {
|
||||||
|
margin: 5px;
|
||||||
|
text-align: center;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: $text-controls-color;
|
||||||
|
}
|
||||||
|
a:visited {
|
||||||
|
color: $text-controls-color;
|
||||||
|
}
|
||||||
|
a:hover {
|
||||||
|
color: $controls-hover-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:active {
|
||||||
|
color: $controls-click-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
@ -1,7 +1,6 @@
|
|||||||
@import "theme.scss";
|
@import "theme.scss";
|
||||||
|
|
||||||
.dashboard-container {
|
.dashboard-container {
|
||||||
width: calc(100% - 22rem - 16rem);
|
|
||||||
.dashboard-header {
|
.dashboard-header {
|
||||||
font-size: 1.2rem;
|
font-size: 1.2rem;
|
||||||
font-weight: 300;
|
font-weight: 300;
|
||||||
|
45
style/dashboard_row.scss
Normal file
45
style/dashboard_row.scss
Normal file
@ -0,0 +1,45 @@
|
|||||||
|
.dashboard-tile-row {
|
||||||
|
.dashboard-tile-row-title-row {
|
||||||
|
display: flex;
|
||||||
|
|
||||||
|
.dashboard-tile-row-scroll-btn {
|
||||||
|
margin-left: auto;
|
||||||
|
margin-top: auto;
|
||||||
|
margin-bottom: auto;
|
||||||
|
|
||||||
|
button {
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
|
||||||
|
.dashboard-tile-row-scroll {
|
||||||
|
color: $text-controls-color;
|
||||||
|
width: 2.5rem;
|
||||||
|
height: 2.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-tile-row-scroll:hover {
|
||||||
|
color: $controls-hover-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
.dashboard-tile-row-scroll:active {
|
||||||
|
color: $controls-click-color;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ul {
|
||||||
|
display: flex;
|
||||||
|
overflow-x: hidden;
|
||||||
|
scroll-behavior: smooth;
|
||||||
|
margin-left: 40px;
|
||||||
|
padding-inline-start: 0;
|
||||||
|
|
||||||
|
li {
|
||||||
|
list-style-type: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
-webkit-mask-image: linear-gradient(90deg, #000000 95%, transparent);
|
||||||
|
mask-image: linear-gradient(90deg, #000000 95%, transparent);
|
||||||
|
}
|
||||||
|
}
|
28
style/dashboard_tile.scss
Normal file
28
style/dashboard_tile.scss
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
.dashboard-tile {
|
||||||
|
img {
|
||||||
|
width: $dashboard-tile-size;
|
||||||
|
height: $dashboard-tile-size;
|
||||||
|
border-radius: 7px;
|
||||||
|
margin-right: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
text-decoration: none;
|
||||||
|
color: $text-controls-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
p.dashboard-tile-title {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: bold;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
p.dashboard-tile-description {
|
||||||
|
font-size: 12px;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
margin-right: 10px;
|
||||||
|
}
|
18
style/error.scss
Normal file
18
style/error.scss
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
.error-container {
|
||||||
|
.error-header {
|
||||||
|
display: inline-grid;
|
||||||
|
|
||||||
|
svg {
|
||||||
|
width: 30px;
|
||||||
|
height: 30px;
|
||||||
|
grid-row-start: 1;
|
||||||
|
align-self: center;
|
||||||
|
padding-right: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
grid-row-start: 1;
|
||||||
|
align-self: center;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -9,8 +9,9 @@
|
|||||||
}
|
}
|
||||||
.home-component {
|
.home-component {
|
||||||
background: #1c1c1c;
|
background: #1c1c1c;
|
||||||
height: 100vh;
|
width: calc(100% - 22rem - 16rem);
|
||||||
margin: 2px;
|
margin: 2px;
|
||||||
padding: 0.2rem 1.5rem 1.5rem 1rem;
|
padding: 0.2rem 1.5rem $playbar-size 1rem;
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
|
overflow: scroll;
|
||||||
}
|
}
|
||||||
|
59
style/loading.scss
Normal file
59
style/loading.scss
Normal file
@ -0,0 +1,59 @@
|
|||||||
|
@import "theme.scss";
|
||||||
|
|
||||||
|
.loading-page {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading {
|
||||||
|
position: relative;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 5px;
|
||||||
|
margin: 10px;
|
||||||
|
background-color: $accent-color;
|
||||||
|
color: $accent-color;
|
||||||
|
animation: dot-flashing 1s infinite linear alternate;
|
||||||
|
animation-delay: 0.5s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading::before, .loading::after {
|
||||||
|
content: "";
|
||||||
|
display: inline-block;
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading::before {
|
||||||
|
left: -15px;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 5px;
|
||||||
|
background-color: $accent-color;
|
||||||
|
color: $accent-color;
|
||||||
|
animation: dot-flashing 1s infinite alternate;
|
||||||
|
animation-delay: 0s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.loading::after {
|
||||||
|
left: 15px;
|
||||||
|
width: 10px;
|
||||||
|
height: 10px;
|
||||||
|
border-radius: 5px;
|
||||||
|
background-color: $accent-color;
|
||||||
|
color: $accent-color;
|
||||||
|
animation: dot-flashing 1s infinite alternate;
|
||||||
|
animation-delay: 1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes dot-flashing {
|
||||||
|
0% {
|
||||||
|
background-color: $accent-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
50%, 100% {
|
||||||
|
background-color: $controls-hover-color;
|
||||||
|
}
|
||||||
|
}
|
@ -8,7 +8,7 @@
|
|||||||
top: 50%;
|
top: 50%;
|
||||||
left: 50%;
|
left: 50%;
|
||||||
width: 27rem;
|
width: 27rem;
|
||||||
height: 30rem;
|
height: 31rem;
|
||||||
transform: translate(-50%, -50%);
|
transform: translate(-50%, -50%);
|
||||||
background: $auth-containers;
|
background: $auth-containers;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
@ -96,6 +96,17 @@
|
|||||||
color: #fff;
|
color: #fff;
|
||||||
transition: all 0.2s;
|
transition: all 0.2s;
|
||||||
}
|
}
|
||||||
|
.login-form .error-msg {
|
||||||
|
color: $error-color;
|
||||||
|
margin-top: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
}
|
||||||
|
.login-form .loading {
|
||||||
|
margin-top: 4.5rem;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-bottom: calc(1.5rem - 10px);
|
||||||
|
}
|
||||||
.login-form input[type="submit"] {
|
.login-form input[type="submit"] {
|
||||||
margin-top: 3rem;
|
margin-top: 3rem;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
@ -8,6 +8,14 @@
|
|||||||
@import 'home.scss';
|
@import 'home.scss';
|
||||||
@import 'search.scss';
|
@import 'search.scss';
|
||||||
@import 'personal.scss';
|
@import 'personal.scss';
|
||||||
|
@import 'dashboard_tile.scss';
|
||||||
|
@import 'dashboard_row.scss';
|
||||||
|
@import 'upload.scss';
|
||||||
|
@import 'error.scss';
|
||||||
|
@import 'song_list.scss';
|
||||||
|
@import 'profile.scss';
|
||||||
|
@import 'loading.scss';
|
||||||
|
@import 'album_page.scss';
|
||||||
|
|
||||||
body {
|
body {
|
||||||
font-family: sans-serif;
|
font-family: sans-serif;
|
||||||
|
@ -3,7 +3,6 @@
|
|||||||
.personal-container {
|
.personal-container {
|
||||||
width: 16rem;
|
width: 16rem;
|
||||||
background: #1c1c1c;
|
background: #1c1c1c;
|
||||||
height: 100vh;
|
|
||||||
margin: 2px;
|
margin: 2px;
|
||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
|
|
||||||
@ -12,9 +11,19 @@
|
|||||||
border-radius: 0.4rem;
|
border-radius: 0.4rem;
|
||||||
margin: 0.2rem;
|
margin: 0.2rem;
|
||||||
min-height: 6rem;
|
min-height: 6rem;
|
||||||
border: 2px solid rgba(89, 89, 89, 0.199);
|
border: 0.2rem solid rgba(89, 89, 89, 0.199);
|
||||||
padding: 0.5rem;
|
padding: 0.5rem;
|
||||||
|
|
||||||
|
.profile-name {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
h1 {
|
||||||
|
font-size: 1.2rem;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
.profile-icon {
|
.profile-icon {
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
padding: 0.2rem;
|
padding: 0.2rem;
|
||||||
@ -22,17 +31,23 @@
|
|||||||
font-size: 2rem;
|
font-size: 2rem;
|
||||||
border-radius: 50%;
|
border-radius: 50%;
|
||||||
transition: all 0.3s;
|
transition: all 0.3s;
|
||||||
height: max-content;
|
height: 45;
|
||||||
|
width: 45;
|
||||||
margin-left: auto;
|
margin-left: auto;
|
||||||
|
.profile-image {
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border-radius: 50%;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-icon:hover {
|
.profile-icon:hover {
|
||||||
transform: scale(1.1);
|
transform: scale(1.05);
|
||||||
background-color: rgba(255, 255, 255, 0.1);
|
background-color: rgba(255, 255, 255, 0.1);
|
||||||
}
|
}
|
||||||
|
|
||||||
.profile-icon:active {
|
.profile-icon:active {
|
||||||
transform: scale(0.8);
|
transform: scale(0.95);
|
||||||
}
|
}
|
||||||
.dropdown-container {
|
.dropdown-container {
|
||||||
position: absolute;
|
position: absolute;
|
||||||
@ -42,10 +57,10 @@
|
|||||||
border-radius: 0.5rem;
|
border-radius: 0.5rem;
|
||||||
width: 10rem;
|
width: 10rem;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
background-color: red;
|
background-color: #1c1c1c;
|
||||||
border: 1px solid grey;
|
border: 0.2rem solid rgba(89, 89, 89, 0.199);
|
||||||
|
|
||||||
.dropdown-not-logged {
|
.dropdown-logged {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
@ -54,21 +69,29 @@
|
|||||||
h1 {
|
h1 {
|
||||||
font-size: 1.2rem;
|
font-size: 1.2rem;
|
||||||
}
|
}
|
||||||
|
.profile-info {
|
||||||
|
display: flex;
|
||||||
|
width: 100%;
|
||||||
|
justify-content: center;
|
||||||
|
border-top: 0.2rem solid rgba(89, 89, 89, 0.199);
|
||||||
|
border-bottom: 0.2rem solid rgba(89, 89, 89, 0.199);
|
||||||
|
h1 {
|
||||||
|
font-size: 1rem;
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
.auth-button {
|
.auth-button {
|
||||||
|
margin-top: 0.5rem;
|
||||||
|
padding: 0.5rem;
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
background-color: #1c1c1c;
|
||||||
|
border: 0.2rem solid rgba(89, 89, 89, 0.199);
|
||||||
|
color: white;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.3s;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.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;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
.playbar {
|
.playbar {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
height: 75px;
|
height: $playbar-size;
|
||||||
background-color: $play-bar-background-color;
|
background-color: $play-bar-background-color;
|
||||||
opacity: 0.9;
|
opacity: 0.9;
|
||||||
position: fixed;
|
position: fixed;
|
||||||
@ -39,15 +39,12 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.media-info {
|
.playbar-left-group {
|
||||||
font-size: 16;
|
display: flex;
|
||||||
margin-left: 10px;
|
|
||||||
|
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 50%;
|
top: 50%;
|
||||||
transform: translateY(-50%);
|
transform: translateY(-50%);
|
||||||
display: grid;
|
margin-left: 10px;
|
||||||
grid-template-columns: 50px 1fr;
|
|
||||||
|
|
||||||
.media-info-img {
|
.media-info-img {
|
||||||
width: 50px;
|
width: 50px;
|
||||||
@ -57,6 +54,10 @@
|
|||||||
text-align: left;
|
text-align: left;
|
||||||
margin-left: 10px;
|
margin-left: 10px;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.like-dislike {
|
||||||
|
margin-left: 20px;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.playcontrols {
|
.playcontrols {
|
||||||
@ -64,23 +65,6 @@
|
|||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
|
|
||||||
button {
|
|
||||||
.controlbtn {
|
|
||||||
color: $text-controls-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
.controlbtn:hover {
|
|
||||||
color: $controls-hover-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
.controlbtn:active {
|
|
||||||
color: $controls-click-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
background-color: transparent;
|
|
||||||
border: transparent;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.playduration {
|
.playduration {
|
||||||
@ -94,8 +78,17 @@
|
|||||||
bottom: 13px;
|
bottom: 13px;
|
||||||
top: 13px;
|
top: 13px;
|
||||||
right: 90px;
|
right: 90px;
|
||||||
|
}
|
||||||
|
|
||||||
button {
|
button {
|
||||||
|
.hmirror {
|
||||||
|
-moz-transform: scale(-1, 1);
|
||||||
|
-webkit-transform: scale(-1, 1);
|
||||||
|
-o-transform: scale(-1, 1);
|
||||||
|
-ms-transform: scale(-1, 1);
|
||||||
|
transform: scale(-1, 1);
|
||||||
|
}
|
||||||
|
|
||||||
.controlbtn {
|
.controlbtn {
|
||||||
color: $text-controls-color;
|
color: $text-controls-color;
|
||||||
}
|
}
|
||||||
@ -112,4 +105,3 @@
|
|||||||
border: transparent;
|
border: transparent;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
36
style/profile.scss
Normal file
36
style/profile.scss
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
@import 'theme.scss';
|
||||||
|
|
||||||
|
.profile-container {
|
||||||
|
.profile-header {
|
||||||
|
display: flex;
|
||||||
|
|
||||||
|
.profile-image {
|
||||||
|
width: 75px;
|
||||||
|
height: 75px;
|
||||||
|
border-radius: 50%;
|
||||||
|
padding: 10px;
|
||||||
|
padding-bottom: 5px;
|
||||||
|
margin-top: auto;
|
||||||
|
margin-bottom: auto;
|
||||||
|
|
||||||
|
svg {
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 {
|
||||||
|
font-size: 40px;
|
||||||
|
align-self: center;
|
||||||
|
padding: 10px;
|
||||||
|
padding-bottom: 5px;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
.profile-details {
|
||||||
|
p {
|
||||||
|
font-size: 1rem;
|
||||||
|
margin: 0.5rem;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,6 +1,4 @@
|
|||||||
@import "theme.scss";
|
@import "theme.scss";
|
||||||
|
|
||||||
.search-container {
|
.search-container {
|
||||||
width: calc(100% - 22rem - 16rem);
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
@ -4,20 +4,43 @@
|
|||||||
background-color: transparent;
|
background-color: transparent;
|
||||||
width: 22rem;
|
width: 22rem;
|
||||||
height: calc(100% - 75px);
|
height: calc(100% - 75px);
|
||||||
}
|
|
||||||
|
|
||||||
.sidebar-top-container {
|
.sidebar-top-container {
|
||||||
border-radius: 1rem;
|
border-radius: 1rem;
|
||||||
background-color: #1c1c1c;
|
background-color: #1c1c1c;
|
||||||
height: 9rem;
|
height: 9rem;
|
||||||
margin: 3px;
|
margin: 3px;
|
||||||
padding: 0.1rem 1rem 1rem 1rem;
|
padding: 0.1rem 1rem 1rem 1rem;
|
||||||
}
|
position: relative;
|
||||||
|
.header {
|
||||||
.sidebar-top-container .header {
|
|
||||||
font-size: 1.2rem;
|
font-size: 1.2rem;
|
||||||
}
|
}
|
||||||
.sidebar-top-container .buttons {
|
.upload-btn {
|
||||||
|
position: absolute;
|
||||||
|
top: 10px;
|
||||||
|
right: 7px;
|
||||||
|
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: 1rem;
|
||||||
|
padding-left: 1rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.3s ease;
|
||||||
|
.add-sign {
|
||||||
|
font-size: 1.5rem;
|
||||||
|
margin-top: auto;
|
||||||
|
margin-right: 5px;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.upload-btn:hover {
|
||||||
|
background-color: #9e9e9e;
|
||||||
|
}
|
||||||
|
.buttons {
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: row;
|
flex-direction: row;
|
||||||
font-size: 1.8rem;
|
font-size: 1.8rem;
|
||||||
@ -25,24 +48,23 @@
|
|||||||
transition: all 0.5s;
|
transition: all 0.5s;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
color: grey;
|
color: grey;
|
||||||
|
text-decoration: none;
|
||||||
}
|
}
|
||||||
.sidebar-top-container .buttons:hover {
|
.buttons:hover {
|
||||||
color: white;
|
color: white;
|
||||||
}
|
}
|
||||||
|
.buttons:last-child {
|
||||||
.sidebar-top-container .buttons:last-child {
|
|
||||||
margin-left: 0.02rem;
|
margin-left: 0.02rem;
|
||||||
margin-top: 0.5rem;
|
margin-top: 0.5rem;
|
||||||
}
|
}
|
||||||
|
h1 {
|
||||||
.sidebar-top-container h1 {
|
|
||||||
font-size: 0.95rem;
|
font-size: 0.95rem;
|
||||||
margin-left: 0.9rem;
|
margin-left: 0.9rem;
|
||||||
font-weight: 400;
|
font-weight: 400;
|
||||||
font-style: $standard-font;
|
font-style: $standard-font;
|
||||||
letter-spacing: 0.5px;
|
letter-spacing: 0.5px;
|
||||||
}
|
}
|
||||||
|
}
|
||||||
.sidebar-bottom-container {
|
.sidebar-bottom-container {
|
||||||
border-radius: 1rem;
|
border-radius: 1rem;
|
||||||
background-color: #1c1c1c;
|
background-color: #1c1c1c;
|
||||||
@ -89,3 +111,6 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@ -17,7 +17,7 @@
|
|||||||
top: 50%;
|
top: 50%;
|
||||||
left: 50%;
|
left: 50%;
|
||||||
width: 27rem;
|
width: 27rem;
|
||||||
height: 35rem;
|
height: 36rem;
|
||||||
transform: translate(-50%, -50%);
|
transform: translate(-50%, -50%);
|
||||||
background: $auth-containers;
|
background: $auth-containers;
|
||||||
z-index: 1;
|
z-index: 1;
|
||||||
@ -92,7 +92,17 @@
|
|||||||
.signup-form .input-box input:focus ~ i {
|
.signup-form .input-box input:focus ~ i {
|
||||||
height: 2.6rem;
|
height: 2.6rem;
|
||||||
}
|
}
|
||||||
|
.signup-form .error-msg {
|
||||||
|
color: $error-color;
|
||||||
|
margin-top: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
}
|
||||||
|
.signup-form .loading {
|
||||||
|
margin-top: 4.5rem;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-bottom: calc(1.5rem - 10px);
|
||||||
|
}
|
||||||
.signup-form input[type="submit"] {
|
.signup-form input[type="submit"] {
|
||||||
margin-top: 3.5rem;
|
margin-top: 3.5rem;
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
124
style/song_list.scss
Normal file
124
style/song_list.scss
Normal file
@ -0,0 +1,124 @@
|
|||||||
|
table.song-list {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
|
||||||
|
tr.song-list-item {
|
||||||
|
border: solid;
|
||||||
|
border-width: 1px 0;
|
||||||
|
border-color: #303030;
|
||||||
|
position: relative;
|
||||||
|
|
||||||
|
td {
|
||||||
|
color: $text-controls-color;
|
||||||
|
white-space: nowrap;
|
||||||
|
padding-left: 10px;
|
||||||
|
padding-right: 10px;
|
||||||
|
|
||||||
|
a {
|
||||||
|
text-decoration: none;
|
||||||
|
color: $text-controls-color;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
text-decoration: underline $controls-hover-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
td.song-image {
|
||||||
|
width: 35px;
|
||||||
|
display: flex;
|
||||||
|
|
||||||
|
img.song-image {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
-ms-transform: translateY(-50%);
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 35px;
|
||||||
|
height: 35px;
|
||||||
|
border-radius: 5px;
|
||||||
|
}
|
||||||
|
|
||||||
|
svg.song-image-overlay {
|
||||||
|
position: absolute;
|
||||||
|
top: 50%;
|
||||||
|
-ms-transform: translateY(-50%);
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 35px;
|
||||||
|
height: 35px;
|
||||||
|
border-radius: 5px;
|
||||||
|
fill: $text-controls-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
svg.song-image-overlay:hover {
|
||||||
|
fill: $controls-hover-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
svg.song-image-overlay:active {
|
||||||
|
fill: $controls-click-color;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
td.song-list-spacer {
|
||||||
|
width: 20%;
|
||||||
|
}
|
||||||
|
|
||||||
|
td.song-list-spacer-big {
|
||||||
|
width: 40%;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
svg.hmirror {
|
||||||
|
-moz-transform: scale(-1, 1);
|
||||||
|
-webkit-transform: scale(-1, 1);
|
||||||
|
-o-transform: scale(-1, 1);
|
||||||
|
-ms-transform: scale(-1, 1);
|
||||||
|
transform: scale(-1, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.controlbtn {
|
||||||
|
color: $text-controls-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controlbtn:hover {
|
||||||
|
color: $controls-hover-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controlbtn:active {
|
||||||
|
color: $controls-click-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
background-color: transparent;
|
||||||
|
border: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hide-until-hover {
|
||||||
|
visibility: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.song-playing-overlay {
|
||||||
|
background-color: rgba(0, 0, 0, 0.8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
tr.song-list-item:first-child {
|
||||||
|
border-top: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr.song-list-item:last-child {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
tr.song-list-item:hover {
|
||||||
|
background-color: #303030;
|
||||||
|
|
||||||
|
.hide-until-hover {
|
||||||
|
visibility: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
td.song-image {
|
||||||
|
svg.song-image-overlay {
|
||||||
|
background-color: rgba(0, 0, 0, 0.8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -10,7 +10,12 @@ $controls-click-color: #909090;
|
|||||||
$play-bar-background-color: #212121;
|
$play-bar-background-color: #212121;
|
||||||
$play-grad-start: #0a0533;
|
$play-grad-start: #0a0533;
|
||||||
$play-grad-end: $accent-color;
|
$play-grad-end: $accent-color;
|
||||||
|
$border-color: #7851ed;
|
||||||
$queue-background-color: $play-bar-background-color;
|
$queue-background-color: $play-bar-background-color;
|
||||||
|
$error-color: red;
|
||||||
|
|
||||||
$auth-inputs: #796dd4;
|
$auth-inputs: #796dd4;
|
||||||
$auth-containers: white;
|
$auth-containers: white;
|
||||||
|
|
||||||
|
$dashboard-tile-size: 200px;
|
||||||
|
$playbar-size: 75px;
|
188
style/upload.scss
Normal file
188
style/upload.scss
Normal file
@ -0,0 +1,188 @@
|
|||||||
|
@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;
|
||||||
|
.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;
|
||||||
|
.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 {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
x
Reference in New Issue
Block a user