Compare commits

..

227 Commits

Author SHA1 Message Date
f299254d55 Merge pull request 'Fix Docker compose missing libretunes-images volume' (#120) from 119-fix-docker-compose-missing-libretunesimages-volume into main
Reviewed-on: LibreTunes/LibreTunes#120
2024-10-25 19:40:10 +00:00
14aa4d236e Add libretunes-images to volumes 2024-10-25 18:28:45 +00:00
3cfcacc9ba Merge pull request 'Setup routing for image and audio assets based on environment variables' (#107) from 35-make-asset-paths-configurable into main
Reviewed-on: LibreTunes/LibreTunes#107
Reviewed-by: Ethan Girouard <ethan@girouard.com>
2024-10-16 17:48:12 +00:00
f39d93bd0c Change audio and image path Docker comopse settings
Add volume for images
2024-10-15 23:22:15 -04:00
cdffd2c5eb Merge pull request 'Create song list component' (#113) from 106-create-song-list-component into main
Reviewed-on: LibreTunes/LibreTunes#113
2024-10-15 19:31:05 +00:00
e90ea56d14 Remove TODO 2024-10-11 17:16:51 -04:00
b222b7911f Add example environment variables and update docker-compose 2024-10-11 16:53:08 -04:00
0550b18d77 Add SongList component 2024-10-11 13:25:14 -04:00
36e7a5827b Merge pull request 'Create component for displaying music on dashboard' (#105) from 33-create-component-for-displaying-music-on-dashboard into main
Reviewed-on: LibreTunes/LibreTunes#105
2024-10-06 21:49:01 +00:00
134b425ce6 Remove unused MediaType 2024-10-06 15:50:58 -04:00
c678d93661 Create ArtistData, impl DashboardTile 2024-10-06 15:50:58 -04:00
c18bf277b9 Create AlbumData, impl DashboardTile 2024-10-06 15:50:57 -04:00
097b1fc491 impl DashboardTile for Songdata 2024-10-06 15:47:22 -04:00
f02a22d805 Format text inside dashboard tiles normally 2024-10-06 15:47:22 -04:00
553e24800b Refactor DashboardTile into trait 2024-10-06 15:47:18 -04:00
2793391f00 Merge remote-tracking branch 'origin/main' into 33-create-component-for-displaying-music-on-dashboard 2024-10-06 14:16:58 -04:00
cce9b946ec Merge pull request 'Page Title Updates on Playing Song' (#103) from 97-update-page-title-with-current-playing into main
Reviewed-on: LibreTunes/LibreTunes#103
2024-10-05 16:35:02 +00:00
51858593c2 Updated Title Display 2024-10-04 23:56:12 +00:00
2bb9b3bdd7 Page Title Updates on Playing Song 2024-10-04 23:19:07 +00:00
a43955726a Setup routing for image and audio assets based on environment variables 2024-10-04 17:33:51 -04:00
e03853929f Merge pull request 'Update tower to 0.5' (#102) from 101-update-tower-to-05 into main
Reviewed-on: LibreTunes/LibreTunes#102
2024-10-04 19:57:59 +00:00
2c71e065b7 Update tower and tower-http
Remove gloo-net override
2024-10-04 15:14:32 -04:00
20a3c0c7df Merge pull request 'Add Profile Pictures' (#99) from 94-add-profile-pictures into main
Reviewed-on: LibreTunes/LibreTunes#99
2024-10-01 17:01:56 +00:00
b2f138e7e9 Move NoCustomError import to fix warning 2024-10-01 00:17:20 -04:00
33aa285deb Add upload_picture api endpoint 2024-10-01 00:07:26 -04:00
4105d0cedb Update Actions workflows to use new CICD Docker image 2024-09-30 23:57:45 -04:00
414c1f0e20 Use dynamic linking in Docker build
Switch base image to rust:slim
Dynamically link libretunes build
Copy required shared objs to scratch image
Remove CSS minify step (Leptos does this already)
2024-09-30 19:02:59 -04:00
9927b94d59 Add image-convert crate 2024-09-29 17:52:32 -04:00
b9551e5bee Merge pull request 'Implement history' (#98) from 41-implement-history into main
Reviewed-on: LibreTunes/LibreTunes#98
2024-09-29 18:27:08 +00:00
73910a087a Add playing songs to history 2024-09-29 14:04:51 -04:00
236c75492a Merge pull request 'Implement friends' (#96) from 44-implement-friends into main
Reviewed-on: LibreTunes/LibreTunes#96
2024-09-29 01:15:56 +00:00
ec76269367 Fix duplicate api module definition 2024-09-28 20:50:25 -04:00
c92d68dddf Update leptos_use to 0.13.5 2024-09-28 20:50:25 -04:00
8fd064dffc Merge remote-tracking branch 'origin/main' into 41-implement-history 2024-09-28 20:40:37 -04:00
a83fb9dea5 Add friendships and friend_requests database tables 2024-09-28 20:28:00 -04:00
bf89838297 Merge pull request '81_switch-from-gitlab-ci-cd-to-gitea-actions' (#91) from 81_switch-from-gitlab-ci-cd-to-gitea-actions into main
Reviewed-on: LibreTunes/LibreTunes#91
2024-09-16 02:57:38 +00:00
b7e5327903 Add Gitea Actions jobs 2024-09-15 21:49:53 -04:00
8fea5fcec7 Remove GitLab CI/CD file 2024-09-15 21:47:04 -04:00
266bba05aa Merge pull request 'Convert Infaliable Result into Option and handle' (#90) from 89_fix-warning-with-handling-infaliable-result-in-fileserv-rs into main
Reviewed-on: LibreTunes/LibreTunes#90
2024-09-16 01:44:52 +00:00
86f9b6fbb3 Convert Infaliable Result into Option and handle 2024-09-15 21:43:59 -04:00
da45a503ac Merge pull request 'Add Docker build steps from old docker-leptos/musl image' (#88) from 86_combine-old-docker-leptos-musl-image-build-into-dockerfile into main
Reviewed-on: LibreTunes/LibreTunes#88
2024-09-16 01:32:20 +00:00
074f866e5f Add Docker build steps from old docker-leptos/musl image 2024-09-15 21:31:22 -04:00
cb0936003c Merge pull request 'Change target cfg condition to target_env' (#87) from 85_fix-warnings-due-to-removal-of-target-cfg-condition into main
Reviewed-on: LibreTunes/LibreTunes#87
2024-09-16 00:20:10 +00:00
d66849c6cb Change target cfg condition to target_env 2024-09-15 20:18:02 -04:00
b54ecb5b27 Merge pull request 'Update time to v0.3.36' (#84) from 83_update-time-crate-to-fix-type-inference-build-error into main
Reviewed-on: LibreTunes/LibreTunes#84
2024-09-15 00:38:43 +00:00
0ee61f288f Update time to v0.3.36 2024-09-15 00:36:22 +00:00
8c516e3070 Merge pull request 'Update wasm-bindgen to 0.2.93' (#82) from 80_update-wasm-bindgen-to-0.2.93 into main
Reviewed-on: LibreTunes/LibreTunes#82
2024-09-15 00:30:50 +00:00
22f3749ee4 Update wasm-bindgen to 0.2.93 2024-09-15 00:23:43 +00:00
e55656c0e6 Add leptos_use crate 2024-07-30 22:29:13 -04:00
18cbb0017f Merge remote-tracking branch 'origin/31-update-songdata-for-fetching-songs-on-frontend-for-playback' into 36-implement-likes-and-dislikes 2024-07-30 22:12:44 -04:00
53cde3bed6 Hide scroll buttons when at end of scroll bar 2024-07-30 21:47:55 -04:00
eab011070d Don't track scroll_element in scroll button handlers 2024-07-30 21:46:59 -04:00
9d6013b8a4 Move dashboard tile row left spacing to margin-left 2024-07-30 21:35:44 -04:00
fa811350ae Add leptos_use crate 2024-07-30 21:09:10 -04:00
7f4108e1c5 Add conversion from SongData to DashboardTile 2024-07-30 21:02:48 -04:00
906b5bd9dd Merge remote-tracking branch 'origin/31-update-songdata-for-fetching-songs-on-frontend-for-playback' into 33-create-component-for-displaying-music-on-dashboard 2024-07-30 20:57:52 -04:00
7cb556e5ef Merge branch '36-implement-likes-and-dislikes' into 'main'
Implement likes and dislikes

Closes #36

See merge request libretunes/libretunes!32
2024-07-30 20:55:52 -04:00
bab819822d Remove like/dislike API calls TODO comment 2024-07-30 19:34:52 -04:00
0c54f0aeb8 Remove leftover dislike button logging 2024-07-30 19:34:15 -04:00
afbcc65457 Implement like/dislike using SongData instead of PlayStatus 2024-07-28 22:42:04 -04:00
e5a6e8f44e Add like_dislike field to SongData 2024-07-28 22:40:52 -04:00
d45f102be7 Remove TryInto<SongData> for Song
These pre-defined conversion traits are meant to be fast, and implementing this conversion that accesses the database goes against this design.
2024-07-28 22:37:17 -04:00
74b34b1e54 Merge remote-tracking branch 'origin/31-update-songdata-for-fetching-songs-on-frontend-for-playback' into 36-implement-likes-and-dislikes 2024-07-24 17:30:05 -04:00
2ea3979a89 Merge branch '31-update-songdata-for-fetching-songs-on-frontend-for-playback' into 'main'
Resolve "Update SongData for fetching songs on frontend for playback"

Closes #31

See merge request libretunes/libretunes!31
2024-07-24 17:18:10 -04:00
21bb2d127f Fix unused crate::database import 2024-07-23 23:37:48 -04:00
76631126de Add Song/SongData conversions 2024-07-23 23:32:26 -04:00
f8bbe319bd Update SongData for frontend use 2024-07-23 23:31:48 -04:00
ffad799f72 Add function to get song album object 2024-07-23 23:30:15 -04:00
c72d4aee18 Add Arist::display_list function 2024-07-23 22:57:24 -04:00
8a474077da Merge branch '47-add-placeholder-images-for-when-no-artist-album-song-image-is-present' into 'main'
Add music placeholder image

Closes #47

See merge request libretunes/libretunes!30
2024-07-23 21:44:12 -04:00
6202b287f0 Fix music placeholder asset path 2024-07-23 20:51:12 -04:00
6b8c8d41e4 Add music placeholder image 2024-07-21 13:15:55 -04:00
4aa90cdefb Add API functions for getting/adding history 2024-05-19 16:14:38 -04:00
ee70b1080e Add various history functions for users 2024-05-19 15:44:09 -04:00
62def56a41 Add model for history entry 2024-05-19 15:43:58 -04:00
0c64865cd9 Add api module 2024-05-19 15:38:40 -04:00
cc11de4f3d Add get_user auth function 2024-05-19 15:38:40 -04:00
81f0b9310f Add DB table for song history 2024-05-19 12:44:47 -04:00
4513335784 Merge branch '29-implement-admin-user-permission-flag' into 'main'
Implement admin user permission flag

Closes #29

See merge request libretunes/libretunes!28
2024-05-19 12:43:51 -04:00
fa26ee40ed Add auth functions for checking admin status 2024-05-19 12:20:50 -04:00
c27ad19499 Prevent arbitrary admin user creation 2024-05-19 10:45:50 -04:00
6ae55d5cfc Add admin column to users table 2024-05-19 10:45:45 -04:00
7bcb5f8c04 Merge branch '40-reduce-dependencies-and-their-features' into 'main'
Reduce dependencies and their features

Closes #40

See merge request libretunes/libretunes!27
2024-05-18 20:29:27 -04:00
9a462d5ee9 Make async-trait required for backend only 2024-05-18 18:51:59 -04:00
5cc504b4d6 Merge branch '19-implement-file-uploads' into 'main'
Resolve "Implement file uploads"

Closes #19

See merge request libretunes/libretunes!26
2024-05-18 18:51:30 -04:00
eb4dcd4776 Remove tower_sessions dependency 2024-05-18 18:39:14 -04:00
355c791ea7 Reset form fields after sucessful submission 2024-05-18 18:15:50 -04:00
b0edd2174e Don't initially show upload error message 2024-05-18 18:10:48 -04:00
3978526231 Merge remote-tracking branch 'origin/main' into 19-implement-file-uploads 2024-05-18 18:10:03 -04:00
0adf294cfc Display error message when upload song fails 2024-05-18 16:36:37 -04:00
e7e7a8175e Add web_sys dependency 2024-05-18 16:34:48 -04:00
952fb93e1e Only allow mp3 file upload selections 2024-05-18 16:34:07 -04:00
1633d8c1a5 Fix required/optional form fields 2024-05-18 16:33:48 -04:00
b4054aa2b7 Ensure track is specified if album is specified 2024-05-18 16:32:31 -04:00
3934a25900 Handle present but empty fields 2024-05-18 16:32:04 -04:00
26c34e0012 Merge branch '39-add-images-to-albums' into 'main'
Add image_path column to albums table

Closes #39

See merge request libretunes/libretunes!25
2024-05-16 21:58:49 -04:00
522658c0dc Merge branch '38-refactor-navigation-using-leptos-nested-routing' into 'main'
Use nested routing for navigation

Closes #38

See merge request libretunes/libretunes!24
2024-05-16 21:50:21 -04:00
3c9ae521b1 Remove trailing comma from artist id field 2024-05-16 20:59:48 -04:00
4958d3a881 fixed bug 2024-05-16 20:58:27 -04:00
965bf5a457 Reduce axum features to tokio, http1 2024-05-16 19:30:46 -04:00
8ffe09381c Remove futures dependency
Use tokio::join instead of futures::join
2024-05-16 19:23:48 -04:00
12384b5a75 Disable default features in time 2024-05-16 19:18:53 -04:00
bf9067aa43 Disable default features in serde 2024-05-16 19:17:21 -04:00
7b43906632 Disable default features in diesel 2024-05-16 19:14:38 -04:00
4685861af3 Make wasm-bindgen required for frontend only 2024-05-16 19:08:22 -04:00
df78afbe60 Disable default features in wasm-bindgen 2024-05-16 19:07:39 -04:00
caefc46fcc added album search feature for upload 2024-05-16 18:59:16 -04:00
94d62ea2d5 Disable default features in leptos crate 2024-05-16 18:53:58 -04:00
893c411c7f Disable default features in http crate 2024-05-16 18:51:47 -04:00
618b7d65ce Make console_error_panic_hook required for frontend only 2024-05-16 18:47:45 -04:00
78d8e1243d Remove csr feature 2024-05-16 18:42:03 -04:00
955fc84412 allow choosing artists by searching for upload 2024-05-16 18:35:02 -04:00
cc4aee4ab4 Add image_path column to albums table 2024-05-16 18:13:14 -04:00
5775d3148b finished upload design 2024-05-16 15:44:13 -04:00
714fbc596a styled upload form 2024-05-12 23:56:59 -07:00
ff43b3f7e8 Use nested routing for navigation
Remove dashboard_open signal
Use <a> tags to navigate to new pages
Add dashboard and search to nested routing
2024-05-12 11:00:47 -04:00
af66381f5f Implement dashboard row sideways scrolling 2024-05-11 15:23:49 -04:00
683f979bc7 Add styling for dashboard row 2024-05-11 13:16:31 -04:00
f4908ad3b3 Add DashboardRow component 2024-05-11 13:16:02 -04:00
b1cc0f156c Add styling for dashboard tile 2024-05-11 13:08:32 -04:00
ec43ab472d Add DashboardTile component 2024-05-11 13:08:05 -04:00
eebd58f5a6 Add MediaType struct 2024-05-11 12:53:57 -04:00
e411ab9eee Add API functions for liking and disliking songs 2024-05-10 20:32:23 -04:00
775c7eff3a Add api module 2024-05-10 20:32:23 -04:00
2ed67e5545 Add various like/dislike functions for users 2024-05-10 20:32:22 -04:00
08f1b95c18 Add get_user auth function 2024-05-10 20:26:59 -04:00
7a750b60aa Update styling to fit LikeDislike component 2024-05-10 20:26:25 -04:00
2b9d849578 Add styling for horizontally mirrored button 2024-05-10 20:26:25 -04:00
28ff98ab32 Add LikeDislike component 2024-05-10 20:26:10 -04:00
a0da89204c Move MediaInfo into playbar-left-group div 2024-05-10 19:51:27 -04:00
c07237ad8a Move redundant controlbtn styling 2024-05-10 17:38:37 -04:00
727029b757 Create DB tables for likes and dislikes 2024-05-10 16:03:18 -04:00
8a959d530d Implement basic upload dialog 2024-05-10 15:51:26 -04:00
7abfbaf600 Fix unused imports 2024-05-10 15:25:57 -04:00
161ea5f9c2 Implement file upload backend 2024-05-10 15:20:57 -04:00
353a8e3a9c Allow finding Artist and Album by primary key 2024-05-10 14:18:48 -04:00
5d7ac2bb80 Add returning codec type to audio util function 2024-05-10 14:09:24 -04:00
695f404ba8 Merge remote-tracking branch 'origin/main' into 19-implement-file-uploads 2024-05-10 12:49:58 -04:00
79ba191415 Add function to get audio file duration 2024-05-10 11:28:43 -04:00
3338cc2662 Add util module 2024-05-10 11:28:11 -04:00
60ad643669 Merge branch '34-fix-serde-version-warning-in-cargo-toml' into 'main'
Fix unspecified dependency version warnings in Cargo.toml

Closes #34

See merge request libretunes/libretunes!23
2024-05-10 11:11:11 -04:00
490772654d Add multer crate 2024-05-10 10:55:26 -04:00
b2fd8dc8e5 Fix misspelling of "version" for tower 2024-05-10 10:33:16 -04:00
91812f4695 Fix misspelling of "version" for serde 2024-05-10 10:32:19 -04:00
9b1ea51896 Merge branch '30-add-logging-to-startup-of-backend' into 'main'
Add logging

Closes #30

See merge request libretunes/libretunes!22
2024-05-08 17:56:45 -04:00
6bf08b7507 Add symphonia crate 2024-04-19 09:23:10 -04:00
04e0a66122 Add server_fn crate 2024-04-12 17:04:51 -04:00
6c74220458 Merge branch '22-create-home-page-2' into 'main'
Created initial home page outline

Closes #22

See merge request libretunes/libretunes!20
2024-04-12 16:54:50 -04:00
14a8f83fe6 Removed unused leptos_dom import 2024-04-12 16:43:04 -04:00
a4fb055e84 Fix use of old icons crate 2024-04-12 16:33:33 -04:00
8e44a48b18 Merge remote-tracking branch 'origin/main' into 22-create-home-page-2 2024-04-12 16:23:28 -04:00
f23b62de98 fixed google font api 2024-04-12 13:24:30 -04:00
b6066e2d3e Include ASCII art file in Docker build 2024-04-11 23:42:22 -04:00
241389e5f7 Add logging to main 2024-04-11 23:19:21 -04:00
557c189a17 Add ASCII art of logo and name 2024-04-11 23:19:02 -04:00
4f6f3f90c1 Add flexi_logger crate 2024-04-11 23:14:53 -04:00
7062c75013 Add log crate 2024-04-11 23:06:04 -04:00
eeeae822a5 Merge branch '24-switch-from-actix-to-axum' into 'main'
Switch from Actix to Axum

Closes #24

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

Closes #28

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

Closes #13

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

Closes #25

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

Closes #27

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

View File

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

20
.env.example Normal file
View File

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

View File

@ -0,0 +1,75 @@
name: Push Workflows
on: push
jobs:
build:
runs-on: libretunes-cicd
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Build project
env:
RUSTFLAGS: "-D warnings"
run: cargo-leptos build
docker-build:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- 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-from: type=registry,ref=${{ steps.get-image-name.outputs.IMAGE_NAME }}:${{ gitea.sha }}
cache-to: type=inline
- 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-from: type=registry,ref=${{ steps.get-image-name.outputs.IMAGE_NAME }}:latest
cache-to: type=inline
test:
runs-on: libretunes-cicd
steps:
- name: Checkout repository
uses: actions/checkout@v4
- 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: Run Leptos tests
run: cargo-leptos test
docs:
runs-on: libretunes-cicd
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Generate docs
run: cargo doc --no-deps
- name: Upload docs
uses: actions/upload-artifact@v3
with:
name: docs
path: target/doc

View File

@ -1,78 +0,0 @@
# Build the project
build:
needs: []
image: $CI_REGISTRY/libretunes/ops/docker-leptos:latest
script:
- cargo-leptos build
# Build the docker image and push it to the registry
docker-build:
needs: ["build"]
image: docker:latest
script:
- /usr/local/bin/dockerd-entrypoint.sh &
- while ! docker info; do echo "Waiting for Docker to become available..."; sleep 1; done
- docker login -u $CI_REGISTRY_USER -p $CI_REGISTRY_PASSWORD $CI_REGISTRY
- docker build -t $CI_REGISTRY_IMAGE:$CI_COMMIT_SHORT_SHA .
# If running on the default branch, tag as latest
- if [ "$CI_COMMIT_BRANCH" == "$CI_DEFAULT_BRANCH" ]; then docker tag
$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
.argocd:
image: argoproj/argocd:v2.6.15
before_script:
- argocd login ${ARGOCD_SERVER} --username ${ARGOCD_USERNAME} --password ${ARGOCD_PASSWORD} --grpc-web
# Start the review environment
start-review:
extends: .argocd
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
script:
- argocd app sync argocd/libretunes-review-${CI_COMMIT_SHORT_SHA}
- argocd app wait argocd/libretunes-review-${CI_COMMIT_SHORT_SHA}
environment:
name: review/$CI_COMMIT_SHORT_SHA
url: https://review-$CI_COMMIT_SHORT_SHA.libretunes.mregirouard.com
on_stop: stop-review
# Stop the review environment
stop-review:
needs: ["start-review"]
extends: .argocd
rules:
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
when: manual
allow_failure: true
script:
- argocd app delete argocd/libretunes-review-${CI_COMMIT_SHORT_SHA} --cascade
environment:
name: review/$CI_COMMIT_SHORT_SHA
action: stop

2616
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -8,47 +8,51 @@ build = "src/build.rs"
crate-type = ["cdylib", "rlib"]
[dependencies]
actix-files = { version = "0.6", optional = true }
actix-web = { version = "4", optional = true, features = ["macros"] }
console_error_panic_hook = "0.1"
console_error_panic_hook = { version = "0.1", optional = true }
cfg-if = "1"
http = { version = "0.2", optional = true }
leptos = { version = "0.5", features = ["nightly"] }
leptos_meta = { version = "0.5", features = ["nightly"] }
leptos_actix = { version = "0.5", optional = true }
leptos_router = { version = "0.5", features = ["nightly"] }
wasm-bindgen = "=0.2.89"
leptos_icons = { version = "0.1.0", default_features = false, features = [
"BsPlayFill",
"BsPauseFill",
"BsSkipStartFill",
"BsSkipEndFill",
"RiPlayListMediaFill",
"CgTrash",
"IoReturnUpBackSharp",
"AiEyeFilled",
"AiEyeInvisibleFilled",
"BsThreeDotsVertical",
] }
http = { version = "1.0", default-features = false }
leptos = { version = "0.6", default-features = false, features = ["nightly"] }
leptos_meta = { version = "0.6", features = ["nightly"] }
leptos_axum = { version = "0.6", optional = true }
leptos_router = { version = "0.6", features = ["nightly"] }
wasm-bindgen = { version = "=0.2.93", default-features = false, optional = true }
leptos_icons = { version = "0.3.0" }
icondata = { version = "0.3.0" }
dotenv = { version = "0.15.0", optional = true }
diesel = { version = "2.1.4", features = ["postgres", "r2d2", "time"], optional = true }
diesel = { version = "2.1.4", features = ["postgres", "r2d2", "time"], default-features = false, 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 }
time = { version = "0.3.34", features = ["serde"] }
time = { version = "0.3.34", features = ["serde"], default-features = false }
diesel_migrations = { version = "2.1.0", optional = true }
actix-identity = { version = "0.7.0", optional = true }
actix-session = { version = "0.9.0", features = ["redis-rs-session"], optional = true }
pbkdf2 = { version = "0.12.2", features = ["simple"], optional = true }
futures = { version = "0.3.30", default-features = false, optional = true }
tokio = { version = "1", optional = true, features = ["rt-multi-thread"] }
axum = { version = "0.7.5", features = ["tokio", "http1"], default-features = false, optional = true }
tower = { version = "0.5.1", optional = true, features = ["util"] }
tower-http = { version = "0.6.1", optional = true, features = ["fs"] }
thiserror = "1.0.57"
tower-sessions-redis-store = { version = "0.11", optional = true }
async-trait = { version = "0.1.79", optional = true }
axum-login = { version = "0.14.0", optional = true }
server_fn = { version = "0.6.11", features = ["multipart"] }
symphonia = { version = "0.5.4", default-features = false, features = ["mp3"], optional = true }
multer = { version = "3.0.0", optional = true }
log = { version = "0.4.21", optional = true }
flexi_logger = { version = "0.28.0", optional = true, default-features = false }
web-sys = "0.3.69"
leptos-use = "0.13.5"
image-convert = { version = "0.18.0", optional = true, default-features = false }
[features]
csr = ["leptos/csr", "leptos_meta/csr", "leptos_router/csr"]
hydrate = ["leptos/hydrate", "leptos_meta/hydrate", "leptos_router/hydrate"]
hydrate = [
"leptos/hydrate",
"leptos_meta/hydrate",
"leptos_router/hydrate",
"console_error_panic_hook",
"wasm-bindgen",
]
ssr = [
"dep:actix-files",
"dep:actix-web",
"dep:leptos_actix",
"dep:leptos_axum",
"leptos/ssr",
"leptos_meta/ssr",
"leptos_router/ssr",
@ -57,10 +61,20 @@ ssr = [
"lazy_static",
"openssl",
"diesel_migrations",
"actix-identity",
"actix-session",
"pbkdf2",
"futures",
"tokio",
"axum",
"tower",
"tower-http",
"tower-sessions-redis-store",
"async-trait",
"axum-login",
"symphonia",
"multer",
"log",
"flexi_logger",
"leptos-use/ssr",
"image-convert",
]
# Defines a size-optimized profile for the WASM bundle in release mode

View File

@ -1,22 +1,37 @@
FROM registry.mregirouard.com/libretunes/ops/docker-leptos/musl:latest as builder
FROM rust:slim as builder
WORKDIR /app
RUN rustup default nightly
RUN rustup target add wasm32-unknown-unknown
RUN cargo install cargo-leptos
# Install a few dependencies
RUN set -eux; \
apt-get update; \
apt-get install -y --no-install-recommends \
npm; \
pkg-config \
clang \
build-essential \
libssl-dev \
libpq-dev \
wget; \
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 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
RUN mkdir /app/src && mkdir /app/style && mkdir /app/assets && \
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 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 src /app/src
COPY migrations /app/migrations
COPY style /app/style
# Touch files to force rebuild
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
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
FROM scratch
@ -50,9 +68,15 @@ LABEL description="LibreTunes, an open-source browser audio player and \
library manager built for collaborative listening."
# 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 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
ENV LEPTOS_SITE_ADDR=0.0.0.0:3000
ENV LEPTOS_SITE_ROOT=/site

View File

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

10
ascii_art.txt Normal file
View File

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

View 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

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

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

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

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

View File

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

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

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

View File

@ -13,8 +13,11 @@ services:
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
POSTGRES_DB: ${POSTGRES_DB}
LIBRETUNES_AUDIO_PATH: /assets/audio
LIBRETUNES_IMAGE_PATH: /assets/images
volumes:
- libretunes-audio:/site/audio
- libretunes-audio:/assets/audio
- libretunes-images:/assets/images
depends_on:
- redis
- postgres
@ -50,5 +53,6 @@ services:
volumes:
libretunes-audio:
libretunes-images:
libretunes-redis:
libretunes-postgres:

View File

@ -0,0 +1,2 @@
DROP TABLE song_likes;
DROP TABLE song_dislikes;

View File

@ -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)
);

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,2 @@
DROP INDEX song_history_user_id_idx;
DROP TABLE song_history;

View 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);

View 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;

View 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);

39
src/albumdata.rs Normal file
View File

@ -0,0 +1,39 @@
use crate::models::Artist;
use crate::components::dashboard_tile::DashboardTile;
use time::Date;
/// Holds information about an album
///
/// Intended to be used in the front-end
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<Date>,
/// 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)))
}
}

44
src/api/history.rs Normal file
View File

@ -0,0 +1,44 @@
use std::time::SystemTime;
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<(SystemTime, 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(())
}

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

@ -0,0 +1,3 @@
pub mod history;
pub mod profile;
pub mod songs;

49
src/api/profile.rs Normal file
View File

@ -0,0 +1,49 @@
use leptos::*;
use server_fn::codec::{MultipartData, MultipartFormData};
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
use crate::auth::get_user;
use server_fn::error::NoCustomError;
}
}
/// 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(())
}

55
src/api/songs.rs Normal file
View 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))
}

View File

@ -1,32 +1,48 @@
use crate::playbar::PlayBar;
use crate::playbar::CustomTitle;
use crate::playstatus::PlayStatus;
use crate::queue::Queue;
use crate::searchbar::SearchBar;
use leptos::*;
use leptos_meta::*;
use leptos_router::*;
use crate::pages::login::*;
use crate::pages::signup::*;
use crate::error_template::{AppError, ErrorTemplate};
#[component]
pub fn App() -> impl IntoView {
// Provides context that manages stylesheets, titles, meta tags, etc.
provide_meta_context();
let play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status);
let upload_open = create_rw_signal(false);
view! {
// injects a stylesheet into the document <head>
// id=leptos means cargo-leptos will hot-reload this stylesheet
<Stylesheet id="leptos" href="/pkg/libretunes.css"/>
// sets the document title
<Title text="LibreTunes"/>
<CustomTitle play_status=play_status/>
// content for this welcome page
<Router>
<Router fallback=|| {
let mut outside_errors = Errors::default();
outside_errors.insert_with_default_key(AppError::NotFound);
view! {
<ErrorTemplate outside_errors/>
}
.into_view()
}>
<main>
<Routes>
<Route path="" view=HomePage/>
<Route path="/*any" view=NotFound/>
<Route path="" view=move || view! { <HomePage play_status=play_status upload_open=upload_open/> }>
<Route path="" view=Dashboard />
<Route path="dashboard" view=Dashboard />
<Route path="search" view=Search />
</Route>
<Route path="/login" view=Login />
<Route path="/signup" view=Signup />
</Routes>
@ -35,18 +51,25 @@ pub fn App() -> impl IntoView {
}
}
use crate::components::sidebar::*;
use crate::components::dashboard::*;
use crate::components::search::*;
use crate::components::personal::*;
use crate::components::upload::*;
/// Renders the home page of your application.
#[component]
fn HomePage() -> impl IntoView {
let mut play_status = PlayStatus::default();
let play_status = create_rw_signal(play_status);
fn HomePage(play_status: RwSignal<PlayStatus>, upload_open: RwSignal<bool>) -> impl IntoView {
view! {
<div class="home">
<PlayBar status=play_status/>
<Queue status=play_status/>
<SearchBar status=play_status/>
</div>
<div class="home-container">
<Upload open=upload_open/>
<Sidebar upload_open=upload_open/>
// This <Outlet /> will render the child route components
<Outlet />
<Personal />
<PlayBar status=play_status/>
<Queue status=play_status/>
</div>
}
}
@ -63,8 +86,8 @@ fn NotFound() -> impl IntoView {
{
// this can be done inline because it's synchronous
// if it were async, we'd use a server function
let resp = expect_context::<leptos_actix::ResponseOptions>();
resp.set_status(actix_web::http::StatusCode::NOT_FOUND);
let resp = expect_context::<leptos_axum::ResponseOptions>();
resp.set_status(axum::http::StatusCode::NOT_FOUND);
}
view! {

32
src/artistdata.rs Normal file
View File

@ -0,0 +1,32 @@
use crate::components::dashboard_tile::DashboardTile;
/// Holds information about an artist
///
/// Intended to be used in the front-end
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())
}
}

View File

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

48
src/auth_backend.rs Normal file
View File

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

8
src/components.rs Normal file
View File

@ -0,0 +1,8 @@
pub mod sidebar;
pub mod dashboard;
pub mod search;
pub mod personal;
pub mod dashboard_tile;
pub mod dashboard_row;
pub mod upload;
pub mod song_list;

View File

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

View File

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

View 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()
}
}

View File

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

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

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

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

@ -0,0 +1,54 @@
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use crate::components::upload::*;
#[component]
pub fn Sidebar(upload_open: RwSignal<bool>) -> impl IntoView {
use leptos_router::use_location;
let location = use_location();
let on_dashboard = Signal::derive(
move || location.pathname.get().starts_with("/dashboard") || location.pathname.get() == "/",
);
let on_search = Signal::derive(
move || location.pathname.get().starts_with("/search"),
);
view! {
<div class="sidebar-container">
<div class="sidebar-top-container">
<h2 class="header">LibreTunes</h2>
<UploadBtn dialog_open=upload_open />
<a class="buttons" href="/dashboard" style={move || if on_dashboard() {"color: #e1e3e1"} else {""}} >
<Icon icon=icondata::OcHomeFillLg />
<h1>Dashboard</h1>
</a>
<a class="buttons" href="/search" style={move || if on_search() {"color: #e1e3e1"} else {""}}>
<Icon icon=icondata::BiSearchRegular />
<h1>Search</h1>
</a>
</div>
<Bottom />
</div>
}
}
#[component]
pub fn Bottom() -> impl IntoView {
view! {
<div class="sidebar-bottom-container">
<div class="heading">
<h1 class="header">Playlists</h1>
<button class="add-playlist">
<div class="add-sign">
<Icon icon=icondata::IoAddSharp />
</div>
New Playlist
</button>
</div>
</div>
}
}

157
src/components/song_list.rs Normal file
View File

@ -0,0 +1,157 @@
use leptos::*;
use leptos_icons::*;
use crate::songdata::SongData;
use crate::models::{Album, Artist};
const LIKE_DISLIKE_BTN_SIZE: &str = "2em";
#[component]
pub fn SongList(songs: MaybeSignal<Vec<SongData>>) -> impl IntoView {
view! {
<table class="song-list">
{
songs.with(|songs| {
let mut first_song = true;
songs.iter().map(|song| {
let playing = first_song.into();
first_song = false;
view! {
<SongListItem song={song.clone()} song_playing=playing />
}
}).collect::<Vec<_>>()
})
}
</table>
}
}
#[component]
pub fn SongListItem(song: SongData, song_playing: MaybeSignal<bool>) -> impl IntoView {
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 /></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 liked disliked/></td>
<td>{format!("{}:{:02}", song.duration / 60, song.duration % 60)}</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>) -> impl IntoView {
view! {
<img class="song-image" src={image_path}/>
{if song_playing.get() {
view! { <Icon class="song-image-overlay song-playing-overlay" icon=icondata::BsPauseFill /> }.into_view()
} else {
view! { <Icon class="song-image-overlay hide-until-hover" icon=icondata::BsPlayFill /> }.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(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"))
}
});
let toggle_like = move |_| {
liked.set(!liked.get_untracked());
disliked.set(disliked.get_untracked() && !liked.get_untracked());
};
let toggle_dislike = move |_| {
disliked.set(!disliked.get_untracked());
liked.set(liked.get_untracked() && !disliked.get_untracked());
};
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
View 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>
}
}

View File

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

73
src/error_template.rs Normal file
View File

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

70
src/fileserv.rs Normal file
View File

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

View File

@ -1,6 +1,8 @@
pub mod app;
pub mod auth;
pub mod songdata;
pub mod albumdata;
pub mod artistdata;
pub mod playstatus;
pub mod playbar;
pub mod database;
@ -8,13 +10,20 @@ pub mod queue;
pub mod song;
pub mod models;
pub mod pages;
pub mod components;
pub mod users;
pub mod search;
pub mod searchbar;
pub mod fileserv;
pub mod error_template;
pub mod api;
pub mod upload;
pub mod util;
use cfg_if::cfg_if;
cfg_if! {
if #[cfg(feature = "ssr")] {
if #[cfg(feature = "ssr")] {
pub mod auth_backend;
pub mod schema;
}
}
@ -27,7 +36,6 @@ if #[cfg(feature = "hydrate")] {
#[wasm_bindgen]
pub fn hydrate() {
use app::*;
use leptos::*;
console_error_panic_hook::set_once();

View File

@ -1,10 +1,10 @@
// Needed for building in Docker container
// See https://github.com/clux/muslrust?tab=readme-ov-file#diesel-and-pq-builds
// See https://github.com/sgrif/pq-sys/issues/25
#[cfg(target = "x86_64-unknown-linux-musl")]
#[cfg(target_env = "musl")]
extern crate openssl;
#[cfg(target = "x86_64-unknown-linux-musl")]
#[cfg(target_env = "musl")]
#[macro_use]
extern crate diesel;
@ -12,93 +12,71 @@ extern crate diesel;
extern crate diesel_migrations;
#[cfg(feature = "ssr")]
#[actix_web::main]
async fn main() -> std::io::Result<()> {
use actix_identity::IdentityMiddleware;
use actix_session::storage::RedisSessionStore;
use actix_session::SessionMiddleware;
use actix_web::cookie::Key;
#[tokio::main]
async fn main() {
use axum::{routing::get, Router, extract::Path};
use leptos::*;
use leptos_axum::{generate_route_list, LeptosRoutes};
use libretunes::app::*;
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 axum_login::AuthManagerLayerBuilder;
use libretunes::auth_backend::AuthBackend;
use log::*;
flexi_logger::Logger::try_with_env_or_str("debug").unwrap().format(flexi_logger::opt_format).start().unwrap();
info!("\n{}", include_str!("../ascii_art.txt"));
info!("Starting Leptos server...");
use dotenv::dotenv;
dotenv().ok();
debug!("Running database migrations...");
// Bring the database up to date
libretunes::database::migrate();
let session_secret_key = if let Ok(key) = std::env::var("SESSION_SECRET_KEY") {
Key::from(key.as_bytes())
} else {
Key::generate()
};
debug!("Connecting to Redis...");
let redis_url = std::env::var("REDIS_URL").expect("REDIS_URL must be set");
let redis_store = RedisSessionStore::new(redis_url).await.unwrap();
let redis_config = RedisConfig::from_url(&redis_url).expect(&format!("Unable to parse Redis URL: {}", redis_url));
let redis_pool = RedisPool::new(redis_config, None, None, None, 1).expect("Unable to create Redis pool");
redis_pool.connect();
redis_pool.wait_for_connect().await.expect("Unable to connect to Redis");
use actix_files::Files;
use actix_web::*;
use leptos::*;
use leptos_actix::{generate_route_list, LeptosRoutes};
use libretunes::app::*;
let session_store = RedisStore::new(redis_pool);
let session_layer = SessionManagerLayer::new(session_store);
let auth_backend = AuthBackend;
let auth_layer = AuthManagerLayerBuilder::new(auth_backend, session_layer).build();
let conf = get_configuration(None).await.unwrap();
let addr = conf.leptos_options.site_addr;
let leptos_options = conf.leptos_options;
let addr = leptos_options.site_addr;
// Generate the list of routes in your Leptos App
let routes = generate_route_list(App);
println!("listening on http://{}", &addr);
HttpServer::new(move || {
let leptos_options = &conf.leptos_options;
let site_root = &leptos_options.site_root;
let app = Router::new()
.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, "")))
.layer(auth_layer)
.fallback(file_and_error_handler)
.with_state(leptos_options);
App::new()
.route("/api/{tail:.*}", leptos_actix::handle_server_fns())
// serve JS/WASM/CSS from `pkg`
.service(Files::new("/pkg", format!("{site_root}/pkg")))
// serve other assets from the `assets` directory
.service(Files::new("/assets", site_root))
// serve the favicon from /favicon.ico
.service(favicon)
.leptos_routes(leptos_options.to_owned(), routes.to_owned(), App)
.app_data(web::Data::new(leptos_options.to_owned()))
.wrap(IdentityMiddleware::default())
.wrap(SessionMiddleware::new(redis_store.clone(), session_secret_key.clone()))
//.wrap(middleware::Compress::default())
})
.bind(&addr)?
.run()
.await
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");
}
#[cfg(feature = "ssr")]
#[actix_web::get("favicon.ico")]
async fn favicon(
leptos_options: actix_web::web::Data<leptos::LeptosOptions>,
) -> actix_web::Result<actix_files::NamedFile> {
let leptos_options = leptos_options.into_inner();
let site_root = &leptos_options.site_root;
Ok(actix_files::NamedFile::open(format!(
"{site_root}/favicon.ico"
))?)
}
#[cfg(not(any(feature = "ssr", feature = "csr")))]
#[cfg(not(feature = "ssr"))]
pub fn main() {
// no client-side main function
// unless we want this to work with e.g., Trunk for pure client-side testing
// see lib.rs for hydration function instead
// see optional feature `csr` instead
}
#[cfg(all(not(feature = "ssr"), feature = "csr"))]
pub fn main() {
// a client-side main function is required for using `trunk serve`
// prefer using `cargo leptos serve` instead
// to run: `trunk serve --open --features csr`
use leptos::*;
use libretunes::app::*;
use wasm_bindgen::prelude::wasm_bindgen;
console_error_panic_hook::set_once();
leptos::mount_to_body(App);
}

View File

@ -1,5 +1,4 @@
use std::time::SystemTime;
use std::error::Error;
use time::Date;
use serde::{Deserialize, Serialize};
@ -9,6 +8,7 @@ cfg_if! {
if #[cfg(feature = "ssr")] {
use diesel::prelude::*;
use crate::database::PgPooledConn;
use std::error::Error;
}
}
@ -41,13 +41,284 @@ pub struct User {
/// The time the user was created
#[cfg_attr(feature = "ssr", diesel(deserialize_as = SystemTime))]
pub created_at: Option<SystemTime>,
/// 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<(SystemTime, 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
#[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(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Artist {
/// A unique id for the artist
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
@ -162,13 +433,33 @@ impl Artist {
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
#[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(check_for_backend(diesel::pg::Pg)))]
#[derive(Serialize, Deserialize)]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct Album {
/// A unique id for the album
#[cfg_attr(feature = "ssr", diesel(deserialize_as = i32))]
@ -177,6 +468,8 @@ pub struct Album {
pub title: String,
/// The album's release date
pub release_date: Option<Date>,
/// The path to the album's image file
pub image_path: Option<String>,
}
impl Album {
@ -289,4 +582,47 @@ impl Song {
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: SystemTime,
/// The id of the song that was listened to
pub song_id: i32,
}

View File

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

View File

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

View File

@ -1,13 +1,14 @@
use std::time::Duration;
use crate::models::Artist;
use crate::playstatus::PlayStatus;
use crate::songdata::SongData;
use crate::api::songs;
use leptos::ev::MouseEvent;
use leptos::html::{Audio, Div};
use leptos::leptos_dom::*;
use leptos_meta::Title;
use leptos::*;
use leptos_icons::BsIcon::*;
use leptos_icons::RiIcon::*;
use leptos_icons::*;
use leptos_use::{utils::Pausable, use_interval_fn};
/// Width and height of the forward/backward skip buttons
const SKIP_BTN_SIZE: &str = "3.5em";
@ -23,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
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
/// Get the current time and duration of the current song, if available
@ -195,9 +199,9 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
let icon = Signal::derive(move || {
status.with(|status| {
if status.playing {
Icon::from(BsPauseFill)
icondata::BsPauseFill
} else {
Icon::from(BsPlayFill)
icondata::BsPlayFill
}
})
});
@ -206,7 +210,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
<div class="playcontrols" align="center">
<button on:click=skip_back on:mousedown=prevent_focus>
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=Icon::from(BsSkipStartFill) />
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=icondata::BsSkipStartFill />
</button>
<button on:click=toggle_play on:mousedown=prevent_focus>
@ -214,7 +218,7 @@ fn PlayControls(status: RwSignal<PlayStatus>) -> impl IntoView {
</button>
<button on:click=skip_forward on:mousedown=prevent_focus>
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=Icon::from(BsSkipEndFill) />
<Icon class="controlbtn" width=SKIP_BTN_SIZE height=SKIP_BTN_SIZE icon=icondata::BsSkipEndFill />
</button>
</div>
@ -247,37 +251,149 @@ fn PlayDuration(elapsed_secs: MaybeSignal<i64>, total_secs: MaybeSignal<i64>) ->
fn MediaInfo(status: RwSignal<PlayStatus>) -> impl IntoView {
let name = Signal::derive(move || {
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 || {
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 || {
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 || {
status.with(|status| {
// TODO Use some default / unknown image?
status.queue.front().map_or("".into(), |song| song.image_path.clone())
status.queue.front().map_or("/images/placeholders/MusicPlaceholder.svg".into(),
|song| song.image_path.clone())
})
});
view! {
<div class="media-info">
<img class="media-info-img" align="left" src={image}/>
<div class="media-info-text">
{name}
<br/>
{artist} - {album}
</div>
}
}
/// The like and dislike buttons
#[component]
fn LikeDislike(status: RwSignal<PlayStatus>) -> impl IntoView {
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>
}
}
@ -339,18 +455,33 @@ fn QueueToggle(status: RwSignal<PlayStatus>) -> impl IntoView {
view! {
<div class="queue-toggle">
<button on:click=update_queue on:mousedown=prevent_focus>
<Icon class="controlbtn" width=QUEUE_BTN_SIZE height=QUEUE_BTN_SIZE icon=Icon::from(RiPlayListMediaFill) />
<Icon class="controlbtn" width=QUEUE_BTN_SIZE height=QUEUE_BTN_SIZE icon=icondata::RiPlayListMediaFill />
</button>
</div>
}
}
/// Renders the title of the page based on the currently playing song
#[component]
pub fn CustomTitle(play_status: RwSignal<PlayStatus>) -> impl IntoView {
let title = create_memo(move |_| {
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
#[component]
pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// Listen for key down events -- arrow keys don't seem to trigger key press events
let _arrow_key_handle = window_event_listener(ev::keydown, move |e: ev::KeyboardEvent| {
if e.key() == "ArrowRight" && status.with_untracked(|status| status.search_active) == false {
if e.key() == "ArrowRight" {
e.prevent_default();
log!("Right arrow key pressed, skipping forward by {} seconds", ARROW_KEY_SKIP_TIME);
@ -363,7 +494,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
error!("Unable to skip forward: Unable to get current duration");
}
} else if e.key() == "ArrowLeft" && status.with_untracked(|status| status.search_active) == false {
} else if e.key() == "ArrowLeft" {
e.prevent_default();
log!("Left arrow key pressed, skipping backward by {} seconds", ARROW_KEY_SKIP_TIME);
@ -380,7 +511,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
// Listen for space bar presses to play/pause
let _space_bar_handle = window_event_listener(ev::keypress, move |e: ev::KeyboardEvent| {
if e.key() == " " && status.with_untracked(|status| status.search_active) == false {
if e.key() == " " {
e.prevent_default();
log!("Space bar pressed, toggling play/pause");
@ -404,7 +535,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
status.with_untracked(|status| {
// Start playing the first song in the queue, if available
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
// here because we already have access to the audio element
@ -421,6 +552,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 |_| {
log!("Audio playing");
status.update(|status| status.playing = true);
@ -429,6 +593,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
let on_pause = move |_| {
log!("Audio paused");
status.update(|status| status.playing = false);
pause_hist_timeout();
};
let on_time_update = move |_| {
@ -446,6 +611,11 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
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 |_| {
@ -457,7 +627,7 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
let prev_song = status.queue.pop_front();
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);
} else {
log!("Queue empty, no previous song to add to history");
@ -490,7 +660,10 @@ pub fn PlayBar(status: RwSignal<PlayStatus>) -> impl IntoView {
on:timeupdate=on_time_update on:ended=on_end type="audio/mpeg" />
<div class="playbar">
<ProgressBar percentage=percentage.into() status=status />
<div class="playbar-left-group">
<MediaInfo status=status />
<LikeDislike status=status />
</div>
<PlayControls status=status />
<PlayDuration elapsed_secs=elapsed_secs.into() total_secs=total_secs.into() />
<QueueToggle status=status />

View File

@ -11,8 +11,6 @@ pub struct PlayStatus {
pub playing: bool,
/// Whether or not the queue is open
pub queue_open: bool,
/// Whether or not the search bar is active (useful for knowing when spacebar to play/pause, etc should be disabled)
pub search_active: bool,
/// A reference to the HTML audio element
pub audio_player: Option<NodeRef<Audio>>,
/// A queue of songs that have been played, ordered from oldest to newest
@ -58,7 +56,6 @@ impl Default for PlayStatus {
Self {
playing: false,
queue_open: false,
search_active: false,
audio_player: None,
history: VecDeque::new(),
queue: VecDeque::new(),

View File

@ -1,10 +1,10 @@
use crate::models::Artist;
use crate::playstatus::PlayStatus;
use crate::song::Song;
use leptos::ev::MouseEvent;
use leptos::leptos_dom::*;
use leptos::*;
use leptos_icons::*;
use leptos_icons::CgIcon::*;
use leptos::ev::DragEvent;
const RM_BTN_SIZE: &str = "2.5rem";
@ -99,14 +99,14 @@ pub fn Queue(status: RwSignal<PlayStatus>) -> impl IntoView {
on:dragenter=move |e: DragEvent| on_drag_enter(e, index)
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
when=move || index != 0
fallback=|| view!{
<p>Playing</p>
}>
<button on:click=move |_| remove_song(index) on:mousedown=prevent_focus>
<Icon class="remove-song" width=RM_BTN_SIZE height=RM_BTN_SIZE icon=Icon::from(CgTrash) />
<Icon class="remove-song" width=RM_BTN_SIZE height=RM_BTN_SIZE icon=icondata::CgTrash />
</button>
</Show>
</div>

View File

@ -12,6 +12,7 @@ diesel::table! {
id -> Int4,
title -> Varchar,
release_date -> Nullable<Date>,
image_path -> Nullable<Varchar>,
}
}
@ -22,6 +23,22 @@ 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! {
song_artists (song_id, artist_id) {
song_id -> Int4,
@ -29,6 +46,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! {
songs (id) {
id -> Int4,
@ -49,6 +89,7 @@ diesel::table! {
email -> Varchar,
password -> Varchar,
created_at -> Timestamp,
admin -> Bool,
}
}
@ -56,13 +97,24 @@ diesel::joinable!(album_artists -> albums (album_id));
diesel::joinable!(album_artists -> artists (artist_id));
diesel::joinable!(song_artists -> artists (artist_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::allow_tables_to_appear_in_same_query!(
album_artists,
albums,
artists,
friend_requests,
friendships,
song_artists,
song_dislikes,
song_history,
song_likes,
songs,
users,
);

View File

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

View File

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

View File

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

View File

@ -1,16 +1,81 @@
use crate::models::{Album, Artist, Song};
use crate::components::dashboard_tile::DashboardTile;
use time::Date;
/// 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(Clone)]
pub struct SongData {
/// Song id
pub id: i32,
/// Song name
pub name: String,
/// Song artist
pub artist: String,
pub title: String,
/// Song artists
pub artists: Vec<Artist>,
/// 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<Date>,
/// Path to song file, relative to the root of the web server.
/// For example, `"/assets/audio/Song.mp3"`
pub song_path: String,
/// Path to song image, relative to the root of the web server.
/// For example, `"/assets/images/Song.jpg"`
pub image_path: String,
/// 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)))
}
}

294
src/upload.rs Normal file
View File

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

View File

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

37
src/util/audio.rs Normal file
View 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))
}

7
src/util/mod.rs Normal file
View File

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

10
style/dashboard.scss Normal file
View File

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

45
style/dashboard_row.scss Normal file
View 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
View 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;
}

16
style/home.scss Normal file
View File

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

View File

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

74
style/personal.scss Normal file
View File

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

View File

@ -39,15 +39,12 @@
}
}
.media-info {
font-size: 16;
margin-left: 10px;
.playbar-left-group {
display: flex;
position: absolute;
top: 50%;
transform: translateY(-50%);
display: grid;
grid-template-columns: 50px 1fr;
margin-left: 10px;
.media-info-img {
width: 50px;
@ -57,6 +54,10 @@
text-align: left;
margin-left: 10px;
}
.like-dislike {
margin-left: 20px;
}
}
.playcontrols {
@ -64,23 +65,6 @@
flex-direction: row;
justify-content: 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 {
@ -94,22 +78,30 @@
bottom: 13px;
top: 13px;
right: 90px;
}
button {
.controlbtn {
color: $text-controls-color;
}
.controlbtn:hover {
color: $controls-hover-color;
}
.controlbtn:active {
color: $controls-click-color;
}
background-color: transparent;
border: transparent;
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 {
color: $text-controls-color;
}
.controlbtn:hover {
color: $controls-hover-color;
}
.controlbtn:active {
color: $controls-click-color;
}
background-color: transparent;
border: transparent;
}
}

View File

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

6
style/search.scss Normal file
View File

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

View File

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

116
style/sidebar.scss Normal file
View File

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

View File

@ -1,22 +0,0 @@
.song {
display: flex;
align-items: center;
img {
max-width: 50px; /* Adjust maximum width for images */
margin-right: 10px; /* Add spacing between image and text */
border-radius: 5px; /* Add border radius to image */
}
.song-info {
h3 {
margin: 0;
color: #fff; /* Adjust text color for song */
}
p {
margin: 0;
color: #aaa; /* Adjust text color for artist */
}
}
}

124
style/song_list.scss Normal file
View 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);
}
}
}
}

View File

@ -1,3 +1,7 @@
@import url('https://fonts.googleapis.com/css2?family=Open+Sans:ital,wght@0,300..800;1,300..800&display=swap');
$standard-font: 'Open Sans', sans-serif;
$background-color: #030303;
$accent-color: #4032a8;
$text-controls-color: #e0e0e0;
@ -7,12 +11,8 @@ $play-bar-background-color: #212121;
$play-grad-start: #0a0533;
$play-grad-end: $accent-color;
$queue-background-color: $play-bar-background-color;
$search-background-color: $play-bar-background-color;
$search-bar-input-background-color: gray;
$search-bar-input-color: black;
$search-highlight-color: #333;
$search-item-type-color: #666;
$search-options-color: #666;
$auth-inputs: #796dd4;
$auth-containers: white;
$dashboard-tile-size: 200px;

188
style/upload.scss Normal file
View 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;
}
}
}