Compare commits

...

122 Commits

Author SHA1 Message Date
phoenix 50d0ea630f Update rust (#250)
* bump: rust Cargo.toml

* bump: rust docker

* bump: rust ci

* bump: axum

* bump: axum-extra

* bump: tokio

* bump: tower-http

* bump: uuid

* bump: utoipa

* bump: icarus_meta

* bump: icarus_models

* bump: icarus_envy

* bump: icarus

* Updated base image in dockerfile

* Adding sample local env file

* Fixing postgresql volume issue in docker
2026-05-22 11:29:38 -04:00
phoenix d273c801bf Update rust (#249)
* Updated rust version

* Updated rust in workflow

* Updating rust version in docker file

* Updating postgresql

* Updated crates

* cargo update

* Updated readme

* Version bump

* Warning fix
2026-04-05 18:13:49 -04:00
KD bcd960d9a1 tsk-245: Modify result when getting songs but no songs are present (#247)
* tsk-245: Modify result when getting songs but no songs are present

* tsk-245: Fixed endpoint indicating success when no content is found

* tsk-245: Version bump
2025-11-07 11:48:07 -05:00
KD dbbbf02acf tsk-244: Remove code causing migrations to be ran twice (#246)
* tsk-244: Remove code causing migrations to be ran twice

* tsk-244: Cleanup

* tsk-244: Version bump
2025-11-06 12:56:47 -05:00
KD 01b34c9848 tsk-230: Using UserClaims from icarus_models (#243)
* tsk-230: Using UserClaims from icarus_models

* tsk-230: Cleanup

* tsk-230: Version bump
2025-11-05 09:59:13 -05:00
KD 1b9bd4359c tsk-207: Move code elsewhere that is found in src/main.rs (#242)
* tsk-207: Move code elsewhere that is found in src/main.rs

* tsk-207: Some refactoring

* tsk-207: Moving file around

* tsk-207: Code formatting

* tsk-207: Version bump

* tsk-207: Test fix
2025-11-04 11:19:12 -05:00
KD d05502dd8e tsk-227: Change statement when evaluating multipart form when queueing song (#241)
* tsk-227: Change statement when evaluating multipart form when queueing song

* tsk-227: Version bump
2025-11-04 10:47:51 -05:00
KD 147a50c867 tsk-196: Moving SongQueue struct (#240)
* tsk-196: Moving SongQueue struct

* tsk-196: Code formatting

* tsk-196: Version bump
2025-11-03 13:56:18 -05:00
KD a80e21b918 tsk-204: Changing name of test payload function (#239)
* tsk-204: Changing name of test payload function

* tsk-204: Added more test payload functions

* tsk-204: Version bump
2025-11-03 13:41:56 -05:00
KD 731aae5240 tsk-206: Moving request functions to their own module in testing (#238)
* tsk-206: Moving request functions to their own module in testing

* tsk-206: Version bump

* tsk-206: Forgot some imports. Some cleanup

* tsk-206: Forgot some imports

* tsk-206: How did I miss these?

* tsk-206: Code formatting
2025-11-02 21:30:40 -05:00
KD 79e909bfc0 tsk-86: Postgresql version bump 18.0 (#237)
* tsk-86: Postgresql version bump 18.0

* tsk-186: Updated exposed port on docker

* tsk-186: cargo update

* tsk-186: Version bump
2025-11-02 17:03:14 -05:00
KD 7940527418 tsk-208: Moving config and endpoint code (#236)
* tsk-208: Moving config and endpoint code

* tsk-208: Code formatting

* tsk-208: Version bump

* tsk-208: Accidentally changed port
2025-11-01 14:57:40 -04:00
KD f859eaf0a2 tsk-205: Put functions within a util module (#235)
* tsk-205: Put functions within a util module

* tsk-205: Code formatting

* tsk-205: Version bump

* tsk-205: Code cleanup
2025-11-01 14:32:53 -04:00
KD 22080a2f29 tsk-201: Making content disposition more unique (#234)
* tsk-201: Making content disposition more unique

* tsk-201: Cleanup

* tsk-201: Version bump
2025-10-31 12:34:43 -04:00
KD c630cb84b5 tsk-200: Utilizing mime for Content type for fetching queued CoverArt data (#233)
* tsk-200: Utilizing mime for Content type for fetching queued CoverArt data

* tsk-200: Cleanup

* tsk-200: Version bump
2025-10-31 12:20:11 -04:00
KD ca38465f2d tsk-202: Make CoverArt filename random during creation (#232)
* tsk-202: Make downloaded CoverArt filename random

* tsk-202: Cleanup

* tsk-202: Version bump

* tsk-202: Version bump down
2025-10-30 16:48:26 -04:00
KD fd4e661b3c tsk-224: Save file_type to CoverArt (#231)
* tsk-224: Save file_type to CoverArt

* tsk-224: Updated migrations

* tsk-224: Code formatting

* tsk-224: Fix test

* tsk-224: Test fix

* tsk-224: Version bump

* tsk-224: Warning fix
2025-10-30 16:25:59 -04:00
KD 6995ed483c icarus_models version bump (#229)
* icarus_models version bump

* Fix test

* Build fixes

* Version bump

* Using standard version
2025-10-30 15:35:02 -04:00
KD 2cc5e99590 tsk-192: jsonwebtoken version bump (#228)
* tsk-192: jsonwebtoken version bump

* tsk-192: Added feature to jsonwebtoken

* tsk-192: Code cleanup

* tsk-192: cargo update

* tsk-192: Version bump
2025-10-29 16:40:17 -04:00
KD 09d7fa32c8 tsk-179: Modify status code of song queue endpoint (#226)
* tsk-179: Updating docs for endpoint status codes

* tsk-179: Updated status code

* tsk-179: Improved error handling

* tsk-179: Code formatting

* tsk-179: Version bump
2025-10-29 15:20:04 -04:00
KD 27ef175828 tsk-213: Identify audio file type in initial step when queueing (#225)
* tsk-213: Adding song check when queueing songs

* tsk-213: Added check for updating queued song

* tsk-213: Removed todo

* tsk-213: Code cleanup

* tsk-213: Warning fix

* tsk-213: Version bump

* tsk-213: Minor status code changes
2025-10-29 14:58:34 -04:00
KD 1871ebe40b tsk-203: Addressing hard coding when downloading coverart (#223)
* tsk-203: Addressing hard coding when downloading coverart

* tsk-203: Code formatting

* tsk-203: Version bump

* tsk-203: Make downloaded coverart file random

* tsk-203: Code formatting
2025-10-27 14:16:04 -04:00
KD 1a5a9fcaaf tsk-194: Make distinction in MetadataQueue endpoints (#222)
* tsk-194: Moving metadata module

* tsk-194: Build fix

* tsk-194: Name changes

* tsk-194: Code formatting

* tsk-194: Version bump

* tsk-194: Test fixes
2025-10-27 13:25:30 -04:00
KD 8b36bc8c49 tsk-218: Separate Song and SongQueue in the endpoints (#221)
* tsk-218: Added empty file

* tsk-218: Created song module in queue module

* tsk-218: Code formatting

* tsk-218: Version bump

* tsk-218: Cleanup

* tsk-218: Test fixes
2025-10-26 17:48:17 -04:00
KD 003e5b77c1 tsk-197: Rename download_flac() function (#220)
* tsk-197: Renamed function

* tsk-197: Version bump

* tsk-197: icarus_models version bump
2025-10-25 21:34:33 -04:00
KD 02d9ef013e tsk-199: Separate CoverArt queue endpoints (#219)
* tsk-199: Created queue module for queue endpoints

* tsk-199: Code formatting

* tsk-199: Test fixes

* tsk-199: Version bump

* tsk-199: Updated readme
2025-10-25 21:17:40 -04:00
KD 351b4acb1c tsk-211: Fix SQL error when checking queue (#217)
* tsk-211: Fixing error on getting queue item

* tsk-211: Some cleanup

* tsk-211: Cleanup

* tsk-211: Updated readme

* tsk-211: Version bump
2025-10-22 21:42:19 -04:00
KD 381dd49b56 tsk-209: Create repo module (#216)
* tsk-209: Refactored repo code

* tsk-209: Refactoring more code

* tsk-209: Code formatting

* tsk-209: Refactored metadata repo code

* tsk-209: Refactored the other code

* tsk-209: Code formatting

* tsk-209: Version bump

* tsk-209: Fix test
2025-10-22 20:37:15 -04:00
KD a9ba1c5193 tsk-212: Post fixes (#215)
* tsk-212: icarus_meta version bump

* tsk-212: icarus_meta version bump

* tsk-212: Got functionality working

* tsk-212: Migration changes

Added file_type to CoverArtQueue

* tsk-212: Add support to save file_type from CoverArtQueue

* tsk-212: Warning fix

* tsk-212: Version bump

* tsk-212: icarus_meta version bump

* tsk-212: icarus_meta version bump

* tsk-212: icarus_meta related changes

* tsk-212: Replaced code with constants

* tsk-212: icarus_meta version bump
2025-10-21 22:42:32 -04:00
KD fb360c8269 tsk-212: Identify type of CoverArt (#214)
* tsk-212: icarus_meta version bump

* tsk-212: icarus_meta version bump

* tsk-212: Got functionality working

* tsk-212: Migration changes

Added file_type to CoverArtQueue

* tsk-212: Add support to save file_type from CoverArtQueue

* tsk-212: Warning fix

* tsk-212: Version bump

* tsk-212: icarus_meta version bump

* tsk-212: icarus_meta version bump

* tsk-212: icarus_meta related changes

* tsk-212: Replaced code with constants
2025-10-21 22:24:52 -04:00
KD e461e78661 icarus_models version bump (#210)
* icarus_models version bump

* icarus_models related changes

* Code formatting

* Test changeS:

* Test changes

* Migration changes

* Migration changes

* Warning fix

* Cleanup

* Updated readme

* Removed line from migrations

* Code cleanup

* Version bump

* cargo update

* icarus_models version bump
2025-10-20 11:19:06 -04:00
KD 2023fc81f8 Version fix (#193)
* Version fix

* Workflow fix

* Test fix

* Test fix

* Removing code that was meant to be removed

Caused an extra file to be created when the request is called

* Updated env sample to address workflow

* Removed import

* env fix

* Version change

* Version bump

Going with the version I done earlier. I won't have the versioning match the api version in the endpoints

* Fixing versions for app dependencies
2025-10-14 22:02:26 -04:00
KD 48a40a4821 tsk-182: Update rust version (#191)
* Updated rust version

* Warning fix

* Updating crates and dependencies

* Version bump

* tsk-182: cargo update

* Updated jsonwebtoken
2025-10-12 18:23:56 -04:00
KD 8bf99be22c icarus_models version bump (#190)
* icarus_models version bump

* icarus_models changes

* Code refactoring

* Changes

* Version bump

* Fixed todo
2025-10-11 19:50:56 -04:00
KD 8c12c8c761 icarus_envy version bump (#189)
* icarus_envy version bump

* icarus_envy related changes

* Code formatting

* Code cleanup

* Version bump
2025-10-10 19:04:01 -04:00
KD caaec248db CORS support (#183)
* Changes to same .env file

* Updated sample env files

* icarus_envy version bump

* Adding CORS

* Added other urls

* Code formatting

* Changed allowed urls

* Modified docker compose. Port changes

* Changed port

* Cleanup

* Version bump
2025-10-10 16:33:15 -04:00
KD 309d76785a Language change (#185)
* Adding skeleton file

* Adding content

* Still having issues with the language

* Some changes

* Ignoring .NET related files
2025-10-01 09:55:04 -04:00
KD c83a37c20a Change language of project (#184)
* Adding skeleton file

* Adding content
2025-10-01 09:48:02 -04:00
KD 032801b903 Merge pull request #153 from kdeng00/v0.2
v0.2 release
2025-08-30 13:34:06 -04:00
kdeng00 b844f06e82 Added license 2025-08-30 13:30:34 -04:00
kdeng00 517a01d60c Version bump 2025-08-30 13:28:37 -04:00
KD 1ae2f88beb tsk-171: Updated Readme (#181) 2025-08-29 22:14:03 -04:00
KD 805df87f5b tsk-170: API documentation (#178)
* tsk-170: Added utopia crates for API documentation

* tsk-170: Adding code to document API

* tsk-170: icarus_models version bump

Added schema capabilities

* tsk-170: crate changes

* tsk-170: Added documentation for song queue endpoint

* tsk-170: Swagger openapi docs are now up

Well, at least one

* tsk-170: Some documentation

* tsk-170: Code formatting

* tsk-170: Saving changes

* tsk-170: Added more documentation

* tsk-170: Added the rest of the documentation

* tsk-170: Formatting

* tsk-170: icarus_models version bump
2025-08-24 19:58:38 -04:00
KD 598996cb8d tsk-176: Get all songs endpoint (#177)
* tsk-176: Added function to retrieve all songs

* tsk-176: Depdendency version bump

icarus_envy, icarus_meta, and icarus_models

* tsk-176: Fix after icarus_models change

* tsk-176: Test fix

* tsk-176: Formatting

* tsk-176: Endpoint is now available

* tsk-176: Added test

* tsk-176: Cleanup

* tsk-176: Version bump
2025-08-19 12:25:46 -04:00
KD 21a97c150c tsk-172: Include songparser as docker image (#173)
* tsk-172: Updated docker compose to include songparser service

* tsk-172: Changed docker dependencies

* tsk-172: Cleanup
2025-08-16 19:14:01 -04:00
KD 679a4ad322 Auth (#169)
* Added jwt crate

* Saving changes

Might go a different route later

* Crate changes

* Adding auth module

* Saving changes

* Added jsonwebtoken crate

* Saving changes

* Added feature to tower-http crate

* Using secret key from env file

* Locking down one endpoint to start

* Warning fix

* Got auth functioning

* Updated icarus_models

* Fixed auth in tests

* Warning fixes

* Code formatting

* Added auth to the other endpoints

* Version bump

* This should fix the pipeline test failure
2025-08-01 15:16:00 -04:00
KD 9aefeace23 Use multiple files in tests (#168)
* File renamed

* Filename change in the code as well

* Added more migration sql for tests

* Using different song for a test

* Changes to test and helper functions

* Workflow change

* Code formatting

* Version bump
2025-07-30 15:28:47 -04:00
KD a0c6ae65a3 Delete song endpoint (#167)
* Added initial code for delete song endpoint

* Saving changes

* More changes

* Made delete song endpoint available

* Response change

* Added test function

* Changes to code

Fixing errors

* How did I miss this?

* Got the test working

* Code cleanup and formatting

* Version bump

* Code changes

* Workflow change
2025-07-29 21:34:16 -04:00
KD c7230d3b32 Download coverart endpoint (#166)
* Added download coverart endpoint

* Endpoint is now available

* Added test

* Code formatting

* Version bump
2025-07-28 17:05:42 -04:00
KD 703fc49f32 Downloading song endpoint (#165)
* Added initial code for downloading song endpoint

* Finished download song endpoint

* Making download endpoint available

* Added test

* Code formatting

* Version bump
2025-07-28 16:40:14 -04:00
KD e98e055de0 Stream song (#164)
* Added crates and dependency features

* Added endpoint to stream songs

* Changed name of function

* Song stream endpoint is now available

* Endpoint is now working

* Added test

* Warning fixes

* Code formatting

* Added TODO for later

* Test fix

* Version bump
2025-07-27 14:20:42 -04:00
KD a8603361c0 Get coverart (#163)
* Added initial code to get coverart endpoint

* Test migration cleanup

* Updated icarus_models

* Made endpoint evailable

* Added test

* Version bump

* Code formatting
2025-07-26 14:12:03 -04:00
KD dbda9a3897 Get songs endpoint (#162)
* Added test_migrations directory

* Added skeleton endpoint to get songs

* Code formatting

* Added more code

* Added TODO

* Code formatting

* Updated album in album json file

* Changing directory name

* Test refactoring

* Forgot to include this

* Added test for getting songs and added function for test_migrations

* Adding test migrations

* Removing placeholder

* Renamed

* Renamed

* Fixed what caused test failure

* Created migration with cli command

Creating test_migrations/20250725213448_migration_name.sql

* Migration changes

* Removing migration

* More migration changes

* Made endpoint available

* Migration changes

* Got the test to work

* Cleaned up test

* Code formatting

* More cleanup

* Version bump
2025-07-25 18:20:28 -04:00
KD a987e438c4 Added flac files used for testing (#161)
* Added flac files used for testing

* Refactor test

* Added CoverArt file for test files

* Added album json file for testing

* Modifying test json file

* Modifying test file for consistency

* Test refactoring

* Test file changes

* Removing commented code

* Removing files used for testing

* Removing placeholder

* Code formatting
2025-07-25 16:09:01 -04:00
KD a150d34c6c Added release workflow (#160)
* Added release workflow

* Temp change

* File extension change

* Syntax change

* Removing that temp change
2025-07-22 21:59:20 -04:00
KD 34e292bea9 Link user id to song queue (#159)
* Added initial code for endpoint to link user id with song queue #156

* Updated songQueue to have a user_id field #156

* Added function to link user_id with songQueue record #156

* Added useful constant #156

* Finished adding code #156

Need to make the endpoint available and then write a test. Might have to modify existing tests

* Made link user id endpoint available #156

* Added TODOs for later

* Changing location of test code

* Code formatting

* Added test #156

* Formatted code

* Added user_id to SongQueue and added more related code

* Code formatting

* Fixing possible nil user_id field in SongQueue when calling a function

* Fixed another issue

* Made changes to function to also return user_id

* Making use of user_id in test requests

* Code formatting

* Updated workflow

* Forgot to include port

* Docker changes for port change

* Reverting port changes

* Cleaning up Dockerfile

* Version bump
2025-07-22 21:36:29 -04:00
KD c9bcea5f98 Version change (#158) 2025-07-15 16:15:51 -04:00
KD 6c9e4809a9 Fixing bug where message in response was unpopulated on successful requests (#157) 2025-07-15 15:10:51 -04:00
KD 4c5bd1ccde Updated icarus_models (#155) 2025-07-14 20:09:43 -04:00
KD 5a2639cb59 Added error checking for file creation in create metadata endpoint (#154)
* Added error checking for file creation in create metadata endpoint

* Code formatting

* Fixed create metadata endoint

* Added missing message in the response

* Cleanup

* Warning fixes

* Code formatting
2025-07-14 19:42:07 -04:00
KD fd9df41f51 Updated rust version in docker (#152) 2025-07-13 18:54:47 -04:00
KD 7fdea3491f Upgrading postgresql to 17.5 (#151)
Closes #150
2025-07-12 15:59:23 -04:00
KD 3cde57dca8 Refactoring (#149)
* Warning fixes

* More warning fixes

* Cargo.toml cleanup
2025-06-29 17:33:45 -04:00
KD 8c93429647 Update dependencies (#148)
* Updating Cargo.lock

* Updating axum

* Updated tokio, tokio-util, and tower-http

* Updated uuid and sqlx

* Updated icarus_models, icarus_envy, and icarus_meta

* Updated tempfile
2025-06-29 17:15:20 -04:00
KD 5721c387ea Rust std change (#147)
* Targeting rust 1.88

* Updating workflow
2025-06-29 17:03:59 -04:00
KD a624702813 Update song queue endpoint fix (#146)
* Bug fix that was causing errors

* Code formatting

* Removed commented code
2025-06-28 19:06:41 -04:00
KD 9c67bfd8a8 Update song queue changes (#145)
* Updated gitignore to disregard some .env files

.env.docker and .env.local. Primarily used for switching between local and docker development

* Changed PATCH /api/v2/song/queue/{id} endpoint

Modified the response body. Will just return a list of song queue id

* Adding some helpful info for the response body

* Tidying up and making some changes

* Code formatting
2025-06-28 16:45:25 -04:00
KD fbec3305b1 Reorganizing metadata queue code (#144)
* Reorganizing metadata queue code

* Function name change

* Test payload changes

* function parameter name change
2025-06-18 19:47:41 -04:00
KD fa792be9cc Fixed endpoint for getting coverart queue data (#143)
* Fixed endpoint for getting coverart queue data

* Modified test

* Corrected endpoint syntax

* Fixed test

* Some cleanup

* Formatting
2025-06-17 21:40:49 -04:00
KD 6f2e8d6e17 Update song queue flow (#142)
* Added new status and made changes to song queue status code

* Saving changes

* Got a test working

* Got another test working

* Got the last test working

* Code cleanup

* More minor changes

* More minor changes

* Minor changes
2025-06-07 14:47:42 -04:00
KD eb1f19a96e Refactoring tests (#141)
* Saving changes

* Got test working

* Removing commented code

* Code formatting

* Refactoring test

* Code refactoring

* More refactoring

* Code refactoring

* Last bit of tidying up
2025-06-04 20:40:41 -04:00
KD bb766acf4e Added icarus_envy (#140)
* Added icarus_envy

* Commenting out dotenvy crate

* Removing environment and keys modules

* Replacing with icarus_envy

* Making changes to test code

* Removing lingering references in tests

* Test fix

* Test fix

* Another test fix

* Rust formatting

* Removing commented crate

* Using v0.2.0 version of icarus_envy
2025-06-01 20:20:33 -04:00
KD 95688cccfa Including Cargo.lock in source control (#139)
* Removing cargo.lock from gitignore

* Adding cargo.lock
2025-06-01 19:15:33 -04:00
KD e2485cec44 Add sample docker env (#138)
* Added sample .env.docker file

* Updated sample .env file
2025-05-28 19:41:38 -04:00
KD df1562f5e7 Updated auth environment variables in docker (#137) 2025-05-27 16:59:20 -04:00
KD e00e9cf185 Wipe data from coverart queue (#136)
* Changes to coverartQueue migrations

* Added endpoint to wipe data from coverart queue

* Added constant for endpoint

* Endpoint is now available

* Added test

Need to complete

* Test is working

* Code formatting

* Removed TODO
2025-05-26 17:12:11 -04:00
KD f0d2b9de71 Wipe data from song queue (#135)
* Added TODOs for later

* Added endpoint to wipe data from song queue

* Migration changes

* Syntax error fix

* Added and linked endpoint

* Added test

* Warning fixes

* Code formatting
2025-05-25 21:12:17 -04:00
KD f0a0bee22b Create coverart (#134)
* Added migrations for coverart

* Test refactor

* Code formatting

* Added endpoint to create coverart

* Endpoint is available

* Migration changes to song table

* some fixes

* Added test

* Test refactor

* Code formatting

* Clippy warning fixes

* Code cleanup
2025-05-24 19:02:48 -04:00
KD 0b73c055aa Create metadata (#133)
* Added migration for metadata table used to store a song's metadata

* Added comment for new table

* Added endpoint to create metadata

* Filling out code

* Changed type of duration in request

* Reorganizing code

* Changing metadata table to song

* Added TODO for data type discrepancy for the future

* Fix migration syntax error

* Added types to request

* Added environment variable for root directory:

* Moving keys to its own module

* Moved environement related code to its own module

* Added function to get root_directory

* Added endpoint to create song

* Minor fixes

* Added test and refactored tests

* Ironing out some kinks

* Resolved test issue

Turns out I was using the wrong id value

* Added env variable in workflow

* Added TODO

* Updated env variable

* clippy warning fixes

* Making sure date_created is populated when returneD

* Code cleanup

* Added TODOs

* Uncommenting tests

* Code formatting
2025-05-23 20:12:15 -04:00
KD d4c025511d Updating song from queue (#132)
* Added endpoint - no code - for updating the song from the queue

* Added endpoint to update song from queue

* Endpoint is now available

* Fixed endoint uri

* Added tempfile crate for tests

* Test is working

* Test is operational

* Code formatting

* Code cleanup
2025-05-22 16:18:12 -04:00
KD b2a4faec76 Coverart queue fetch data (#131)
* Added coverart queue data fetch endpoint

* Added test

* Code formatting
2025-05-22 15:03:57 -04:00
KD 7d27aed314 Coverart queue fetch without data (#130)
* Added endpoint

* Endpoint is now accessible

* Moved request to its own function in tests

* Added test, but running into issues

* Fixing code causing test to fail

* Code formatting
2025-05-21 19:26:38 -04:00
KD 961f99b744 Update song queue status (#129)
* Changes to status definition

* Added endpoint to update song_queue status

* endpoint return fix

* Endpoint now available

* Added test

* Code formatting

* Clippy warning fix
2025-05-20 20:42:34 -04:00
KD b1f5c5f604 Link coverart with song queue (#128)
* Added initial code to link coverart id and song queue id

* Added more functionality

* Preparing test

* Finished test

* Cleanup

* Code formatting

* Clippy warning fix
2025-05-19 21:54:50 -04:00
KD ddb0bf27f8 Queue coverart (#127)
* Added new module

* Added new endpoint

* Formatting

* Migration changes

* Fix routing issue

* Fixed migration

* Added functionality and test

* Test change

* Cleanup

* Code formatting
2025-05-18 18:22:39 -04:00
KD d491767de4 Get metadata (#126)
* Added time crate

* Added endpoint to get metadata

* Formatting

* Added more code to get metadata

Having issues returning response

* Formatting

* Migration change

* Fix date issue

* Got it somewhat working

* Got things working

* Code fix

* Added test

* Formatting

* Test works

* Cleanup

* Migrations cleanup
2025-04-29 21:52:22 -04:00
KD 8755276b48 Fetch next queued song (#125)
* Added code

* Got it working

* Added test and refactored test code

* Removed comment

* Cleanup

* Code formatting
2025-04-26 18:38:17 -04:00
KD fd41d25c4c Test refactor (#124)
* Refactoring test

* Test refactor

* Added code to get response content

* More refactoring

* Code refactor
2025-04-26 16:56:09 -04:00
KD 5e3ca1861d Next queued song (#123)
* Added code to fetch next queue item

* Updated README

* Give it a go

* Minor docker compose change

* Added docker-compose defaults

* Code refactor

* Removed data from being fetched

* Added test

* Formatting
2025-04-26 16:11:46 -04:00
KD db7350b550 Added status to songQueue table (#122)
* Added status to songQueue table

* Added status

* Formatting

* Removed failed option for the status field for now
2025-04-24 21:11:45 -04:00
KD f823a99984 Queue meta data (#121)
* Added migrations

Added new table to store metadata

* Updated table

* Added code for new endpoint

* Updated module

* Code formatting:

* Added test code

* Fixed test

* Cleanup

* Code refactor
2025-04-23 20:50:07 -04:00
KD 2823452198 Added callers moulde (#120)
* Added callers moulde

* Code formatting

* Added uuid dependency

* Added queue_song endpoint

* Added endpoint to router

* Added dependencies for postgres

* Added migrations directory

* Added more code

* Added migrations

* Removed migration

* Docker fixes

* Updated gitignore

* Updated env sample file

* Endpoint url fix

* Updated env sample

* Updated docker file to copy migrations

* Might undo later

* Updated env sample and docker compose

* Updated cargo dependencies

* Saving changes

* Workflow fix

* Will need to take another look at the dependencies again

* Added code

* Test is not finished yet

* Warning fix for now

* Updated workflow to setup database

* Workflow fix

* Workflow fix attempt

* Warning fix

* Warning fix

* Updated workflow

* Added test files

Might change later

* Added more crates

* Added more test code

Not finished

* Formatting

* Close, but far

* I believe it is now working

* Formatting

* Added more crates

* Code cleanup

* Code reformatting

* Code cleanup

* Crate cleanup

* Cleanup
2025-04-22 20:08:24 -04:00
KD 0ba2d4e8b9 Updated workflow (#119) 2025-04-20 14:05:03 -04:00
KD 4fdd660988 Updated packages (#118)
* Updated tokio

* Updated serde packages

* Updated icarus related dependencies
2025-04-20 14:01:33 -04:00
KD b6fe9a070c Added Docker file (#117)
* Added Docker file

* Added docker files

* Updated docker

Added icarus_auth and second db

* Cleanup

* Docker changes

* Saving changes

Still running into issues with icarus_auth starting in docker. Must be related to credentials or url

* Changes to docker

* Got auth_api working

* Cleanup

* Docker cleanup

* Updated gitignore

* Added README

* Updated gitignore

* Added directory to ignore to dockerignore

* File name change
2025-04-13 14:53:05 -04:00
KD 6e4eeafe13 Added .env.sample file (#116)
* Added .env.sample file

* Adedd variables

* Using default info
2025-04-12 15:56:10 -04:00
KD 6f320acb7c V0.2 web api (#113)
* Adding dependencies

* Added web api code

* Some changes

* Code formatting

* Added dependencies

*   *

* Added workflow

* Changed branch to trigger workflows

* Added ssh key import

* Warning fixes
2025-03-30 15:00:07 -04:00
KD 9dd7ffa2b6 Updated gitignore 2025-03-28 19:04:35 -04:00
KD fbcbd41809 Added initial rust code 2025-03-28 19:03:51 -04:00
KD 01d315e25e Updating gitignore 2025-03-28 19:03:03 -04:00
KD caf9f08d8a Forgot to remove this files 2025-03-28 19:02:31 -04:00
KD 7227eb9420 Removing dotnet files 2025-03-28 19:00:05 -04:00
KD 12c4f56a22 Merge pull request #112 from kdeng00/version_bump
Version bump
2025-03-28 18:50:37 -04:00
KD 6d650b7962 Delete song endpoint Bug fix (#111)
* Bug fix

* Removed some code

* Simplifying method
2025-03-28 18:49:34 -04:00
KD 73bb417bde Version bump 2025-03-28 18:48:02 -04:00
KD b0277077f4 Version bump (#110) 2025-03-11 22:09:57 -04:00
KD 3edf6424d0 Updated packages (#109) 2025-03-11 22:04:45 -04:00
KD dcb51448aa tsk-76: Added model and context for AccessLevel (#108)
* tsk-76: Added model and context for AccessLevel

* Formatted code

* AccessLevel migrations are working

* minor formatting

* tsk-#76: Saving AccessLevel when uploading song

* tsk-#76: Added endpoints

* tsk-#76: Warning fix

* tsk-#76: Adding more controller code

* Functionality to modify access levels is operational

* Formatting

* tsk-#76: Added functionality

* tsk-#76: Formatting code

* tsk-#76: Adding more code

* tsk-#76: Formatting
2025-03-11 21:45:32 -04:00
KD 9d90247bf8 Suppressing warning for endpoints (#107)
* Suppressing warning for endpoints

* Minor refactoring
2025-03-01 16:36:02 -05:00
KD 86e54e086a #91: Deprecating upload endpoint (#106)
* #91: Deprecating upload endpoint

* #91: Marking method as obsolete and left a todo

* #91: Removed methods
2025-02-27 19:35:39 -05:00
KD fd3ce9f96a #103: Remove WAV support (#105)
* #103: Adding checks to prevent .wav files from being uploaded:

* #103: Added method to create song and moving some code around

* #103: Fixed build issue

* tsk-103: Cleanup of temporary files

* tsk-103: Formatting changes

* tsk-103: Minor changes

* tsk-103: Fixing build issue

* tsk-103: Refactored enum

* CORE-23734: Refactoring

* tsk-103: Confirmed functionality is working

* Removed commented code

* Removed commented code
2025-02-16 17:24:50 -05:00
KD a89580ac70 #102: Moving Models and constants to their own library (#104)
* #102: Moving Models and constants to their own library

* #102: Updated sln file

* #102: Updated README to include step install migration tool
2024-08-05 20:05:57 -04:00
KD 8900afdfd2 #93: Add flac support (#101)
* Added script shell to convert wav files to flac

* #93: Minor change to script to convert wav files to flac

* #93: Added more code to for the music file conversion

* #93: Script to convert wav files to flac files is done

* #93: Clean up

* #93: Starting work to implement flac support

* #93: Minor update to conversion script

* #93: Added dotnet manifest file

Includes the dotnet-ef tool

* #93: Updated README and migration script

* #93: Created skeleton for saving flac files

* #93: Making some changes to how the file extension is determined

* #93: Updated gitignore

* #93: Another gitignore update

* #93: Making some changes to the process of saving a song to the filesystem

* #93: Adding SQL script to drop and create database

* #93: Saving uploaded song to a temporary location for processing

* #93: Initializing some properties in the song model earlier

* #93: Uploading wav songs works. Moving on to flac support

* #93: Added more code to save flac files

* #93: Updated some code that affects filename generation for audio files

* #93: Song Model changes and support for different file types

* #93: Working on build errors, removed DotnetZip dependency, and added new Ionic.Zlip.Netstandard dependency

* #93: Reduce build errors

* #93: Removed ID3 dependency

* #93: Cleanup
2024-07-27 13:19:12 -04:00
Kun Deng 4b3fa78336 #95: Id changes to models (#99)
* #95: Updated Id of the CoverArt model

* Model and migration changes
2024-06-21 20:30:23 -04:00
Kun Deng 71656aa940 #94: Saving the file type of cover art, but there is still some work to do (#100)
* #94: Saving the file type of cover art, but there is still some work to do

The filename of cover art is hard coded to have the png extension. Need to correct this

* #94: Added a TODO

* #94: Corrected file extension being saved in the db

* Cleanup

* Saving databasescripts
2024-06-21 20:26:44 -04:00
Kun Deng 562bc87822 #74: Add UserID to the Song model (#98)
* #74: Add UserID to the Song model

* #74: Added functionality to retrieve user id from the token

* #74: Songs will now contain the User Id when uploading

* Updated Readme and script to add migrations

* #74: Some cleanup
2024-06-19 15:41:55 -04:00
Kun Deng ebb15b7cdb #79: Added query parameter to randomize filename when downloading songs (#96)
* #79: Added query parameter to randomize filename when downloading songs

Right now only the  endpoint has this parameter added

* #79: Added functionality to the comressed song endpoint

* Added functionality to the download cover art
2024-06-16 19:04:10 -04:00
Kun Deng 270b7d059c #90: Adding functionality to download cover art (#97)
* Added endpoint to download cover art

* Code cleanup

* More cleanup
2024-06-16 18:28:08 -04:00
Kun Deng 23c50de468 Net8 (#89)
* .NET 8 migration

* Fixed bugs with song management

* More cleanup and making some constants

* Updated yml

* Clean up

Removing comments, some cleanup, and moving the startup code into Program.cs

* Removing comments

* Fixed song deletion issue

* Added functionality to delete song directories

* Updated README
2024-06-15 12:17:12 -04:00
kdeng00 ececcb5ba3 Cover art changes 2024-06-09 13:10:51 -04:00
Kun Deng 8658dd34ab Merge pull request #87 from kdeng00/update_namespace
Migrating to modern c# namespace
2023-04-09 12:43:48 -04:00
kdeng00 c17c9cd329 Migrating to modern c# namespace
Using the short namesapce declaration for conciseness
2023-04-09 12:34:06 -04:00
121 changed files with 9826 additions and 4867 deletions
+21
View File
@@ -0,0 +1,21 @@
# Ignore build artifacts
target/
pkg/
# Ignore git directory
.git/
.github/
# Ignore environment files (configure via docker-compose instead)
.env*
# Ignore IDE/editor specific files
.idea/
.vscode/
# Ignore OS specific files
*.DS_Store
# Add any other files/directories you don't need in the image
# e.g., logs/, tmp/
+12
View File
@@ -0,0 +1,12 @@
APP_ENV=development
BACKEND_PORT=8000
FRONTEND_URL=http://localhost:4200
RUST_LOG=debug
ALLOWED_ORIGINS=https://soaricarus.com,https://www.soaricarus.com
SECRET_MAIN_KEY=refero34o8rfhfjn983thf39fhc943rf923n3h
ROOT_DIRECTORY=/home/icarus/mydata
POSTGRES_MAIN_USER=icarus
POSTGRES_MAIN_PASSWORD=password
POSTGRES_MAIN_DB=icarus_db
POSTGRES_MAIN_HOST=main_db
DATABASE_URL=postgres://${POSTGRES_MAIN_USER}:${POSTGRES_MAIN_PASSWORD}@${POSTGRES_MAIN_HOST}:5432/${POSTGRES_MAIN_DB}
+12
View File
@@ -0,0 +1,12 @@
APP_ENV=development
BACKEND_PORT=8000
FRONTEND_URL=http://localhost:4200
RUST_LOG=debug
ALLOWED_ORIGINS=https://soaricarus.com,https://www.soaricarus.com
SECRET_MAIN_KEY=refero34o8rfhfjn983thf39fhc943rf923n3h
ROOT_DIRECTORY=/home/icarus/mydata
POSTGRES_MAIN_USER=icarus
POSTGRES_MAIN_PASSWORD=password
POSTGRES_MAIN_DB=icarus_db
POSTGRES_MAIN_HOST=main_db
DATABASE_URL=postgres://${POSTGRES_MAIN_USER}:${POSTGRES_MAIN_PASSWORD}@${POSTGRES_MAIN_HOST}:5432/${POSTGRES_MAIN_DB}
+12
View File
@@ -0,0 +1,12 @@
APP_ENV=production
BACKEND_PORT=8000
FRONTEND_URL=http://localhost:4200
RUST_LOG=debug
ALLOWED_ORIGINS=https://soaricarus.com,https://www.soaricarus.com,http://localhost:8000,http://127.0.0.1:8000
SECRET_MAIN_KEY=refero34o8rfhfjn983thf39fhc943rf923n3h
ROOT_DIRECTORY=/home/icarus/mydata
POSTGRES_MAIN_USER=icarus
POSTGRES_MAIN_PASSWORD=password
POSTGRES_MAIN_DB=icarus_db
POSTGRES_MAIN_HOST=localhost
DATABASE_URL=postgres://${POSTGRES_MAIN_USER}:${POSTGRES_MAIN_PASSWORD}@${POSTGRES_MAIN_HOST}:5432/${POSTGRES_MAIN_DB}
+9
View File
@@ -0,0 +1,9 @@
# Override specific file types
*.cs linguist-language=Rust
*.sln linguist-documentation
*.csproj linguist-documentation
# Or vendor all non-Rust files
*.cs linguist-vendored
*.js linguist-vendored
*.py linguist-vendored
-25
View File
@@ -1,25 +0,0 @@
name: .NET
on:
push:
branches: [ "master" ]
pull_request:
branches: [ "master" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup .NET
uses: actions/setup-dotnet@v2
with:
dotnet-version: 6.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build
run: dotnet build --no-restore
- name: Test
run: dotnet test --no-build --verbosity normal
+50
View File
@@ -0,0 +1,50 @@
name: Release Tagging
on:
push:
branches: [ "v0.2" ]
jobs:
release:
runs-on: ubuntu-24.04
steps:
- name: Checkout code
uses: actions/checkout@v5
with:
fetch-depth: 0 # Important for git describe --tags
- name: Install Rust
uses: actions-rs/toolchain@v1
with:
toolchain: 1.95
components: cargo
- name: Extract Version from Cargo.toml
id: version
run: |
VERSION=$(grep '^version = "' Cargo.toml | sed -E 's/version = "([^"]+)"/\1/')
PROJECT_COMMIT_HASH=$(git rev-parse HEAD | cut -c 1-10)
BRANCH_REF="${GITHUB_REF}"
BRANCH_NAME=$(echo "$BRANCH_REF" | cut -d '/' -f 3)
PROJECT_TAG_RELEASE="v$VERSION-$BRANCH_NAME-$PROJECT_COMMIT_HASH"
echo "::set-output name=project_tag_release::$PROJECT_TAG_RELEASE-961"
echo "Version: $VERSION"
echo "Hash: $PROJECT_COMMIT_HASH"
echo "Branch: $BRANCH_NAME"
echo "Tag Release: $PROJECT_TAG_RELEASE"
- name: Print version
id: print_version
run: |
echo "Printing version"
echo "Version: ${{ steps.version.outputs.project_tag_release }}"
- name: Create GitHub Release
uses: actions/create-release@v1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: ${{ steps.version.outputs.project_tag_release }}
release_name: Release ${{ steps.version.outputs.project_tag_release }}
body: |
Release of version ${{ steps.version.outputs.project_tag_release }}
+79
View File
@@ -0,0 +1,79 @@
name: Rust CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-24.04
services:
postgres:
image: postgres:18.3-alpine
env:
POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }}
POSTGRES_USER: ${{ secrets.POSTGRES_USER }}
POSTGRES_DB: ${{ secrets.POSTGRES_DB }}
ports:
- 5432:5432
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v5
- name: Install Rust 1.95
uses: actions-rs/toolchain@v1
with:
toolchain: 1.95
components: clippy, rustfmt
override: true
- name: Cache dependencies
uses: Swatinem/rust-cache@v2
- name: Install libpq
run: sudo apt-get install -y libpq-dev
- name: Setup test database
env:
DATABASE_URL: "postgres://${{ secrets.POSTGRES_USER }}:${{ secrets.POSTGRES_PASSWORD }}@localhost:5432/${{ secrets.POSTGRES_DB }}"
run: |
# Wait for PostgreSQL to be ready
for i in {1..10}; do
pg_isready -U ${{ secrets.POSTGRES_USER }} -d ${{ secrets.POSTGRES_DB }} && break
sleep 2
done
# Run database migrations (if you use sqlx migrations)
cargo install sqlx-cli --no-default-features --features native-tls,postgres
sqlx migrate run --database-url $DATABASE_URL
- name: Build
run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/gitea_deploy_key
chmod 600 ~/.ssh/gitea_deploy_key
ssh-keyscan ${{ vars.MYHOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/gitea_deploy_key
cargo build --verbose --release
- name: Run tests
env:
ROOT_DIRECTORY: "/tmp"
DATABASE_URL: "postgres://${{ secrets.POSTGRES_USER }}:${{ secrets.POSTGRES_PASSWORD }}@localhost:5432/${{ secrets.POSTGRES_DB }}"
run: |
cat .env.sample | head -6 > .env
cargo test --verbose --
- name: Run clippy
run: cargo clippy -- -D warnings
- name: Run rustfmt
run: cargo fmt --all -- --check
+12 -10
View File
@@ -1,11 +1,13 @@
################################################################################ # Added by cargo
# This .gitignore file was automatically created by Microsoft(R) Visual Studio.
################################################################################
/.vs/Icarus /target
/bin/* .env
/bin/Debug/netcoreapp2.2 .env.docker
/Migrations .env.local
/obj
/obj/* .DS_STORE
/Icarus.txt Storage/
*.sln
*.cs
*.csproj
+8
View File
@@ -0,0 +1,8 @@
{
"dev": {
"migrations": "./migrations"
},
"test": {
"migrations": "./test_migrations"
}
}
-31
View File
@@ -1,31 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Icarus.Authorization;
namespace Icarus.Authorization.Handlers
{
public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))
{
return Task.CompletedTask;
}
var scopes = context.User.FindFirst(c =>
c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');
if (scopes.Any(s => s == requirement.Scope))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
}
-19
View File
@@ -1,19 +0,0 @@
using System;
using Microsoft.AspNetCore.Authorization;
namespace Icarus.Authorization
{
public class HasScopeRequirement : IAuthorizationRequirement
{
public string Issuer { get; }
public string Scope { get; }
public HasScopeRequirement(string scope, string issuer)
{
Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
}
}
}
-67
View File
@@ -1,67 +0,0 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.
Please note the project has a code of conduct, please follow it in all your interactions with the project.
## Code of Conduct
### Pledge
In the interest of fostering an open and welcoming environment, I as
aintainers pledge to making participation in this project and
this community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
### Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
### Maintainers Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
## How You Can Contribute
The project is always looking for people to help in anyway they can. The following would be greatly appreciated:
* Developers
* Graphic Designers
* Documenters
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
Generated
+3335
View File
File diff suppressed because it is too large Load Diff
+35
View File
@@ -0,0 +1,35 @@
[package]
name = "icarus"
version = "0.5.0"
edition = "2024"
rust-version = "1.95"
[dependencies]
axum = { version = "0.8.9", features = ["multipart"] }
axum-extra = { version = "0.12.6", features = ["cookie"] }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = { version = "1.0.149" }
tokio = { version = "1.52.3", features = ["full"] }
tokio-util = { version = "0.7.18", features = ["io"] }
tower = { version = "0.5.3", features = ["full"] }
tower-http = { version = "0.6.10", features = ["cors", "timeout"] }
tracing-subscriber = "0.3.23"
futures = { version = "0.3.32" }
mime_guess = { version = "2.0.5" }
uuid = { version = "1.23.1", features = ["v4", "serde"] }
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio-native-tls", "time", "uuid"] }
time = { version = "0.3.47", features = ["formatting", "macros", "parsing", "serde"] }
thiserror = "2.0.18"
base64 = "0.22.1"
jsonwebtoken = { version = "10.3.0", features = ["rust_crypto"] }
josekit = { version = "0.10.3" }
utoipa = { version = "5.5.0", features = ["axum_extras"] }
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
icarus_meta = { git = "ssh://git@git.kundeng.us/phoenix/icarus_meta.git", tag = "v0.6.0" }
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.11.1" }
icarus_envy = { git = "ssh://git@git.kundeng.us/phoenix/icarus_envy.git", tag = "v0.7.0" }
[dev-dependencies]
common-multipart-rfc7578 = { version = "0.7.0" }
url = { version = "2.5.8" }
tempfile = { version = "3.27.0" }
-80
View File
@@ -1,80 +0,0 @@
using System;
using System.Security.Cryptography;
using Microsoft.IdentityModel.Tokens;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
namespace Icarus.Certs
{
public class SigningIssuerCertificate : IDisposable
{
private readonly RSACryptoServiceProvider _rsa;
public SigningIssuerCertificate()
{
_rsa = new RSACryptoServiceProvider();
}
public RsaSecurityKey GetIssuerSigningKey(string publicKeyPath)
{
var file = publicKeyPath;
var publicKey = System.IO.File.ReadAllText(file);
using (var reader = System.IO.File.OpenText(file))
{
var pem = new PemReader(reader);
var o = (RsaKeyParameters)pem.ReadObject();
var parameters = new RSAParameters();
parameters.Modulus = o.Modulus.ToByteArray();
parameters.Exponent = o.Exponent.ToByteArray();
_rsa.ImportParameters(parameters);
}
return new RsaSecurityKey(_rsa);
}
public void Dispose()
{
_rsa?.Dispose();
}
}
public class SigningAudienceCertificate : IDisposable
{
private readonly RSACryptoServiceProvider _rsa;
public SigningAudienceCertificate()
{
_rsa = new RSACryptoServiceProvider();
}
public SigningCredentials GetAudienceSigningKey(string keyPath)
{
var file = keyPath;
var publicKey = System.IO.File.ReadAllText(file);
using (var reader = System.IO.File.OpenText(file))
{
var pem = new PemReader(reader);
var o = (RsaKeyParameters)pem.ReadObject();
var parameters = new RSAParameters();
parameters.Modulus = o.Modulus.ToByteArray();
parameters.Exponent = o.Exponent.ToByteArray();
_rsa.ImportParameters(parameters);
}
return new SigningCredentials(
key: new RsaSecurityKey(_rsa),
algorithm: SecurityAlgorithms.RsaSha256);
}
public void Dispose()
{
_rsa?.Dispose();
}
}
}
-11
View File
@@ -1,11 +0,0 @@
using System;
using System.IO;
namespace Icarus.Constants
{
public class DirectoryPaths
{
public static string CoverArtPath =>
Directory.GetCurrentDirectory() + "/Images/Stock/CoverArt.png";
}
}
-155
View File
@@ -1,155 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class AlbumManager : BaseManager
{
#region Fields
private AlbumContext _albumContext;
#endregion
#region Properties
#endregion
#region Constructors
public AlbumManager(IConfiguration config)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
_albumContext = new AlbumContext(_connectionString);
}
#endregion
#region Methods
public void SaveAlbumToDatabase(ref Song song)
{
_logger.Info("Starting process to save the album record of the song to the database");
var album = new Album();
album.Title = song.AlbumTitle;
album.AlbumArtist = song.Artist;
album.Year = song.Year.Value;
var albumTitle = song.AlbumTitle;
var albumArtist = song.Artist;
var albumRetrieved = _albumContext.Albums.FirstOrDefault(alb => alb.Title.Equals(albumTitle) && alb.AlbumArtist.Equals(albumArtist));
if (albumRetrieved == null)
{
album.SongCount = 1;
_albumContext.Add(album);
_albumContext.SaveChanges();
Console.WriteLine($"Album Id {album.AlbumID}");
}
else
{
album.AlbumID = albumRetrieved.AlbumID;
}
song.AlbumID = album.AlbumID;
}
public void DeleteAlbumFromDatabase(Song song)
{
var album = _albumContext.Albums.FirstOrDefault(alb => alb.Title.Equals(song.AlbumTitle));
if (album == null)
{
_logger.Info("Cannot delete the album record because it does not exist");
return;
}
DeleteAlbumFromDb(album);
}
public Album UpdateAlbumInDatabase(Song oldSong, Song newSong)
{
var albumRecord = _albumContext.Albums.FirstOrDefault(alb => alb.Title.Equals(oldSong.AlbumTitle));
var oldAlbumTitle = oldSong.AlbumTitle;
var oldAlbumArtist = oldSong.Artist;
var newAlbumTitle = newSong.AlbumTitle;
var newAlbumArtist = newSong.Artist;
var info = string.Empty;
if (string.IsNullOrEmpty(newAlbumArtist))
newAlbumArtist = oldAlbumArtist;
if (string.IsNullOrEmpty(newAlbumTitle))
newAlbumTitle = oldAlbumTitle;
if ((string.IsNullOrEmpty(newAlbumTitle) && string.IsNullOrEmpty(newAlbumArtist) ||
oldAlbumTitle.Equals(newAlbumTitle) && oldAlbumArtist.Equals(newAlbumArtist)))
{
_logger.Info("No change to the song's album");
return albumRecord;
}
info = "Change to the song's album";
_logger.Info(info);
var existingAlbumRecord = _albumContext.Albums.FirstOrDefault(alb => alb.Title.Equals(oldSong.AlbumTitle));
if (existingAlbumRecord == null)
{
_logger.Info("Creating new album record");
var newAlbumRecord = new Album
{
Title = newAlbumTitle,
AlbumArtist = newAlbumArtist,
Year = newSong.Year.Value
};
_albumContext.Add(newAlbumRecord);
_albumContext.SaveChanges();
return newAlbumRecord;
}
else
{
_logger.Info("Updating existing album record");
existingAlbumRecord = _albumContext.Albums.FirstOrDefault(alb => alb.Title.Equals(newSong.AlbumTitle));
existingAlbumRecord.AlbumArtist = newAlbumArtist;
_albumContext.Update(existingAlbumRecord);
_albumContext.SaveChanges();
return existingAlbumRecord;
}
}
private void DeleteAlbumFromDb(Album album)
{
if (SongsInAlbum(album) <= 1)
{
_albumContext.Remove(album);
_albumContext.SaveChanges();
}
}
private int SongsInAlbum(Album album)
{
var sngContext = new SongContext(_connectionString);
var songs = sngContext.Songs.Where(sng => sng.AlbumID == album.AlbumID).ToList();
return songs.Count;
}
#endregion
}
}
-137
View File
@@ -1,137 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class ArtistManager : BaseManager
{
#region Fields
private ArtistContext _artistContext;
#endregion
#region Properties
#endregion
#region Constructors
public ArtistManager(IConfiguration config)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
_artistContext = new ArtistContext(_connectionString);
}
#endregion
#region Methods
public void SaveArtistToDatabase(ref Song song)
{
_logger.Info("Starting process to save the artist record of the song to the database");
var artist = new Artist();
artist.Name = song.Artist;
artist.SongCount = 1;
var artistTitle = artist.Name;
var artistRetrieved = _artistContext.Artists.FirstOrDefault(art => art.Name.Equals(artistTitle));
if (artistRetrieved == null)
{
artist.SongCount = 1;
_artistContext.Add(artist);
_artistContext.SaveChanges();
}
else
{
artist.ArtistID = artistRetrieved.ArtistID;
}
song.ArtistID = artist.ArtistID;
}
public Artist UpdateArtistInDatabase(Song oldSongRecord, Song newSongRecord)
{
var oldArtistRecord = _artistContext.Artists.FirstOrDefault(art => art.Name.Equals(oldSongRecord.AlbumTitle));
var oldArtistName = oldArtistRecord.Name;
var newArtistName = newSongRecord.Artist;
if (string.IsNullOrEmpty(newArtistName) || oldArtistName.Equals(newArtistName))
{
_logger.Info("No change to the song's Artist");
return oldArtistRecord;
}
_logger.Info("Change to the song's record found");
if (oldArtistRecord.SongCount <= 1)
{
_logger.Info("Deleting artist record that no longer has any songs");
_artistContext.Remove(oldArtistRecord);
_artistContext.SaveChanges();
}
if (!(_artistContext.Artists.FirstOrDefault(art => art.Name.Equals(oldSongRecord.AlbumTitle)) != null))
{
_logger.Info("Creating new artist record");
var newArtistRecord = new Artist
{
Name = newArtistName
};
_artistContext.Add(newArtistRecord);
_artistContext.SaveChanges();
return newArtistRecord;
}
else
{
_logger.Info("Updating existing artist record");
var existingArtistRecord = _artistContext.Artists.FirstOrDefault(art => art.Name.Equals(newSongRecord.AlbumTitle));
_artistContext.Update(existingArtistRecord);
_artistContext.SaveChanges();
return existingArtistRecord;
}
}
public void DeleteArtistFromDatabase(Song song)
{
if (!(_artistContext.Artists.FirstOrDefault(art => art.Name.Equals(song.Artist)) != null))
{
_logger.Info("Cannot delete the artist record because it does not exist");
return;
}
var artist = _artistContext.Artists.FirstOrDefault(art => art.Name.Equals(song.Artist));
if (SongsOfArtist(artist) <= 1)
{
_artistContext.Remove(artist);
_artistContext.SaveChanges();
}
}
private int SongsOfArtist(Artist artist)
{
var sngContext = new SongContext(_connectionString);
var songs = sngContext.Songs.Where(sng => sng.ArtistID == artist.ArtistID).ToList();
return songs.Count;
}
#endregion
}
}
-16
View File
@@ -1,16 +0,0 @@
using System;
using Microsoft.Extensions.Configuration;
using NLog;
namespace Icarus.Controllers.Managers
{
public class BaseManager
{
#region Fields
protected static Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
protected IConfiguration _config;
protected string _connectionString;
#endregion
}
}
-172
View File
@@ -1,172 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Icarus.Constants;
using Icarus.Controllers.Utilities;
using Icarus.Database.Contexts;
using Icarus.Models;
using Icarus.Types;
namespace Icarus.Controllers.Managers
{
public class CoverArtManager : BaseManager
{
#region Fields
private string _rootCoverArtPath;
private CoverArtContext _coverArtContext;
private byte[] _stockCoverArt = null;
#endregion
#region Constructors
public CoverArtManager(IConfiguration config)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
_rootCoverArtPath = _config.GetValue<string>("CoverArtPath");
Initialize();
}
#endregion
#region Methods
public void SaveCoverArtToDatabase(ref Song song, ref CoverArt coverArt)
{
_logger.Info("Saving cover art record to the database");
_coverArtContext.Add(coverArt);
_coverArtContext.SaveChanges();
song.CoverArtID = coverArt.CoverArtID;
}
public void DeleteCoverArtFromDatabase(CoverArt coverArt)
{
_logger.Info("Attempting to delete cover art from the database");
_coverArtContext.Remove(coverArt);
_coverArtContext.SaveChanges();
}
public void DeleteCoverArt(CoverArt coverArt)
{
try
{
var stockCoverArtPath = _rootCoverArtPath + "CoverArt.png";
if (!string.Equals(stockCoverArtPath, coverArt.ImagePath,
StringComparison.CurrentCultureIgnoreCase))
{
_logger.Info("Song does not contain the stock cover art");
File.Delete(coverArt.ImagePath);
_logger.Info("Cover art deleted from the filesystem");
}
else
{
_logger.Info("Song contains the stock cover art");
_logger.Info("Will not delete from from the filesystem");
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public CoverArt SaveCoverArt(Song song)
{
try
{
var dirMgr = new DirectoryManager(_rootCoverArtPath);
var defaultExtension = ".png";
dirMgr.CreateDirectory(song);
var coverArt = new CoverArt
{
SongTitle = song.Title
};
var segment = coverArt.GenerateFilename(0);
var imagePath = dirMgr.SongDirectory + segment + defaultExtension;
coverArt.ImagePath = imagePath;
var metaData = new MetadataRetriever();
var imgBytes = metaData.RetrieveCoverArtBytes(song);
if (imgBytes != null)
{
_logger.Info("Saving cover art to the filesystem");
File.WriteAllBytes(coverArt.ImagePath, imgBytes);
}
else
{
_logger.Info("Song has no cover art, applying stock cover art");
coverArt.ImagePath = _rootCoverArtPath + $"{segment}{defaultExtension}";
metaData.UpdateCoverArt(song, coverArt);
File.WriteAllBytes(coverArt.ImagePath, _stockCoverArt);
}
return coverArt;
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
return null;
}
public CoverArt SaveCoverArt(IFormFile data, Song song)
{
var cover = new CoverArt { SongTitle = song.Title };
try
{
var dirMgr = new DirectoryManager(_rootCoverArtPath);
var defaultExtension = ".png";
dirMgr.CreateDirectory(song);
var segment = cover.GenerateFilename(0);
var imagePath = dirMgr.SongDirectory + segment + defaultExtension;
cover.ImagePath = imagePath;
using (var fileStream = new FileStream(imagePath, FileMode.Create))
{
data.CopyTo(fileStream);
}
}
catch (Exception ex)
{
_logger.Error(ex.Message, "An error occurred");
}
return cover;
}
public CoverArt GetCoverArt(Song song)
{
return _coverArtContext.CoverArtImages.FirstOrDefault(cov => cov.SongTitle.Equals(song.Title));
}
private void Initialize()
{
_coverArtContext = new CoverArtContext(_connectionString);
if (System.IO.File.Exists(DirectoryPaths.CoverArtPath))
_stockCoverArt = File.ReadAllBytes(DirectoryPaths.CoverArtPath);
if (!File.Exists(_rootCoverArtPath + "CoverArt.png"))
{
File.WriteAllBytes(_rootCoverArtPath + "CoverArt.png",
_stockCoverArt);
Console.WriteLine("Copied Stock Cover Art");
}
}
#endregion
}
}
-232
View File
@@ -1,232 +0,0 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Icarus.Models;
using Icarus.Types;
namespace Icarus.Controllers.Managers
{
// NOTE: Do not use metadata for the song's metadata
public class DirectoryManager : BaseManager
{
#region Fields
private Song _song;
private string _rootSongDirectory;
private string _songDirectory;
#endregion
#region Properties
public string SongDirectory
{
get => _songDirectory;
set => _songDirectory = value;
}
#endregion
#region Constructors
public DirectoryManager(IConfiguration config, Song song)
{
_config = config;
_song = song;
Initialize();
}
public DirectoryManager(IConfiguration config)
{
_config = config;
Initialize();
}
public DirectoryManager(string rootDirectory)
{
_rootSongDirectory = rootDirectory;
}
#endregion
#region Methods
public void CreateDirectory()
{
CreateDirectory(_song);
}
public void CreateDirectory(Song song)
{
_song = song;
try
{
_songDirectory = AlbumDirectory();
if (!Directory.Exists(_songDirectory))
{
Directory.CreateDirectory(_songDirectory);
Console.WriteLine($"The directory has been created");
}
Console.WriteLine($"The song will be saved in the following" +
$" directory: {_songDirectory}");
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public void DeleteEmptyDirectories()
{
try
{
var albumDirectory = AlbumDirectory();
var artistDirectory = ArtistDirectory();
if (IsDirectoryEmpty(albumDirectory))
{
Directory.Delete(albumDirectory);
Console.WriteLine($"directory {albumDirectory} deleted");
}
if (IsDirectoryEmpty(artistDirectory))
{
Directory.Delete(artistDirectory);
Console.WriteLine($"directory {artistDirectory} deleted");
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred {exMsg}");
}
}
public void DeleteEmptyDirectories(Song song)
{
try
{
var albumDirectory = AlbumDirectory(song);
var artistDirectory = ArtistDirectory(song);
if (IsDirectoryEmpty(albumDirectory))
{
Directory.Delete(albumDirectory);
_logger.Info("Album directory deleted");
}
if (IsDirectoryEmpty(artistDirectory))
{
Directory.Delete(artistDirectory);
_logger.Info("Artist directory deleted");
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public string RetrieveAlbumPath(Song song)
{
_logger.Info("Retrieving album song path");
var albumPath = string.Empty;
albumPath = AlbumDirectory(song);
return albumPath;
}
public string RetrieveArtistPath(Song song)
{
_logger.Info("Retrieving artist path");
var artistPath = string.Empty;
artistPath = ArtistDirectory(song);
return artistPath;
}
public string GenerateSongPath(Song song)
{
_logger.Info("Generating song path");
var songPath = string.Empty;
var artistPath = ArtistDirectory(song);
var albumPath = AlbumDirectory(song);
if (!Directory.Exists(artistPath))
{
_logger.Info("Artist path does not exist");
Directory.CreateDirectory(artistPath);
_logger.Info("Creating artist path");
}
if (!Directory.Exists(albumPath))
{
_logger.Info("Album path does not exist");
Directory.CreateDirectory(albumPath);
_logger.Info("Created album path");
}
songPath = albumPath;
return songPath;
}
private void Initialize(DirectoryType dirTypes = DirectoryType.Music)
{
switch (dirTypes)
{
case DirectoryType.Music:
_rootSongDirectory = _config.GetValue<string>("RootMusicPath");
break;
case DirectoryType.CoverArt:
_rootSongDirectory = _config.GetValue<string>("CoverArtPath");
break;
}
}
private bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string AlbumDirectory()
{
return AlbumDirectory(_song);
}
private string AlbumDirectory(Song song)
{
var directory = ArtistDirectory(song);
var segment = SerializeValue(song.AlbumTitle);
directory += $@"{segment}/";
Console.WriteLine($"Album directory {directory}");
return directory;
}
private string ArtistDirectory()
{
return ArtistDirectory(_song);
}
private string ArtistDirectory(Song song)
{
var directory = _rootSongDirectory;
var segment = SerializeValue(song.Artist);
directory += $@"{segment}/";
Console.WriteLine($"Artist directory {directory}");
return directory;
}
private string SerializeValue(string value)
{
const int length = 15;
const string chars = "ABCDEF0123456789";
var random = new Random();
var output = new string(Enumerable.Repeat(chars, length).Select(s =>
s[random.Next(s.Length)]).ToArray());
return output;
}
#endregion
}
}
-137
View File
@@ -1,137 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class GenreManager : BaseManager
{
#region Fields
private GenreContext _genreContext;
#endregion
#region Properties
#endregion
#region Constructors
public GenreManager(IConfiguration config)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
_genreContext = new GenreContext(_connectionString);
}
#endregion
#region Methods
public void SaveGenreToDatabase(ref Song song)
{
_logger.Info("Starting process to save the genre record of the song to the database");
var genre = new Genre
{
GenreName = song.Genre,
SongCount = 1
};
var genreName = song.Genre;
var genreRetrieved = _genreContext.Genres.FirstOrDefault(gnr => gnr.GenreName.Equals(genreName));
if (genreRetrieved == null)
{
_genreContext.Add(genre);
_genreContext.SaveChanges();
}
else
{
genre.GenreID = genreRetrieved.GenreID;
}
song.GenreID = genre.GenreID;
}
public Genre UpdateGenreInDatabase(Song oldSongRecord, Song newSongRecord)
{
var oldGenreRecord = _genreContext.Genres.FirstOrDefault(gnr => gnr.GenreName.Equals(oldSongRecord.Genre));
var oldGenreName = oldGenreRecord.GenreName;
var newGenreName = newSongRecord.Genre;
if (string.IsNullOrEmpty(newGenreName) || oldGenreName.Equals(newGenreName))
{
_logger.Info("No change to the song's Genre");
return oldGenreRecord;
}
_logger.Info("Change to the song's genre found");
if (oldGenreRecord.SongCount <= 1)
{
_logger.Info("Deleting genre record");
_genreContext.Remove(oldGenreRecord);
_genreContext.SaveChanges();
}
if (!(_genreContext.Genres.FirstOrDefault(gnr => gnr.GenreName.Equals(oldSongRecord.Genre)) != null))
{
_logger.Info("Creating new genre record");
var newGenreRecord = new Genre
{
GenreName = newGenreName
};
_genreContext.Add(newGenreRecord);
_genreContext.SaveChanges();
return newGenreRecord;
}
else
{
_logger.Info("Updating existing genre record");
var existingGenreRecord = _genreContext.Genres.FirstOrDefault(gnr => gnr.GenreName.Equals(oldGenreRecord.GenreName));
_genreContext.Update(existingGenreRecord);
_genreContext.SaveChanges();
return existingGenreRecord;
}
}
public void DeleteGenreFromDatabase(Song song)
{
if (!(_genreContext.Genres.FirstOrDefault(gnr => gnr.GenreName.Equals(song.Genre)) != null))
{
_logger.Info("Cannot delete the genre record because it does not exist");
return;
}
var genre = _genreContext.Genres.FirstOrDefault(gnr => gnr.GenreName.Equals(song.Genre));
if (SongsInGenre(genre) <= 1)
{
_genreContext.Remove(genre);
_genreContext.SaveChanges();
}
}
private int SongsInGenre(Genre genre)
{
var sngContext = new SongContext(_connectionString);
var songs = sngContext.Songs.Where(sng => sng.GenreID == genre.GenreID).ToList();
return songs.Count;
}
#endregion
}
}
-507
View File
@@ -1,507 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Data;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using NLog;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class SongManager : BaseManager
{
#region Fields
private string _tempDirectoryRoot;
private string _archiveDirectoryRoot;
private string _compressedSongFilename;
private string _message;
private SongContext _songContext;
#endregion
#region Properties
public string ArchiveDirectoryRoot
{
get => _archiveDirectoryRoot;
set => _archiveDirectoryRoot = value;
}
public string CompressedSongFilename
{
get => _compressedSongFilename;
set => _compressedSongFilename = value;
}
public string Message
{
get => _message;
set => _message = value;
}
#endregion
#region Constructors
public SongManager(IConfiguration config)
{
_config = config;
Initialize();
}
public SongManager(IConfiguration config, string tempDirectoryRoot)
{
_config = config;
_tempDirectoryRoot = tempDirectoryRoot;
Initialize();
}
#endregion
#region Methods
public SongResult UpdateSong(Song song)
{
var result = new SongResult();
if (!DoesSongExist(song))
{
result.SongTitle = song.Title;
result.Message = "Song does not exist";
return result;
}
try
{
var oldSongRecord = _songContext.RetrieveRecord(song);
song.Filename = oldSongRecord.Filename;
song.SongDirectory = oldSongRecord.SongDirectory;
MetadataRetriever updateMetadata = new MetadataRetriever();
updateMetadata.UpdateMetadata(song, oldSongRecord);
var updatedSong = updateMetadata.UpdatedSongRecord;
var albMgr = new AlbumManager(_config);
var gnrMgr = new GenreManager(_config);
var artMgr = new ArtistManager(_config);
var updatedAlbum = albMgr.UpdateAlbumInDatabase(oldSongRecord, updatedSong);
oldSongRecord.AlbumID = updatedAlbum.AlbumID;
var updatedArtist = artMgr.UpdateArtistInDatabase(oldSongRecord, updatedSong);
oldSongRecord.ArtistID = updatedArtist.ArtistID;
var updatedGenre = gnrMgr.UpdateGenreInDatabase(oldSongRecord, updatedSong);
oldSongRecord.GenreID = updatedGenre.GenreID;
UpdateSongInDatabase(ref oldSongRecord, ref updatedSong, ref result);
DeleteEmptyDirectories(ref oldSongRecord, ref updatedSong);
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
result.Message = $"An error occurred: {msg}";
result.SongTitle = song.Title;
}
return result;
}
public bool DeleteSongFromFileSystem(Song songMetaData)
{
bool successful = false;
try
{
var songPath = songMetaData.SongPath();
System.IO.File.Delete(songPath);
successful = true;
DirectoryManager dirMgr = new DirectoryManager(_config, songMetaData);
dirMgr.DeleteEmptyDirectories();
Console.WriteLine("Song successfully deleted");
}
catch (Exception ex)
{
var exMsg = ex.Message;
}
return successful;
}
public bool DoesSongExist(Song song)
{
if (!_songContext.DoesRecordExist(song))
{
return false;
}
return true;
}
public void DeleteSong(Song song)
{
try
{
if (DeleteSongFromFilesystem(song))
{
_logger.Error("Failed to delete the song");
throw new Exception("Failed to delete the song");
}
_logger.Info("Song deleted from the filesystem");
var coverMgr = new CoverArtManager(_config);
var coverArt = coverMgr.GetCoverArt(song);
coverMgr.DeleteCoverArt(coverArt);
coverMgr.DeleteCoverArtFromDatabase(coverArt);
DeleteSongFromDatabase(song);
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public async Task SaveSongToFileSystem(IFormFile songFile)
{
try
{
_logger.Info("Starting the process of saving the song to the filesystem");
var song = await SaveSongTemp(songFile);
DirectoryManager dirMgr = new DirectoryManager(_config, song);
dirMgr.CreateDirectory();
var tempPath = song.SongPath();
song.Filename = song.GenerateFilename(1);
var filePath = $"{dirMgr.SongDirectory}{song.Filename}";
_logger.Info($"Absolute song path: {filePath}");
await Task.Run(() =>
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
var songBytes = System.IO.File.ReadAllBytes(tempPath);
_logger.Info("Saving song to the filesystem");
fileStream.Write(songBytes, 0, songBytes.Count());
System.IO.File.Delete(tempPath);
_logger.Info("Deleting temp file");
_logger.Info("Song successfully saved to filesystem");
}
});
song.SongDirectory = dirMgr.SongDirectory;
var coverMgr = new CoverArtManager(_config);
var coverArt = coverMgr.SaveCoverArt(song);
coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt);
SaveSongToDatabase(song);
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public void SaveSongToFileSystem(IFormFile songFile, IFormFile coverArtData, Song song)
{
song.SongDirectory = _tempDirectoryRoot;
song.DateCreated = DateTime.Now;
if (string.IsNullOrEmpty(song.Filename))
{
song.Filename = song.GenerateFilename(1);
}
_logger.Info($"Temporary directory: {_tempDirectoryRoot}");
var tempPath = song.SongPath();
_logger.Info("Temporary song path: {0}", tempPath);
using (var filestream = new FileStream(tempPath, FileMode.Create))
{
_logger.Info("Saving song to temporary directory");
songFile.CopyTo(filestream);
}
var coverMgr = new CoverArtManager(_config);
var meta = new MetadataRetriever();
var coverArt = coverMgr.SaveCoverArt(coverArtData, song);
meta.UpdateCoverArt(song, coverArt);
song.Duration = meta.RetrieveSongDuration(song.SongPath());
meta.UpdateMetadata(song, song);
DirectoryManager dirMgr = new DirectoryManager(_config, song);
dirMgr.CreateDirectory();
song.SongDirectory = dirMgr.SongDirectory;
var filePath = song.SongPath();
_logger.Info($"Absolute song path: {filePath}");
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
var songBytes = System.IO.File.ReadAllBytes(tempPath);
try
{
if (System.IO.File.Exists(filePath) && System.IO.File.Exists(tempPath) && fileStream.Length > 0)
{
System.IO.File.Delete(tempPath);
_logger.Info("Deleted temp song from filesystem: {0}", tempPath);
}
else
{
fileStream.Write(songBytes, 0, songBytes.Count());
_logger.Info("Saved song to filesystem: {0}", filePath);
System.IO.File.Delete(tempPath);
_logger.Info("Deleted temp song from filesystem: {0}", tempPath);
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error($"An error occurred: {msg}");
}
_logger.Info("Song successfully saved to filesystem");
}
coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt);
SaveSongToDatabase(song);
}
public async Task<SongData> RetrieveSong(Song songMetaData)
{
var song = new SongData();
try
{
Console.WriteLine("Fetching song from filesystem");
song = await RetrieveSongFromFileSystem(songMetaData);
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
return song;
}
private async Task<SongData> RetrieveSongFromFileSystem(Song details)
{
byte[] uncompressedSong = await System.IO.File.ReadAllBytesAsync(details.SongPath());
return new SongData
{
Data = uncompressedSong
};
}
private async Task<Song> SaveSongTemp(IFormFile songFile)
{
var song = new Song();
_logger.Info("Assigning song filename");
song.SongDirectory = _tempDirectoryRoot;
var filename = song.GenerateFilename(1);
song.Filename = filename;
using (var filestream = new FileStream(song.SongPath(), FileMode.Create))
{
_logger.Info("Saving temp song: {0}", song.SongPath());
await songFile.CopyToAsync(filestream);
}
await Task.Run(() =>
{
MetadataRetriever meta = new MetadataRetriever();
song = meta.RetrieveMetaData(song.SongPath());
});
song.SongDirectory = _tempDirectoryRoot;
song.DateCreated = DateTime.Now;
song.Filename = filename;
return song;
}
private bool SongRecordChanged(Song currentSong, Song songUpdates)
{
var currentTitle = currentSong.Title;
var currentArtist = currentSong.Artist;
var currentAlbum = currentSong.AlbumTitle;
var currentGenre = currentSong.Genre;
var currentYear = currentSong.Year;
if (!currentTitle.Equals(songUpdates.Title) || !currentArtist.Equals(songUpdates.Artist) ||
!currentAlbum.Equals(songUpdates.AlbumTitle) ||
!currentGenre.Equals(songUpdates.Genre) || currentYear != songUpdates.Year)
return true;
return false;
}
private void DeleteEmptyDirectories(ref Song oldSong, ref Song updatedSong)
{
DirectoryManager mgr = new DirectoryManager(_config);
_logger.Info("Checking to see if there are any directories to delete");
mgr.DeleteEmptyDirectories(oldSong);
}
private void Initialize()
{
try
{
_connectionString = _config.GetConnectionString("DefaultConnection");
_songContext = new SongContext(_connectionString);
}
catch (Exception ex)
{
Console.WriteLine($"Error Occurred: {ex.Message}");
}
}
private void SaveSongToDatabase(Song song)
{
_logger.Info("Starting process to save the song to the database");
var albumMgr = new AlbumManager(_config);
var artistMgr = new ArtistManager(_config);
var genreMgr = new GenreManager(_config);
albumMgr.SaveAlbumToDatabase(ref song);
artistMgr.SaveArtistToDatabase(ref song);
genreMgr.SaveGenreToDatabase(ref song);
var info = "Saving Song to DB";
_logger.Info(info);
_songContext.Add(song);
_songContext.SaveChanges();
}
private bool DeleteSongFromFilesystem(Song song)
{
var songPath = song.SongPath();
_logger.Info("Deleting song from the filesystem");
try
{
System.IO.File.Delete(songPath);
}
catch(Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred when attempting to delete the song from the filesystem");
return false;
}
return DoesSongExistOnFilesystem(song);
}
private bool DoesSongExistOnFilesystem(Song song)
{
if (!System.IO.File.Exists(song.SongPath()))
{
_logger.Info("Song does not exist on the filesystem");
return false;
}
_logger.Info("Song exists on the filesystem");
return true;
}
private void UpdateSongInDatabase(ref Song oldSongRecord, ref Song newSongRecord, ref SongResult result)
{
var updatedSongRecord = oldSongRecord;
var songContext = new SongContext(_connectionString);
if (!SongRecordChanged(oldSongRecord, newSongRecord))
{
_logger.Info("No change to the song record");
return;
}
_logger.Info("Changes to song record found");
if (!string.IsNullOrEmpty(newSongRecord.Title))
updatedSongRecord.Title = newSongRecord.Title;
if (!string.IsNullOrEmpty(newSongRecord.AlbumTitle))
{
updatedSongRecord.AlbumTitle = newSongRecord.AlbumTitle;
}
if (!string.IsNullOrEmpty(newSongRecord.Artist))
{
updatedSongRecord.Artist = newSongRecord.Artist;
}
if (!string.IsNullOrEmpty(newSongRecord.Genre))
{
updatedSongRecord.Genre = newSongRecord.Genre;
Console.WriteLine("Genre changed");
Console.WriteLine($"{updatedSongRecord.Genre} {newSongRecord.Genre}");
}
if (newSongRecord.Year != null || newSongRecord.Year > 0)
updatedSongRecord.Year = newSongRecord.Year;
_logger.Info("Applied changes to song record");
_logger.Info("Saving song metadata to the database");
songContext.Update(updatedSongRecord);
songContext.SaveChanges();
newSongRecord = updatedSongRecord;
result.Message = "Successfully updated song";
result.SongTitle = updatedSongRecord.Title;
}
private void DeleteSongFromDatabase(Song song)
{
_logger.Info("Starting process to delete records related to the song from the database");
var albumMgr = new AlbumManager(_config);
var artistMgr = new ArtistManager(_config);
var genreMgr = new GenreManager(_config);
albumMgr.DeleteAlbumFromDatabase(song);
artistMgr.DeleteArtistFromDatabase(song);
genreMgr.DeleteGenreFromDatabase(song);
var sngContext = new SongContext(_connectionString);
sngContext.Songs.Remove(song);
sngContext.SaveChanges();
}
#endregion
}
}
-410
View File
@@ -1,410 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using JWT;
using JWT.Serializers;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using RestSharp;
using Icarus.Models;
namespace Icarus.Controllers.Managers
{
#region Classes
public class TokenManager : BaseManager
{
#region Fields
private string _clientId;
private string _clientSecret;
private string _privateKeyPath = string.Empty;
private string _privateKey = string.Empty;
private string _publicKeyPath = string.Empty;
private string _publicKey = string.Empty;
private string _audience;
private string _grantType;
private string _url;
#endregion
#region Properties
#endregion
#region Constructors
public TokenManager(IConfiguration config)
{
_config = config;
InitializeValues();
}
#endregion
#region Methods
public LoginResult RetrieveLoginResult(User user)
{
_logger.Info("Preparing Auth0 API request");
var client = new RestClient(_url);
var request = new RestRequest("oauth/token", Method.POST);
var tokenRequest = RetrieveTokenRequest();
_logger.Info("Serializing token object into JSON");
var tokenObject = JsonConvert.SerializeObject(tokenRequest);
request.AddParameter("application/json; charset=utf-8",
tokenObject, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
_logger.Info("Sending request");
IRestResponse response = client.Execute(request);
_logger.Info("Response received");
_logger.Info("Deserializing response");
var tokenResult = JsonConvert
.DeserializeObject<TokenTierOne>(response.Content);
_logger.Info("Response deserialized");
return new LoginResult
{
UserID = user.UserID, Username = user.Username, Token = tokenResult.AccessToken,
TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration,
Message = "Successfully retrieved token"
};
}
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
public LoginResult LogIn(User user)
{
var tokenResult = new TokenTierOne();
tokenResult.TokenType = "Jwt";
var privateKey = ReadKeyContent(_privateKeyPath).Result;
var publicKey = ReadKeyContent(_publicKeyPath).Result;
var payload = Payload();
var token = CreateToken(payload, privateKey);
tokenResult.AccessToken = token;
var expClaim = payload.FirstOrDefault(cl =>
{
return cl.Type.Equals("exp");
});
tokenResult.Expiration = System.Convert.ToInt32(expClaim.Value);
return new LoginResult
{
UserID = user.UserID, Username = user.Username, Token = tokenResult.AccessToken,
TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration,
Message = "Successfully retrieved token"
};
}
public LoginResult LoginSymmetric(User user)
{
var tokenResult = new TokenTierOne();
tokenResult.TokenType = "Jwt";
var payload = Payload();
payload.Add(new System.Security.Claims.Claim("user_id", user.UserID.ToString(), ClaimValueTypes.Integer));
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["JWT:Secret"]));
var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
_config["JWT:Issuer"],
_config["JWT:Audience"],
payload,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: signIn);
tokenResult.AccessToken = new JwtSecurityTokenHandler().WriteToken(token);
var expClaim = payload.FirstOrDefault(cl =>
{
return cl.Type.Equals("exp");
});
var expiredDate = DateTime.Parse(expClaim.Value);
var exp = Math.Floor((expiredDate - DateTime.UnixEpoch).TotalSeconds);
tokenResult.Expiration = Convert.ToInt32(exp);
return new LoginResult
{
UserID = user.UserID, Username = user.Username, Token = tokenResult.AccessToken,
TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration,
Message = "Successfully retrieved token"
};
}
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
public bool IsTokenValid(string scope, string accessToken)
{
var result = false;
var token = DecodeToken(accessToken);
if (token == null || token.Erroneous())
{
return result;
}
result = (!token.TokenExpired() && token.ContainsScope(scope)) ? true : false;
// What would make a token valid?
// 1. The expiration date must be before the current date
// 2. The desired scope must be part of the scopes within the access token
// 3. Must be able to be decoded
return result;
}
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
public Token DecodeToken(string accessToken)
{
var rsaParams = GetRSAPublic(_publicKey);
Token tok = null;
try
{
using (var rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(rsaParams);
IJsonSerializer serializer = new JsonNetSerializer();
IDateTimeProvider provider = new UtcDateTimeProvider();
IJwtValidator validator = new JwtValidator(serializer, provider);
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
var algorithm = new JWT.Algorithms.RS256Algorithm(rsa);
IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder, algorithm);
var json = decoder.Decode(accessToken);
tok = JsonConvert.DeserializeObject<Token>(json);
}
}
catch (Exception ex)
{
_logger.Error("An error occurred: {0}", ex.Message);
}
return tok;
}
private string AllScopes()
{
var allScopes = new List<String>()
{
"download:songs",
"read:song_details",
"upload:songs",
"delete:songs",
"read:albums",
"read:artists",
"update:songs",
"stream:songs",
"read:genre",
"read:year",
"download:cover_art"
};
var scopes = string.Empty;
for (var i = 0; i < allScopes.Count; i++)
{
if (i == allScopes.Count - 1)
{
scopes += allScopes[i];
}
else
{
scopes += allScopes[i] + " ";
}
}
return scopes;
}
private List<Claim> Payload()
{
var expLimit = 30;
var currentDate = DateTime.Now;
var expiredDate = currentDate.AddMinutes(expLimit);
var issued = Math.Floor((currentDate - DateTime.UnixEpoch).TotalSeconds);
var expires = Math.Floor((expiredDate - DateTime.UnixEpoch).TotalSeconds);
var issuer = "https://soaricarus.auth0.com";
issuer = "http://localhost:5002";
var audience = "https://icarus/api";
audience = "http://localhost:5002";
var subject = _config["JWT:Subject"];
var claim = new List<System.Security.Claims.Claim>()
{
new System.Security.Claims.Claim("scope", AllScopes(), "string"),
new System.Security.Claims.Claim(JwtRegisteredClaimNames.Exp, expiredDate.ToString()),
new System.Security.Claims.Claim(JwtRegisteredClaimNames.Aud, audience),
new System.Security.Claims.Claim(JwtRegisteredClaimNames.Iss, issuer),
new Claim(JwtRegisteredClaimNames.Sub, subject),
new System.Security.Claims.Claim(JwtRegisteredClaimNames.Iat, currentDate.ToString())
};
return claim;
}
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
private string CreateToken(List<Claim> claims, string privateKey)
{
var token = string.Empty;
if (string.IsNullOrEmpty(privateKey))
{
privateKey = ReadKeyContent(_privateKeyPath).Result;
}
RSAParameters rsaParams;
using (var tr = new System.IO.StringReader(privateKey))
{
var pemReader = new PemReader(tr);
var keyPair = pemReader.ReadObject() as AsymmetricCipherKeyPair;
if (keyPair == null)
{
throw new Exception("Could not read RSA private key");
}
var privateRsaParams = keyPair.Private as RsaPrivateCrtKeyParameters;
rsaParams = DotNetUtilities.ToRSAParameters(privateRsaParams);
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
var rsaParamsPublic = GetRSAPublic(ReadKeyContent(_publicKeyPath).Result);
var rsaPublic = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParams);
rsaPublic.ImportParameters(rsaParamsPublic);
Dictionary<string, object> payload = new Dictionary<string, object>();
foreach (var claim in claims)
{
var type = claim.Type;
var val = Int32.TryParse(claim.Value, out _);
if (val)
{
payload.Add(type, Convert.ToInt32(claim.Value));
}
else
{
payload.Add(type, claim.Value);
}
}
var algorithm = new JWT.Algorithms.RS256Algorithm(rsaPublic, rsa);
IJsonSerializer serializer = new JsonNetSerializer();
IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
IJwtEncoder encoder = new JwtEncoder(algorithm, serializer, urlEncoder);
token = encoder.Encode(payload, privateKey);
}
return token;
}
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
private RSAParameters GetRSAPublic(string publicKey)
{
using (var tr = new System.IO.StringReader(publicKey))
{
var pemReader = new PemReader(tr);
var publicKeyParams = pemReader.ReadObject() as RsaKeyParameters;
if (publicKeyParams == null)
{
throw new Exception("Could not read RSA public key");
}
return DotNetUtilities.ToRSAParameters(publicKeyParams);
}
}
private async Task<string> ReadKeyContent(string filepath)
{
return await System.IO.File.ReadAllTextAsync(filepath);
}
private TokenRequest RetrieveTokenRequest()
{
_logger.Info("Retrieving token object");
return new TokenRequest
{
ClientId = _clientId, ClientSecret = _clientSecret,
Audience = _audience, GrantType = _grantType
};
}
private void InitializeValues()
{
_logger.Info("Analyzing Auth0 information");
_clientId = _config["Auth0:ClientId"];
_clientSecret = _config["Auth0:ClientSecret"];
_audience = _config["Auth0:ApiIdentifier"];
_grantType = "client_credentials";
_url = $"https://{_config["Auth0:Domain"]}";
}
#region Testing Methods
// For testing purposes
private void PrintCredentials()
{
Console.WriteLine("Auth0 credentials:");
Console.WriteLine($"Client Id: {_clientId}");
Console.WriteLine($"Client Secret: {_clientSecret}");
Console.WriteLine($"Audience: {_audience}");
Console.WriteLine($"Url: {_url}");
}
#endregion
#endregion
#region Classes
private class TokenRequest
{
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("grant_type")]
public string GrantType { get; set; }
}
private class TokenTierOne
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int Expiration { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
}
#endregion
}
#endregion
}
-345
View File
@@ -1,345 +0,0 @@
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using NLog;
using TagLib;
using Icarus.Models;
namespace Icarus.Controllers.Utilities
{
public class MetadataRetriever
{
#region Fields
private static NLog.Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
private Song _updatedSong;
private string _message;
private string _title;
private string _artist;
private string _album;
private string _genre;
private int _year;
private int _duration;
#endregion
#region Properties
public Song UpdatedSongRecord
{
get => _updatedSong;
set => _updatedSong = value;
}
public string Message
{
get => _message;
set => _message = value;
}
#endregion
#region Constructors
#endregion
#region Methods
public static void PrintMetadata(Song song)
{
Console.WriteLine("\n\nMetadata of the song:");
Console.WriteLine($"ID: {song.SongID}");
Console.WriteLine($"Title: {song.Title}");
Console.WriteLine($"Artist: {song.Artist}");
Console.WriteLine($"Album: {song.AlbumTitle}");
Console.WriteLine($"Genre: {song.Genre}");
Console.WriteLine($"Year: {song.Year}");
Console.WriteLine($"Duration: {song.Duration}");
Console.WriteLine($"AlbumID: {song.AlbumID}");
Console.WriteLine($"ArtistID: {song.ArtistID}");
Console.WriteLine($"GenreID: {song.GenreID}");
Console.WriteLine($"Song Path: {song.SongPath()}");
Console.WriteLine($"Filename: {song.Filename}");
Console.WriteLine("\n");
_logger.Info("Metadata of the song");
_logger.Info($"Title: {song.Title}");
_logger.Info($"Artist: {song.Artist}");
_logger.Info($"Album: {song.AlbumTitle}");
_logger.Info($"Genre: {song.Genre}");
_logger.Info($"Year: {song.Year}");
_logger.Info($"Duration: {song.Duration}");
}
public Song RetrieveMetaData(string filePath)
{
Song song = new Song();
try
{
TagLib.File fileTag = TagLib.File.Create(filePath);
_title = fileTag.Tag.Title;
_artist = string.Join("", fileTag.Tag.Performers);
_album = fileTag.Tag.Album;
_genre = string.Join("", fileTag.Tag.Genres);
_year = (int)fileTag.Tag.Year;
_duration = (int)fileTag.Properties.Duration.TotalSeconds;
var albumArtist = string.Join("", fileTag.Tag.AlbumArtists);
var track = (int)fileTag.Tag.Track;
var disc = (int)fileTag.Tag.Disc;
song.Title = _title;
song.Artist = _artist;
song.AlbumTitle = _album;
song.AlbumArtist = albumArtist;
song.Genre = _genre;
song.Year = _year;
song.Duration = _duration;
song.Track = track;
song.Disc = disc;
song.TrackCount = (int)fileTag.Tag.TrackCount;
song.DiscCount = (int)fileTag.Tag.DiscCount;
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine("An error occurred in MetadataRetriever");
Console.WriteLine(msg);
_logger.Error(msg, "An error occurred in MetadataRetriever");
}
return song;
}
public int RetrieveSongDuration(string filepath)
{
var duration = 0;
var fileTag = TagLib.File.Create(filepath);
duration = (int)fileTag.Properties.Duration.TotalSeconds;
return duration;
}
public byte[] RetrieveCoverArtBytes(Song song)
{
try
{
Console.WriteLine("Fetching image");
var tag = TagLib.File.Create(song.SongPath());
byte[] imgBytes = tag.Tag.Pictures[0].Data.Data;
return imgBytes;
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred in MetadataRetriever");
}
return null;
}
public void UpdateMetadata(Song updatedSong, Song oldSong)
{
try
{
InitializeUpdatedSong(oldSong);
var songValues = CheckSongValues(updatedSong);
PerformUpdate(updatedSong, songValues);
Message = "Successfully updated metadata";
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: {msg}");
_logger.Error(msg, "An error occurred");
Message = "Failed to update metadata";
}
}
public void UpdateCoverArt(Song song, CoverArt coverArt)
{
Console.WriteLine("Updating song's cover art");
var tag = TagLib.File.Create(song.SongPath());
var pics = tag.Tag.Pictures;
Array.Resize(ref pics, 1);
pics[0] = new Picture(coverArt.ImagePath)
{
Description = "Cover Art"
};
tag.Tag.Pictures = pics;
tag.Save();
}
private void PerformUpdate(Song updatedSong, SortedDictionary<string, bool> checkedValues)
{
var filePath = updatedSong.SongPath();
var title = updatedSong.Title;
var artist = updatedSong.Artist;
var album = updatedSong.AlbumTitle;
var genre = updatedSong.Genre;
var year = updatedSong.Year;
var albumArtist = updatedSong.AlbumArtist;
var track = updatedSong.Track;
var trackCount = updatedSong.TrackCount;
var disc = updatedSong.Disc;
var discCount = updatedSong.DiscCount;
TagLib.File fileTag = TagLib.File.Create(filePath);
try
{
Console.WriteLine($"Updating metadata of {title}");
_logger.Info($"Updating metadata of {title}");
foreach (var key in checkedValues.Keys)
{
bool result = checkedValues[key];
if (!result)
switch (key.ToLower())
{
case "title":
_updatedSong.Title = title;
fileTag.Tag.Title = title;
break;
case "artists":
_updatedSong.Artist = artist;
fileTag.Tag.Performers = new []{artist};
break;
case "album":
_updatedSong.AlbumTitle = album;
fileTag.Tag.Album = album;
break;
case "genre":
_updatedSong.Genre = genre;
fileTag.Tag.Genres = new []{genre};
break;
case "year":
_updatedSong.Year = year;
fileTag.Tag.Year = (uint)year;
break;
case "albumartist":
_updatedSong.AlbumArtist = albumArtist;
fileTag.Tag.AlbumArtists = new []{albumArtist};
break;
case "track":
_updatedSong.Track = track;
fileTag.Tag.Track = (uint)(track);
break;
case "trackcount":
_updatedSong.TrackCount = trackCount;
fileTag.Tag.TrackCount = (uint)(trackCount);
break;
case "disc":
_updatedSong.Disc = disc;
fileTag.Tag.Disc = (uint)(disc);
break;
case "disccount":
_updatedSong.DiscCount = discCount;
fileTag.Tag.DiscCount = (uint)(discCount);
break;
}
}
fileTag.Save();
Console.WriteLine("Successfully updated metadata");
_logger.Info("Successfully updated metadata");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred:\n{msg}");
_logger.Error(msg, "An error occurred");
}
}
private void InitializeUpdatedSong(Song song)
{
_updatedSong = song;
}
private void PrintMetadata()
{
Console.WriteLine("\n\nMetadata of the song:");
Console.WriteLine($"Title: {_title}");
Console.WriteLine($"Artist: {_artist}");
Console.WriteLine($"Album: {_album}");
Console.WriteLine($"Genre: {_genre}");
Console.WriteLine($"Year: {_year}");
Console.WriteLine($"Duration: {_duration}\n\n");
_logger.Info("Metadata of the song");
_logger.Info($"Title: {_title}");
_logger.Info($"Artist: {_artist}");
_logger.Info($"Album: {_album}");
_logger.Info($"Genre: {_genre}");
_logger.Info($"Year: {_year}");
_logger.Info($"Duration: {_duration}");
}
private void PrintMetadata(Song song, string message)
{
Console.WriteLine($"\n\n{message}");
Console.WriteLine($"Title: {song.Title}");
Console.WriteLine($"Artist: {song.Artist}");
Console.WriteLine($"Album: {song.AlbumTitle}");
Console.WriteLine($"Genre: {song.Genre}");
Console.WriteLine($"Year: {song.Year}");
Console.WriteLine($"Duration: {song.Duration}\n\n");
_logger.Info(message);
_logger.Info($"Title: {_title}");
_logger.Info($"Artist: {_artist}");
_logger.Info($"Album: {_album}");
_logger.Info($"Genre: {_genre}");
_logger.Info($"Year: {_year}");
_logger.Info($"Duration: {_duration}");
}
private SortedDictionary<string, bool> CheckSongValues(Song song)
{
var songValues = new SortedDictionary<string, bool>();
Console.WriteLine("Checking for null data");
_logger.Info("Checking for null data");
try
{
songValues["Title"] = String.IsNullOrEmpty(song.Title);
songValues["Artists"] = String.IsNullOrEmpty(song.Artist);
songValues["Album"] = String.IsNullOrEmpty(song.AlbumTitle);
songValues["Genre"] = String.IsNullOrEmpty(song.Genre);
songValues["AlbumArtist"] = String.IsNullOrEmpty(song.AlbumArtist);
songValues["Year"] = CheckIntField(song.Year);
songValues["Track"] = CheckIntField(song.Track);
songValues["TrackCount"] = CheckIntField(song.TrackCount);
songValues["Disc"] = CheckIntField(song.Disc);
songValues["DiscCount"] = CheckIntField(song.Disc);
Console.WriteLine("Checking for null data completed");
_logger.Info("Checking for null data completed");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: \n{msg}");
_logger.Error(msg, "An error occurred");
}
return songValues;
}
private bool CheckIntField(int? value)
{
if (value == null)
{
return true;
}
else if (value == 0)
{
return true;
}
return false;
}
#endregion
}
}
-90
View File
@@ -1,90 +0,0 @@
using System;
using System.Security.Cryptography;
using BCrypt.Net;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using NLog;
using Icarus.Models;
namespace Icarus.Controllers.Utilities
{
public class PasswordEncryption
{
#region Fields
private static Logger _logger = NLog.LogManager.GetCurrentClassLogger();
#endregion
#region Properties
#endregion
#region Constructor
#endregion
#region Methods
public bool VerifyPassword(User user, string password)
{
try
{
var result = BCrypt.Net.BCrypt.Verify(password, user.Password);
return result;
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
return false;
}
public string HashPassword(User user)
{
try
{
string hashedPassword = string.Empty;
hashedPassword = BCrypt.Net.BCrypt.HashPassword(user.Password);
_logger.Info("Successfully hashed password");
return hashedPassword;
}
catch (Exception ex)
{
var exMsg = ex.Message;
_logger.Error(exMsg, "An error occurred");
}
return null;
}
string GenerateHash(string password, byte[] salt)
{
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password, salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256/8));
return hashed;
}
byte[] GenerateSalt()
{
byte[] salt = new byte[128/8];
using (var rng = RandomNumberGenerator.Create())
rng.GetBytes(salt);
return salt;
}
#endregion
}
}
-130
View File
@@ -1,130 +0,0 @@
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Ionic.Zip;
using Icarus.Models;
namespace Icarus.Controllers.Utilities
{
public class SongCompression
{
#region Fields
string _compressedSongFilename;
string _tempDirectory;
byte[] _uncompressedSong;
#endregion
#region Propterties
public string CompressedSongFilename
{
get => _compressedSongFilename;
set => _compressedSongFilename = value;
}
#endregion
#region Constructors
public SongCompression()
{
}
public SongCompression(string tempDirectory)
{
_tempDirectory = tempDirectory;
}
public SongCompression(byte[] uncompressedSong)
{
_uncompressedSong = uncompressedSong;
}
#endregion
#region Methods
public async Task<SongData> RetrieveCompressedSong(Song song)
{
SongData songData = new SongData();
try
{
var archivePath = RetrieveCompressesSongPath(song);
Console.WriteLine($"Compressed song saved to: {archivePath}");
songData.Data = await System.IO.File.ReadAllBytesAsync(archivePath);
}
catch(Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error ocurred: \n{exMsg}");
}
return songData;
}
public string RetrieveCompressesSongPath(Song songDetails)
{
string tmpZipFilePath = _tempDirectory + songDetails.Filename;
try
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile(songDetails.SongPath());
zip.Save(tmpZipFilePath);
}
Console.WriteLine("Successfully compressed");
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine("An error ocurred");
Console.WriteLine(exMsg);
}
if (songDetails.Filename.Contains(".mp3"))
{
_compressedSongFilename = StripMP3Extension(songDetails.Filename);
}
return tmpZipFilePath;
}
// Method not being used
public byte[] CompressedSong(byte[] uncompressedSong)
{
byte[] compressedSong = null;
try
{
Console.WriteLine("Song has been successfully compressed");
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine("An error ocurred:");
Console.WriteLine(exMsg);
}
return compressedSong;
}
string StripMP3Extension(string filename)
{
Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1;
var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4);
stripped += ".zip";
Console.WriteLine($"After {stripped}");
return stripped;
}
#endregion
}
}
-77
View File
@@ -1,77 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/album")]
[ApiController]
[Authorize]
public class AlbumController : BaseController
{
#region Fields
private readonly ILogger<AlbumController> _logger;
private string _connectionString;
#endregion
#region Properties
#endregion
#region Constructors
public AlbumController(ILogger<AlbumController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region HTTP Routes
[HttpGet]
public IActionResult GetAlbums()
{
List<Album> albums = new List<Album>();
var albumContext = new AlbumContext(_connectionString);
albums = albumContext.Albums.ToList();
if (albums.Count > 0)
return Ok(albums);
else
return NotFound();
}
[HttpGet("{id}")]
public IActionResult GetAlbum(int id)
{
Album album = new Album
{
AlbumID = id
};
var albumContext = new AlbumContext(_connectionString);
if (albumContext.DoesRecordExist(album))
{
album = albumContext.RetrieveRecord(album);
return Ok(album);
}
else
return NotFound();
}
#endregion
}
}
-74
View File
@@ -1,74 +0,0 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/artist")]
[ApiController]
[Authorize]
public class ArtistController : BaseController
{
#region Fields
private readonly ILogger<ArtistController> _logger;
private string _connectionString;
#endregion
#region Properties
#endregion
#region Constructors
public ArtistController(ILogger<ArtistController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region HTTP Routes
[HttpGet]
public IActionResult GetArtists()
{
var artistContext = new ArtistContext(_connectionString);
var artists = artistContext.Artists.ToList();
if (artists.Count > 0)
return Ok(artists);
else
return NotFound();
}
[HttpGet("{id}")]
public IActionResult GetArtist(int id)
{
Artist artist = new Artist
{
ArtistID = id
};
var artistContext = new ArtistContext(_connectionString);
if (artistContext.DoesRecordExist(artist))
{
artist = artistContext.RetrieveRecord(artist);
return Ok(artist);
}
else
return NotFound();
}
#endregion
}
}
-53
View File
@@ -1,53 +0,0 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Managers;
namespace Icarus.Controllers.V1
{
public class BaseController : ControllerBase
{
#region Fiends
protected IConfiguration _config;
#endregion
#region Methods
[ApiExplorerSettings(IgnoreApi = true)]
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
protected string ParseBearerTokenFromHeader()
{
var token = string.Empty;
const string tokenType = "Bearer";
const string otherTokenType = "Jwt";
var req = Request;
var auth = req.Headers.Authorization;
var val = auth.ToString();
if ((val.Contains(tokenType) || val.Contains(otherTokenType)) && val.Split(" ").Count() > 1)
{
var split = val.Split(" ");
token = split[1];
}
return token;
}
[ApiExplorerSettings(IgnoreApi = true)]
[Obsolete("Asymmetric key signing for tokens have been deprecated")]
protected bool IsTokenValid(string scope)
{
var token = ParseBearerTokenFromHeader();
var tokMgr = new TokenManager(_config);
return tokMgr.IsTokenValid(scope, token);
}
#endregion
}
}
-83
View File
@@ -1,83 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Controllers.Managers;
using Icarus.Database.Contexts;
using Icarus.Models;
namespace Icarus.Controllers.V1
{
[Route("api/v1/coverart")]
[ApiController]
[Authorize]
public class CoverArtController : BaseController
{
#region Fields
private readonly ILogger<CoverArtController> _logger;
private string _connectionString;
#endregion
#region Constructors
public CoverArtController(ILogger<CoverArtController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region HTTP Routes
[HttpGet]
public IActionResult GetCoverArts()
{
var coverArtContext = new CoverArtContext(_connectionString);
var coverArtRecords = coverArtContext.CoverArtImages.ToList();
if (coverArtRecords == null)
{
_logger.LogInformation("No cover art records");
return NotFound();
}
else
{
_logger.LogInformation("Found cover art records");
return Ok(coverArtRecords);
}
}
[HttpGet("{id}")]
public IActionResult GetCoverArt(int id)
{
var coverArt = new CoverArt { CoverArtID = id };
var coverArtContext = new CoverArtContext(_connectionString);
coverArt = coverArtContext.RetrieveRecord(coverArt);
if (coverArt != null)
{
_logger.LogInformation("Found cover art record");
var coverArtBytes = System.IO.File.ReadAllBytes(
coverArt.ImagePath);
return File(coverArtBytes, "application/x-msdownload",
coverArt.SongTitle);
}
else
{
_logger.LogInformation("Cover art not found");
return NotFound();
}
}
#endregion
}
}
-77
View File
@@ -1,77 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/genre")]
[ApiController]
[Authorize]
public class GenreController : BaseController
{
#region Fields
private readonly ILogger<GenreController> _logger;
private string _connectionString;
#endregion
#region Properties
#endregion
#region Constructors
public GenreController(ILogger<GenreController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region HTTP Routes
[HttpGet]
public IActionResult GetGenres()
{
var genres = new List<Genre>();
var genreStore = new GenreContext(_connectionString);
genres = genreStore.Genres.ToList();
if (genres.Count > 0)
return Ok(genres);
else
return NotFound(new List<Genre>());
}
[HttpGet("{id}")]
public IActionResult GetGenre(int id)
{
var genre = new Genre
{
GenreID = id
};
var genreStore = new GenreContext(_connectionString);
if (genreStore.DoesRecordExist(genre))
{
genre = genreStore.RetrieveRecord(genre);
return Ok(genre);
}
else
return NotFound(new Genre());
}
#endregion
}
}
-97
View File
@@ -1,97 +0,0 @@
using System;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/login")]
[ApiController]
public class LoginController : ControllerBase
{
#region Fields
private string _connectionString;
private IConfiguration _config;
private ILogger<LoginController> _logger;
#endregion
#region Properties
#endregion
#region Contructors
public LoginController(IConfiguration config, ILogger<LoginController> logger)
{
_logger = logger;
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region HTTP endpoints
[HttpPost]
public IActionResult Login([FromBody] User user)
{
var context = new UserContext(_connectionString);
_logger.LogInformation("Starting process of validating credentials");
var message = "Invalid credentials";
var password = user.Password;
var loginRes = new LoginResult
{
Username = user.Username
};
try
{
if (context.Users.FirstOrDefault(usr => usr.Username.Equals(user.Username)) != null)
{
user = context.Users.FirstOrDefault(usr => usr.Username.Equals(user.Username));
var validatePass = new PasswordEncryption();
var validated = validatePass.VerifyPassword(user, password);
if (!validated)
{
loginRes.Message = message;
_logger.LogInformation(message);
return Ok(loginRes);
}
_logger.LogInformation("Successfully validated user credentials");
TokenManager tk = new TokenManager(_config);
loginRes = tk.LoginSymmetric(user);
return Ok(loginRes);
}
else
{
loginRes.Message = message;
return NotFound(loginRes);
}
}
catch (Exception ex)
{
_logger.LogError("An error occurred: {0}", ex.Message);
_logger.LogError("Inner Exception: {0}", ex.InnerException.Message);
}
return NotFound(loginRes);
}
#endregion
}
}
View File
-85
View File
@@ -1,85 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/register")]
[ApiController]
public class RegisterController : ControllerBase
{
#region Fields
private string _connectionString;
private IConfiguration _config;
#endregion
#region Properties
#endregion
#region Constructor
public RegisterController(IConfiguration config)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
[HttpPost]
public IActionResult RegisterUser([FromBody] User user)
{
PasswordEncryption pe = new PasswordEncryption();
user.Password = pe.HashPassword(user);
user.EmailVerified = false;
user.Status = "Registered";
user.DateCreated = DateTime.Now;
UserContext context = null;
try
{
context = new UserContext(_config.GetConnectionString("DefaultConnection"));
context.Add(user);
context.SaveChanges();
}
catch (Exception ex)
{
var msg = ex.Message;
var stackTrace = ex.StackTrace;
Console.WriteLine($"An error occurred: {msg}");
}
var registerResult = new RegisterResult
{
Username = user.Username
};
if (context.Users.FirstOrDefault(sng => sng.Username.Equals(user.Username)) != null)
{
registerResult.Message = "Successful registration";
registerResult.SuccessfullyRegistered = true;
return Ok(registerResult);
}
else
{
registerResult.Message = "Registration failed";
registerResult.SuccessfullyRegistered = false;
return Ok(registerResult);
}
}
}
}
-64
View File
@@ -1,64 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/compressed/data")]
[ApiController]
[Authorize]
public class SongCompressedDataController : BaseController
{
#region Fields
private string _connectionString;
private string _songTempDir;
private string _archiveDir;
#endregion
#region Properties
#endregion
#region Constructor
public SongCompressedDataController(IConfiguration config)
{
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_archiveDir = _config.GetValue<string>("ArchivePath");
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region API Routes
[HttpGet("{id}")]
public async Task<IActionResult> DownloadCompressedSong(int id)
{
var context = new SongContext(_connectionString);
SongCompression cmp = new SongCompression(_archiveDir);
Console.WriteLine($"Archive directory root: {_archiveDir}");
Console.WriteLine("Starting process of retrieving comrpessed song");
SongData song = await cmp.RetrieveCompressedSong(context.RetrieveRecord(new Song{ SongID = id }));
return File(song.Data, "application/x-msdownload", cmp.CompressedSongFilename);
}
#endregion
}
}
-107
View File
@@ -1,107 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song")]
[ApiController]
[Authorize]
public class SongController : BaseController
{
#region Fields
private readonly ILogger<SongController> _logger;
private string _connectionString;
private SongManager _songMgr;
#endregion
#region Properties
#endregion
#region Constructor
public SongController(IConfiguration config, ILogger<SongController> logger)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
_logger = logger;
_songMgr = new SongManager(config);
}
#endregion
#region Methods
#region HTTP Endpoints
[HttpGet]
public IActionResult GetSongs()
{
List<Song> songs = new List<Song>();
Console.WriteLine("Attemtping to retrieve songs");
_logger.LogInformation("Attempting to retrieve songs");
var context = new SongContext(_connectionString);
songs = context.Songs.ToList();
if (songs.Count > 0)
return Ok(songs);
else
return NotFound();
}
[HttpGet("{id}")]
public IActionResult GetSong(int id)
{
var context = new SongContext(_connectionString);
Song song = new Song { SongID = id };
song = context.RetrieveRecord(song);
Console.WriteLine("Here");
if (song.SongID != 0)
return Ok(song);
else
return NotFound();
}
[HttpPut("{id}")]
public IActionResult UpdateSong(int id, [FromBody] Song song)
{
var context = new SongContext(_connectionString);
song.SongID = id;
Console.WriteLine("Retrieving filepath of song");
_logger.LogInformation("Retrieving filepath of song");
if (!_songMgr.DoesSongExist(song))
{
return NotFound(new SongResult
{
Message = "Song does not exist"
});
}
var songRes = _songMgr.UpdateSong(song);
return Ok(songRes);
}
#endregion
#endregion
}
}
-167
View File
@@ -1,167 +0,0 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Icarus.Controllers.Managers;
using Icarus.Models;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/data")]
[ApiController]
[Authorize]
public class SongDataController : BaseController
{
#region Fields
private string _connectionString;
private ILogger<SongDataController> _logger;
private SongManager _songMgr;
private string _songTempDir;
#endregion
#region Properties
#endregion
#region Constructor
public SongDataController(IConfiguration config, ILogger<SongDataController> logger)
{
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
_logger = logger;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_songMgr = new SongManager(config, _songTempDir);
}
#endregion
[HttpGet("download/{id}")]
public IActionResult Download(int id)
{
var songContext = new SongContext(_connectionString);
var songMetaData = songContext.RetrieveRecord(new Song { SongID = id});
var song = _songMgr.RetrieveSong(songMetaData).Result;
return File(song.Data, "application/x-msdownload", songMetaData.Filename);
}
// Assumes that the song already has metadata such as
// Title
// Artist
// Album
// Genre
// Year
// Track
// Track count
// Disc
// Disc count
// Cover art
//
[HttpPost("upload"), DisableRequestSizeLimit]
public IActionResult Upload([FromForm(Name = "file")] List<IFormFile> songData)
{
try
{
// Console.WriteLine("Uploading song...");
_logger.LogInformation("Uploading song...");
var uploads = _songTempDir;
// Console.WriteLine($"Song Root Path {uploads}");
_logger.LogInformation($"Song root path {uploads}");
foreach (var sng in songData)
if (sng.Length > 0)
{
// Console.WriteLine($"Song filename {sng.FileName}");
_logger.LogInformation($"Song filename {sng.FileName}");
_songMgr.SaveSongToFileSystem(sng).Wait();
}
return Ok();
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.LogError(msg, "An error occurred");
}
return NotFound();
}
// The client is expected to send the file, metadata, and cover art separately.
// Any metadata already on the file will be overwritten with values from the metadata
// as well as the cover art
//
[HttpPost("upload/with/data")]
public IActionResult UploadWithData([FromForm] UploadSongWithDataForm up)
{
try
{
if (up.SongData.Length > 0 && up.CoverArtData.Length > 0 && !string.IsNullOrEmpty(up.SongFile))
{
var song = Newtonsoft.Json.JsonConvert.DeserializeObject<Song>(up.SongFile);
_logger.LogInformation($"Song title: {song.Title}");
_songMgr.SaveSongToFileSystem(up.SongData, up.CoverArtData, song);
}
}
catch (Exception ex)
{
_logger.LogError(ex.Message, "An error occurred");
}
return Ok();
}
[HttpDelete("delete/{id}")]
public IActionResult DeleteSong(int id)
{
var songContext = new SongContext(_connectionString);
var songMetaData = new Song{ SongID = id };
Console.WriteLine($"Id {songMetaData.SongID}");
songMetaData = songContext.RetrieveRecord(songMetaData);
if (string.IsNullOrEmpty(songMetaData.Title))
{
_logger.LogInformation("Song does not exist");
return NotFound("Song does not exist");
}
else
{
_logger.LogInformation("Starting process of deleting song from the filesystem and database");
_songMgr.DeleteSong(songMetaData);
return Ok();
}
}
public class UploadSongWithDataForm
{
[FromForm(Name = "file")]
public IFormFile SongData { get; set; }
// NOTE: Think about making this optional and if it is not provided, use the stock cover art
[FromForm(Name = "cover")]
public IFormFile CoverArtData { get; set; }
[FromForm(Name = "metadata")]
public string SongFile { get; set; }
}
}
}
-69
View File
@@ -1,69 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Web;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Controllers.Managers;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/stream")]
[ApiController]
[Authorize]
public class SongStreamController : BaseController
{
#region Fields
private ILogger<SongStreamController> _logger;
private string _connectionString;
#endregion
#region Properties
#endregion
#region Constructor
public SongStreamController(ILogger<SongStreamController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
_connectionString = _config.GetConnectionString("DefaultConnection");
}
#endregion
#region HTTP endpoints
[HttpGet("{id}")]
public async Task<IActionResult> StreamSong(int id)
{
var context = new SongContext(_config.GetConnectionString("DefaultConnection"));
var song = context.Songs.FirstOrDefault(sng => sng.SongID == id);
var stream = new FileStream(song.SongPath(), FileMode.Open, FileAccess.Read);
stream.Position = 0;
var filename = $"{song.Title}.mp3";
_logger.LogInformation("Starting to stream song...>");
Console.WriteLine("Starting to streamsong...");
var file = await Task.Run(() => {
return File(stream, "application/octet-stream", filename);
});
return file;
}
#endregion
}
}
-37
View File
@@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class AlbumContext : DbContext
{
public DbSet<Album> Albums { get; set; }
public AlbumContext(DbContextOptions<AlbumContext> options) : base(options) { }
public AlbumContext(string connString) : base(new DbContextOptionsBuilder<AlbumContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Album>()
.ToTable("Album");
}
public Album RetrieveRecord(Album album)
{
return Albums.FirstOrDefault(alb => alb.AlbumID == album.AlbumID);
}
public bool DoesRecordExist(Album album)
{
return Albums.FirstOrDefault(alb => alb.AlbumID == album.AlbumID) != null ? true : false;
}
}
}
-39
View File
@@ -1,39 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class ArtistContext : DbContext
{
public DbSet<Artist> Artists { get; set; }
public ArtistContext(DbContextOptions<ArtistContext> options) : base (options) { }
public ArtistContext(string connString) : base(new DbContextOptionsBuilder<ArtistContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Artist>()
.ToTable("Artist");
}
public Artist RetrieveRecord(Artist artist)
{
return Artists.FirstOrDefault(arst => arst.ArtistID == artist.ArtistID);
}
public bool DoesRecordExist(Artist artist)
{
return Artists.FirstOrDefault(arst => arst.ArtistID == artist.ArtistID) != null ? true : false;
}
}
}
-37
View File
@@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class CoverArtContext : DbContext
{
public DbSet<CoverArt> CoverArtImages { get; set; }
public CoverArtContext(DbContextOptions<CoverArtContext> options) : base(options) { }
public CoverArtContext(string connString) : base(new DbContextOptionsBuilder<CoverArtContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CoverArt>()
.ToTable("CoverArt");
}
public CoverArt RetrieveRecord(CoverArt cover)
{
return CoverArtImages.FirstOrDefault(cov => cov.CoverArtID == cover.CoverArtID);
}
public bool DoesRecordExist(CoverArt cover)
{
return CoverArtImages.FirstOrDefault(cov => cov.CoverArtID == cover.CoverArtID) != null ? true : false;
}
}
}
-37
View File
@@ -1,37 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class GenreContext : DbContext
{
public DbSet<Genre> Genres { get; set; }
public GenreContext(DbContextOptions<GenreContext> options) : base(options) { }
public GenreContext(string connString) : base(new DbContextOptionsBuilder<GenreContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Genre>()
.ToTable("Genre");
}
public Genre RetrieveRecord(Genre genre)
{
return Genres.FirstOrDefault(gnr => gnr.GenreID == genre.GenreID);
}
public bool DoesRecordExist(Genre genre)
{
return Genres.FirstOrDefault(gnr => gnr.GenreID == genre.GenreID) != null ? true : false;
}
}
}
-89
View File
@@ -1,89 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class SongContext : DbContext
{
public DbSet<Song> Songs { get; set; }
public SongContext(string connString) : base(new DbContextOptionsBuilder<SongContext>()
.UseMySQL(connString).Options)
{
}
public SongContext(DbContextOptions<SongContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Song>()
.ToTable("Song");
/**
modelBuilder.Entity<Song>()
.HasOne(s => s.Album)
.WithMany(al => al.Songs)
.HasForeignKey(s => s.AlbumID)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>()
.HasOne(sa => sa.SongArtist)
.WithMany(ar => ar.Songs)
.HasForeignKey(s => s.ArtistID)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>()
.HasOne(s => s.SongGenre)
.WithMany(gnr => gnr.Songs)
.HasForeignKey(s => s.GenreID)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>()
.HasOne(s => s.SongYear)
.WithMany(yr => yr.Songs)
.HasForeignKey(s => s.YearID)
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>()
.HasOne(s => s.SongCoverArt)
.WithMany(ca => ca.Songs)
.HasForeignKey(s => s.CoverArtID)
.OnDelete(DeleteBehavior.SetNull);
*/
modelBuilder.Entity<Song>()
.Property(s => s.Year)
.IsRequired(false);
modelBuilder.Entity<Song>()
.Property(s => s.GenreID)
.IsRequired(false);
modelBuilder.Entity<Song>()
.Property(s => s.ArtistID)
.IsRequired(false);
modelBuilder.Entity<Song>()
.Property(s => s.AlbumID)
.IsRequired(false);
modelBuilder.Entity<Song>()
.Property(s => s.CoverArtID)
.IsRequired(false);
}
public Song RetrieveRecord(Song song)
{
return Songs.FirstOrDefault(sng => sng.SongID == song.SongID);
}
public bool DoesRecordExist(Song song)
{
return Songs.FirstOrDefault(sng => sng.SongID == song.SongID) != null ? true : false;
}
}
}
-53
View File
@@ -1,53 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
// using MySql.Data.EntityFrameworkCore;
// using MySql.Data;
// using MySql.Data.EntityFrameworkCore.Extensions;
// using MySql.Data.Entity;
// using MySql.Data.MySqlClient;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class UserContext : DbContext
{
public DbSet<User> Users { get; set; }
#region Constructors
public UserContext(DbContextOptions<UserContext> options) : base(options) { }
[ActivatorUtilitiesConstructor]
public UserContext(string connString) : base(new DbContextOptionsBuilder<UserContext>()
.UseMySQL(connString).Options)
{
}
#endregion
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.ToTable("User");
modelBuilder.Entity<User>()
.Property(u => u.LastLogin).IsRequired(false);
modelBuilder.Entity<User>()
.Property(u => u.DateCreated).HasDefaultValue(DateTime.Now);
}
public User RetrieveRecord(User user)
{
return Users.FirstOrDefault(usr => usr.UserID == user.UserID);
}
public bool DoesRecordExist(User user)
{
return Users.FirstOrDefault(usr => usr.UserID == user.UserID) != null ? true : false;
}
}
}
+70
View File
@@ -0,0 +1,70 @@
# Stage 1: Build the application
FROM rust:1.95 as builder
# Set the working directory inside the container
WORKDIR /usr/src/app
# Install build dependencies if needed (e.g., git for cloning)
RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config libssl3 \
ca-certificates \
openssh-client git \
&& rm -rf /var/lib/apt/lists/*
# Create .ssh/ directory for internal dependencies
RUN mkdir -p -m 0700 ~/.ssh && \
echo "Host git.kundeng.us" >> ~/.ssh/config && \
echo " User git" >> ~/.ssh/config && \
chmod 600 ~/.ssh/config
# << --- ADD HOST KEY HERE --- >>
RUN ssh-keyscan git.kundeng.us >> ~/.ssh/known_hosts
# Copy Cargo manifests
COPY Cargo.toml Cargo.lock ./
# Build *only* dependencies to leverage Docker cache
# This dummy build caches dependencies as a separate layer
RUN --mount=type=ssh mkdir src && \
echo "fn main() {println!(\"if you see this, the build broke\")}" > src/main.rs && \
cargo build --release --quiet && \
rm -rf src target/release/deps/icarus* # Clean up dummy build artifacts (replace icarus)
# Copy the actual source code
COPY src ./src
# If you have other directories like `templates` or `static`, copy them too
COPY .env ./.env
COPY migrations ./migrations
# << --- SSH MOUNT ADDED HERE --- >>
# Build *only* dependencies to leverage Docker cache
# This dummy build caches dependencies as a separate layer
# Mount the SSH agent socket for this command
RUN --mount=type=ssh \
cargo build --release --quiet
# Stage 2: Create the final, smaller runtime image
# Use a minimal base image like debian-slim or even distroless for security/size
FROM debian:trixie-slim
# Install runtime dependencies if needed (e.g., SSL certificates)
RUN apt-get update && apt-get install -y ca-certificates libssl-dev libssl3 && rm -rf /var/lib/apt/lists/*
# Set the working directory
WORKDIR /usr/local/bin
# Copy the compiled binary from the builder stage
# Replace 'icarus' with the actual name of your binary (usually the crate name)
COPY --from=builder /usr/src/app/target/release/icarus .
# Copy other necessary files like .env (if used for runtime config) or static assets
# It's generally better to configure via environment variables in Docker though
COPY --from=builder /usr/src/app/.env .
COPY --from=builder /usr/src/app/migrations ./migrations
# Expose the port your Axum app listens on (e.g., 3000 or 8000)
EXPOSE 8000
# Set the command to run your application
# Ensure this matches the binary name copied above
CMD ["./icarus"]
-37
View File
@@ -1,37 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
<Version>0.1.10</Version>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.2" />
<PackageReference Include="DotNetZip" Version="1.15.0" />
<PackageReference Include="EntityFramework" Version="6.4.4" />
<PackageReference Include="ID3" Version="0.6.0" />
<PackageReference Include="JWT" Version="9.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.1" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="6.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.8" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.8">
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="MySql.EntityFrameworkCore" Version="5.0.8" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.14.0" />
<PackageReference Include="Portable.BouncyCastle" Version="1.9.0" />
<PackageReference Include="RestSharp" Version="106.15.0" />
<PackageReference Include="SevenZip" Version="19.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
<PackageReference Include="taglib" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
<Content Include="Images/Stock/*.*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
-25
View File
@@ -1,25 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.2.32616.157
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Icarus", "Icarus.csproj", "{66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{66389DAC-0D3C-4271-BBAE-AF27FCFD28B7}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {0BE61157-7A0C-41CF-B097-71178A3F6755}
EndGlobalSection
EndGlobal
Binary file not shown.

Before

Width:  |  Height:  |  Size: 107 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 24 KiB

+1 -1
View File
@@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2021 Kun Deng Copyright (c) 2025 Kun Deng
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal
View File
-28
View File
@@ -1,28 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class Album
{
[JsonProperty("album_id")]
public int AlbumID { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("album_artist")]
[Column("Artist")]
public string AlbumArtist { get; set; }
[JsonProperty("song_count")]
[NotMapped]
public int SongCount { get; set; }
[JsonProperty("year")]
public int Year { get; set; }
[JsonIgnore]
[NotMapped]
public List<Song> Songs { get; set; }
}
}
-24
View File
@@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class Artist
{
[JsonProperty("artist_id")]
public int ArtistID { get; set; }
[JsonProperty("name")]
[Column("Artist")]
public string Name { get; set; }
[JsonProperty("song_count")]
[NotMapped]
public int SongCount { get; set; }
[JsonIgnore]
[NotMapped]
public List<Song> Songs { get; set; }
}
}
-12
View File
@@ -1,12 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class BaseResult
{
[JsonProperty("message")]
public string Message { get; set; }
}
}
-43
View File
@@ -1,43 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class CoverArt
{
#region Properties
[JsonProperty("cover_art_id")]
public int CoverArtID { get; set; }
[JsonProperty("title")]
public string SongTitle { get; set; }
[JsonIgnore]
public string ImagePath { get; set; }
[JsonIgnore]
[NotMapped]
public int SongID { get; set; }
[JsonIgnore]
[NotMapped]
public List<Song> Songs { get; set; }
#endregion
#region Methods
public string GenerateFilename(int flag)
{
const int length = 25;
const string chars = "ABCDEF0123456789";
var random = new Random();
var filename = new string(Enumerable.Repeat(chars, length).Select(s =>
s[random.Next(s.Length)]).ToArray());
var extension = ".mp3";
return (flag == 0) ? filename : $"{filename}{extension}";
}
#endregion
}
}
-23
View File
@@ -1,23 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class Genre
{
[JsonProperty("genre_id")]
public int GenreID { get; set; }
[JsonProperty("genre")]
[Column("Category")]
public string GenreName { get; set; }
[JsonProperty("song_count")]
[NotMapped]
public int SongCount { get; set; }
[JsonIgnore]
[NotMapped]
public List<Song> Songs { get; set; }
}
}
-20
View File
@@ -1,20 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class LoginResult : BaseResult
{
[JsonProperty("user_id")]
public int UserID { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("token")]
public string Token { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("expiration")]
public int Expiration { get; set; }
}
}
-14
View File
@@ -1,14 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class RegisterResult : BaseResult
{
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("successfully_registered")]
public bool SuccessfullyRegistered { get; set; }
}
}
-102
View File
@@ -1,102 +0,0 @@
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class Song
{
#region Properties
[JsonProperty("song_id")]
public int SongID { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("album")]
[Column("Album")]
public string AlbumTitle { get; set; }
[JsonProperty("artist")]
public string Artist { get; set; }
[JsonProperty("album_artist")]
public string AlbumArtist { get; set; }
[JsonProperty("year")]
public int? Year { get; set; }
[JsonProperty("genre")]
public string Genre { get; set; }
[JsonProperty("duration")]
public int Duration { get; set; }
[JsonProperty("filename")]
public string Filename { get; set; }
[JsonIgnore]
public string SongDirectory { get; set; }
[JsonProperty("track")]
public int Track { get; set; } = 0;
[JsonProperty("track_count")]
public int TrackCount { get; set; } = 0;
[JsonProperty("disc")]
public int Disc { get; set; } = 0;
[JsonProperty("disc_count")]
public int DiscCount { get; set; } = 0;
[JsonIgnore]
public int? AlbumID { get; set; }
[JsonIgnore]
public int? ArtistID { get; set; }
[JsonIgnore]
public int? GenreID { get; set; }
[JsonIgnore]
public int? CoverArtID { get; set; }
[JsonProperty("date_created")]
public DateTime DateCreated { get; set; }
#endregion
#region Constructors
#endregion
#region Methods
public string SongPath()
{
var fullPath = SongDirectory;
if (fullPath[fullPath.Length -1] != '/')
{
fullPath += "/";
}
fullPath += Filename;
return fullPath;
}
public string GenerateFilename(int flag = 0)
{
const int length = 25;
const string chars = "ABCDEF0123456789";
var random = new Random();
var filename = new string(Enumerable.Repeat(chars, length).Select(s =>
s[random.Next(s.Length)]).ToArray());
var extension = ".mp3";
return flag == 0 ? filename : $"{filename}{extension}";
}
public async Task<string> GenerateFilenameAsync(int flag = 0)
{
const int length = 25;
const string chars = "ABCDEF0123456789";
var extension = ".mp3";
var random = new Random();
var filename = await Task.Run(() =>
{
return new string(Enumerable.Repeat(chars, length).Select(s =>
s[random.Next(s.Length)]).ToArray());
});
return flag == 0 ? filename : $"{filename}{extension}";
}
#endregion
}
}
-12
View File
@@ -1,12 +0,0 @@
using System;
using System.Text;
namespace Icarus.Models
{
public class SongData
{
public int ID { get; set; }
public byte[] Data { get; set; }
public int SongID { get; set; }
}
}
-14
View File
@@ -1,14 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class SongResult
{
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("song_title")]
public string SongTitle { get; set; }
}
}
-56
View File
@@ -1,56 +0,0 @@
using System;
using System.Linq;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class Token
{
#region Properties
[JsonProperty("scope")]
public string Scope { get; set; }
[JsonProperty("exp")]
public int Expiration { get; set; }
[JsonProperty("aud")]
public string Audience { get; set; }
[JsonProperty("iss")]
public string Issuer { get; set; }
[JsonProperty("iat")]
public int Issued { get; set; }
#endregion
#region Methods
public bool TokenExpired()
{
var result = false;
var currentDate = DateTime.Now;
var currentDateInSeconds = Math.Floor((currentDate - DateTime.UnixEpoch).TotalSeconds);
result = (currentDateInSeconds >= Expiration) ? true : false;
return result;
}
public bool ContainsScope(string desiredScope)
{
var result = false;
result = Scope.Contains(desiredScope);
return result;
}
public bool Erroneous()
{
var result = true;
Func<string, bool> isEmpty = a => string.IsNullOrEmpty(a);
result = (!isEmpty(Scope) && !isEmpty(Audience) && !isEmpty(Issuer) &&
Expiration > 0 && Issued > 0) ? false : true;
return result;
}
#endregion
}
}
-57
View File
@@ -1,57 +0,0 @@
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Newtonsoft.Json;
namespace Icarus.Models
{
[Table("User")]
public class User
{
#region Properties
[JsonProperty("user_id")]
[Column("UserID")]
[Key]
public int UserID { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("phone")]
[Column("Phone")]
public string Phone { get; set; }
[JsonProperty("firstname")]
public string Firstname { get; set; }
[JsonProperty("lastname")]
public string Lastname { get; set; }
[JsonProperty("email_verified")]
[NotMapped]
public bool EmailVerified { get; set; }
[JsonProperty("date_created")]
public DateTime DateCreated { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("last_login")]
public DateTime? LastLogin { get; set; }
[JsonIgnore]
[NotMapped]
public System.Collections.Generic.IEnumerable<string> Roles { get; set; }
#endregion
#region Methods
public System.Collections.Generic.IEnumerable<System.Security.Claims.Claim> Claims()
{
var claims = new System.Collections.Generic.List<System.Security.Claims.Claim> { new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Name, Username) };
claims.AddRange(Roles.Select(role => new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, role)));
return claims;
}
#endregion
}
}
Vendored
-46
View File
@@ -1,46 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using NLog.Web;
namespace Icarus
{
public class Program
{
public static void Main(string[] args)
{
var logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
try
{
logger.Debug("init main");
CreateHostBuilder(args).Build().Run();
}
catch (Exception ex)
{
logger.Error(ex, "An error occurred");
throw;
}
finally
{
NLog.LogManager.Shutdown();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
-31
View File
@@ -1,31 +0,0 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:20781",
"sslPort": 44394
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Icarus": {
"commandName": "Project",
"launchBrowser": true,
"dotnetRuneMessage": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5002",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
+21 -135
View File
@@ -1,147 +1,33 @@
# Icarus # Icarus
Web API for the Icarus project.
Icarus is a music streaming API Server that interacts with [Mear](https://github.com/amazing-username/mear).
### Interfacing With Icarus
One can interface with Icarus the music server either by:
* [Mear](https://github.com/amazing-username/mear) - Partially implemented (under development)
* [IcarusDownloadManager](https://github.com/amazing-username/IcarusDownloadManager)
## Built With ### Requires
`icarus_auth` v0.7.x
`songparser` v0.5.x
* C# [.NET](https://dotnet.microsoft.com/) 6 ### Compatible with
* [MySql](https://www.nuget.org/packages/MySql.Data/) `icarus-dm` v0.9.x
* OpenSSL
* BCrypt.Net-Next
* DotNetZip
* ID3
* JWT
* Microsoft.AspNetCore.Authentication.JwtBearer
* Microsoft.AspNetCore.Mvc.NewtonsoftJson
* Microsoft.EntityFrameworkCore
* Microsoft.EntityFrameworkCore.Tools
* MySql.EntityFrameworkCore
* [Newtonsoft.Json](https://www.newtonsoft.com/json)
* NLog.Web.AspNetCpre
* Portable.BouncyCastle
* RestSharp
* SevenZip
* System.IdentityModel.Tokens.Jwt
* [TagLib#](https://github.com/mono/taglib-sharp)
## Getting Started
Quickest way to get started is with docker. Make sure `icarus_auth` and `songparser` repositories
are located in the root of the parent directory. Check the respective repositories to ensure they
are setup correctly before configuring `Icarus`.
## Getting started Copy the `.env.docker.sample` file to `.env`. Ensure that the `ROOT_DIRECTORY` variable is populated
and exists on the docker image's filesystem. The credentials for the database doesn't need to be
changed for development, but if deploying it, it should be modified.
There are several things that need to be completed to properly setup and secure the API. Build containers
This API uses OpenAPI Specification 3.0. After configuring the API, launch the software ```
and navigate your browser to https://localhost:5001/swagger to view the endpoints. docker compose build --ssh default
1. JWT Information
2. API filesystem paths
3. Database connection string
4. Migrations
### JWT Information
Configure JWT information. Notably the Secret
```Json
"JWT": {
"Issuer": "IcarusAPI",
"Audience": "IcarusAPIClient",
"Secret": "Manaiswhatyouthinkitis",
"Subject": "Authorization"
},
``` ```
Bring it up
Replace [domain] with the domain name that represent's your domain. Replace [identifier] with the identifer root name in the appsettings environment file. Not the friendly name but the root name of the identifier, omitting the http protocol and the *api* path. ```
docker compose up -d --force-recreate
```Json
"Auth0": {
"Domain": "[domain].auth0.com",
"ApiIdentifier": "https://[identifier]/api"
},
``` ```
**Note**: The Auth0 section is likely to be changed or removed in future releases. To view the OpenAPI spec, run the project and access `/swagger-ui`. If running through docker,
the url would be something like `http://localhost:8000/swagger-ui`.
### API filesystem paths
For the purposes of properly uploading, downloading, updating, deleting, and streaming songs the API filesystem paths must be configured. What is meant by this is that the `RootMusicPath` directory where all music will be stored must exist as well as the `ArchivePath` and `TemporaryMusicPath` paths. An example on a Linux system:
```Json
{
"RootMusicPath": "/home/dev/null/music/",
"TemporaryMusicPath": "/home/dev/null/music/temp/",
"ArchivePath": "/home/dev/null/music/archive/",
"CoverArtPath": "/home/dev/null/music/coverart/"
}
```
* RootMusicPath - Where music will be stored in the following convention: *`Artist/Album/Songs`*
* TemporaryMusicPath - Where music will be stored when uploding songs to the server until the metadata has been fully parsed and entered into the database. Upon completion the files will be deleted and moved to the appropriate path in the `RootMusicPath`
* ArchivePath - When downloading compressed songs this is the path where songs will be compressed prior to dataa being read into memory, deleting the compressed file, and sending the compressed file from memory to the client
* CoverArtPath - Root directory where cover art will be saved to
**Note**: The `TemporaryMusic` or `ArchivePath` does not have to be located in the `RootMusicPath`. Ensure that the permissions are properly set for all of the paths.
### Database connection string
In order for Database functionality to be operable, there must be a valid connection string and credentials with appropriate permissions. **At the moment there is only support for MySQL**. Depending on your environment `Release` or `Debug` you will need to edit the appsettings.json or appsettings.Development.json accordingly. An example of the fields to change are below:
```Json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=my_db;Uid=admin;Pwd=toughpassword;"
}
}
```
* Server - The address or domain name of the MySQL server
* Database - The database name
* Uid - Username
* Password - Self-explanatory
The only requirement of the User is that the user should have full permissions to the database as well as permissions to create a database. Other than that, that is all that is required.
### Migrations
Prior to starting the API, the Migrations must be applied. There are 6 tables with migrations being applied and thy are:
* Users
* Song
* Album
* Artist
* Year
* Genre
There is a script for Linux systems to apply these migrations, it can be found in the [Scripts/Migrations/Linux](https://github.com/amazing-username/Icarus/blob/master/Scripts/Migrations/Linux/AddUpdate.sh) directory. Just merely execute:
```shell
scripts/Migrations/Linux/AddUpdate.sh
```
Or you can manually add the migrations like so for each migration:
```shell
dotnet ef migrations Add [Migration] --context [Migration]Context
```
Then update the migrations to the database like so<sup>*</sup>:
```shell
dotnet ef database update --context [Migration]Context
```
From this point the database has been successfully configured. Metadata and song filesystem locations can be saved.
<sup>*</sup> Will only need to execute this for UserContext and SongContext because the Song table has relational constraints with Album, Artist, Year, and Genre.
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the code of conduct, and the process for submitting pull requests to the project.
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
-26
View File
@@ -1,26 +0,0 @@
echo "Adding migrations..."
echo "Adding User migration"
dotnet ef migrations add User --context UserContext
echo "Adding Song migration"
dotnet ef migrations add Song --context SongContext
echo "Adding Album migration"
dotnet ef migrations add Album --context AlbumContext
echo "Adding Artist migration"
dotnet ef migrations add Artist --context ArtistContext
echo "Adding Genre migration"
dotnet ef migrations add Genre --context GenreContext
echo "Adding Year migration"
dotnet ef migrations add Year --context YearContext
echo "Adding Cover art migration"
dotnet ef migrations add CoverArt --context CoverArtContext
echo "Updating migrations.."
echo "Updating User migration"
dotnet ef database update --context UserContext
echo "Updating Song migration"
echo "Updating Album migration"
echo "Updating Artist migration"
echo "Updating Genre migration"
echo "Updating Year migration"
echo "Updating Cover art migration"
dotnet ef database update --context SongContext
-99
View File
@@ -1,99 +0,0 @@
CREATE DATABASE Icarus;
USE Icarus;
CREATE TABLE CoverArt (
CoverArtID INT NOT NULL AUTO_INCREMENT,
SongTitle TEXT NOT NULL,
ImagePath TEXT NOT NULL,
PRIMARY KEY (CoverArtID)
);
CREATE TABLE Album (
AlbumID INT NOT NULL AUTO_INCREMENT,
Title TEXT NOT NULL,
Artist TEXT NOT NULL,
Year INT NOT NULL,
PRIMARY KEY (AlbumID)
);
CREATE TABLE Artist (
ArtistID INT NOT NULL AUTO_INCREMENT,
Artist TEXT NOT NULL,
PRIMARY KEY (ArtistID)
);
CREATE TABLE Genre (
GenreID INT NOT NULL AUTO_INCREMENT,
Category TEXT NOT NULL,
PRIMARY KEY (GenreID)
);
CREATE TABLE Song (
SongID INT NOT NULL AUTO_INCREMENT,
Title TEXT NOT NULL,
Artist TEXT NOT NULL,
Album TEXT NOT NULL,
AlbumArtist TEXT NOT NULL,
Genre TEXT NOT NULL,
Year INT NOT NULL,
Duration INT NOT NULL,
Track INT NOT NULL,
TrackCount INT NOT NULL,
Disc INT NOT NULL,
DiscCount INT NOT NULL,
SongDirectory TEXT NOT NULL,
Filename TEXT NOT NULL,
CoverArtID INT NOT NULL,
ArtistID INT NOT NULL,
AlbumID INT NOT NULL,
GenreID INT NOT NULL,
DateCreated DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (SongID),
CONSTRAINT FK_Song_CoverArtID FOREIGN KEY (CoverArtID) REFERENCES CoverArt (CoverArtID),
CONSTRAINT FK_Song_ArtistID FOREIGN KEY (ArtistID) REFERENCES Artist (ArtistID),
CONSTRAINT FK_Song_AlbumID FOREIGN KEY (AlbumID) REFERENCES Album (AlbumID),
CONSTRAINT FK_Song_GenreID FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);
CREATE TABLE User (
UserID INT NOT NULL AUTO_INCREMENT,
Firstname TEXT NOT NULL,
Lastname TEXT NOT NULL,
Email TEXT NOT NULL,
Phone TEXT NOT NULL,
Username TEXT NOT NULL,
Password TEXT NOT NULL,
DateCreated DATETIME DEFAULT CURRENT_TIMESTAMP,
Status TEXT DEFAULT 'Active',
LastLogin DATETIME NULL,
PRIMARY KEY (UserID)
);
CREATE TABLE Salt (
SaltID INT NOT NULL AUTO_INCREMENT,
Salt TEXT NOT NULL,
UserID INT NOT NULL,
PRIMARY KEY (SaltID),
CONSTRAINT FK_Salt_UserID FOREIGN KEY (UserID) REFERENCES User (UserID)
);
CREATE TABLE Token (
TokenID INT NOT NULL AUTO_INCREMENT,
AccessToken TEXT NOT NULL,
TokenType TEXT NOT NULL,
Expires DATETIME DEFAULT CURRENT_TIMESTAMP,
Issued DATETIME DEFAULT CURRENT_TIMESTAMP,
UserID INT NOT NULL,
PRIMARY KEY (TokenID),
CONSTRAINT FK_Token_UserID FOREIGN KEY (UserID) REFERENCES User (UserID)
);
-5
View File
@@ -1,5 +0,0 @@
delete from Song;
delete from Album;
delete from Artist;
delete from Genre;
delete from CoverArt;
-1
View File
@@ -1 +0,0 @@
select * from Song;
-1
View File
@@ -1 +0,0 @@
drop database Icarus;
Vendored
-127
View File
@@ -1,127 +0,0 @@
using System;
using System.Text;
using System.Linq;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json;
using NLog;
using NLog.Web;
using NLog.Web.AspNetCore;
using Icarus.Database.Contexts;
namespace Icarus
{
public class Startup
{
#region Constructors
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
#endregion
#region Properties
public IConfiguration Configuration { get; }
#endregion
#region Methods
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
var auth_id = Configuration["Auth0:Domain"];
var domain = $"https://{auth_id}/";
var audience = Configuration["Auth0:ApiIdentifier"];
var connString = Configuration.GetConnectionString("DefaultConnection");
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.SaveToken = true;
options.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = true,
ValidateAudience = true,
ValidAudience = Configuration["JWT:Audience"],
ValidIssuer = Configuration["JWT:Issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]))
};
});
services.AddDbContext<SongContext>(options => options.UseMySQL(connString));
services.AddDbContext<AlbumContext>(options => options.UseMySQL(connString));
services.AddDbContext<ArtistContext>(options => options.UseMySQL(connString));
services.AddDbContext<UserContext>(options => options.UseMySQL(connString));
services.AddDbContext<GenreContext>(options => options.UseMySQL(connString));
services.AddDbContext<CoverArtContext>(options => options.UseMySQL(connString));
services.AddControllers()
.AddNewtonsoftJson();
services.AddEndpointsApiExplorer();
services.AddSwaggerGen(c =>
{
c.ResolveConflictingActions(apiDescriptions => apiDescriptions.First());
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Icarus", Version = "v1" });
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
{
Name = "Authorization",
Scheme = "Bearer",
BearerFormat = "JWT",
Type = SecuritySchemeType.ApiKey,
In = ParameterLocation.Header,
Description = "Bearer *Auth Token*",
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
}
},
new string[] {}
}
});
});
}
// Called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// NOTE: Dev-related configuration can be done when env.IsDevelopment() evaluated to true
if (env.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
#endregion
}
}
-10
View File
@@ -1,10 +0,0 @@
using System;
namespace Icarus.Types
{
public enum CoverArtField
{
SongTitle = 0,
ImagePath
};
}
-10
View File
@@ -1,10 +0,0 @@
using System;
namespace Icarus.Types
{
public enum DirectoryType
{
Music = 0,
CoverArt
};
}
-28
View File
@@ -1,28 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"Auth0": {
"Domain": "[domain].auth0.com",
"ApiIdentifier": "https://[identifier]/api",
"ClientId": "",
"ClientSecret": ""
},
"JWT": {
"Issuer": "",
"Audience": "",
"Secret": "",
"Subject": ""
},
"ConnectionStrings": {
"DefaultConnection": "Server=;Database=;Uid=;Pwd=;"
},
"RootMusicPath": "/music/path/",
"TemporaryMusicPath": "/music/temp/path/",
"ArchivePath": "/archive/path/",
"CoverArtPath": "/cover/art/path/"
}
-28
View File
@@ -1,28 +0,0 @@
{
"Logging": {
"LogLevel": {
"Default": "Trace",
"Microsoft": "Information"
}
},
"AllowedHosts": "*",
"Auth0": {
"Domain": "[domain].auth0.com",
"ApiIdentifier": "https://[identifier]/api",
"ClientId": "",
"ClientSecret": ""
},
"JWT": {
"Issuer": "",
"Audience": "",
"Secret": "",
"Subject": ""
},
"ConnectionStrings": {
"DefaultConnection": "Server=;Database=;Uid=;Pwd=;"
},
"RootMusicPath": "/music/path/",
"TemporaryMusicPath": "/music/temp/path/",
"ArchivePath": "/archive/path/",
"CoverArtPath": "/cover/art/path/"
}
+128
View File
@@ -0,0 +1,128 @@
version: '3.8' # Use a recent version
services:
# --- Web API ---
api:
build: # Tells docker-compose to build the Dockerfile in the current directory
context: .
ssh: ["default"] # Uses host's SSH agent
container_name: icarus # Optional: Give the container a specific name
ports:
# Map host port 8000 to container port 3000 (adjust as needed)
- "8000:8000"
env_file:
- .env
depends_on:
main_db:
condition: service_healthy
networks:
- icarus-network
restart: unless-stopped # Optional: Restart policy
# --- Web API auth ---
auth_api:
build:
context: ../icarus_auth # IMPORTANT: Relative path to the local checkout of your web API repo (containing the Dockerfile)
ssh: ["default"] # Uses host's SSH agent
dockerfile: Dockerfile # Optional: Specify if your Dockerfile has a non-standard name
container_name: auth_api
restart: unless-stopped
ports:
- "8001:8001" # Map host port 8000 to container port 8000 (adjust container port based on your app's EXPOSE in Dockerfile)
# environment:
# Environment variables your API needs, e.g., database connection
# Add other necessary environment variables
env_file:
- ../icarus_auth/.env
depends_on:
auth_db:
condition: service_healthy
networks:
- icarus-network
# Optional: Mount local code for development (live reload)
# volumes:
# - ./path/to/your/web-api-repo:/app
# --- songparser service ---
songparser:
build:
context: ../songparser
ssh: ["default"]
dockerfile: Dockerfile
container_name: songparser
restart: unless-stopped
env_file:
- ../songparser/.env
depends_on:
- api
- main_db
- auth_api
- auth_db
networks:
- icarus-network
# PostgreSQL Database Service
# --- icarus web api db ---
main_db:
image: postgres:18.3-alpine # Use an official Postgres image (Alpine variant is smaller)
container_name: icarus_db # Optional: Give the container a specific name
environment:
# These MUST match the user, password, and database name in the DATABASE_URL above
POSTGRES_USER: ${POSTGRES_MAIN_USER:-icarus}
POSTGRES_PASSWORD: ${POSTGRES_MAIN_PASSWORD:-password}
POSTGRES_DB: ${POSTGRES_MAIN_DB:-icarus_db}
volumes:
# Persist database data using a named volume
- postgres_data:/var/lib/postgresql
ports:
# Optional: Expose port 5432 ONLY if you need to connect directly from your host machine (e.g., for debugging)
- "5432:5432"
healthcheck:
# Checks if Postgres is ready to accept connections
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
restart: always # Optional: Restart policy
networks:
- icarus-network
# --- icarus web auth api db ---
auth_db:
image: postgres:18.3-alpine # Use an official Postgres image (Alpine variant is smaller)
container_name: icarus_auth_db # Optional: Give the container a specific name
environment:
# These MUST match the user, password, and database name in the DATABASE_URL above
POSTGRES_USER: ${POSTGRES_AUTH_USER:-icarus_op}
POSTGRES_PASSWORD: ${POSTGRES_AUTH_PASSWORD:-password}
POSTGRES_DB: ${POSTGRES_AUTH_DB:-icarus_auth_db}
volumes:
# Persist database data using a named volume
- postgres_data_auth:/var/lib/postgresql
ports:
# Optional: Expose port 5432 ONLY if you need to connect directly from your host machine (e.g., for debugging)
- "5433:5432"
healthcheck:
# Checks if Postgres is ready to accept connections
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
restart: always # Optional: Restart policy
networks:
- icarus-network
# Define the named volume for data persistence
volumes:
postgres_data:
driver: local # Use the default local driver
postgres_data_auth:
driver: local # Use the default local driver
# Define the network (optional, but good practice)
networks:
icarus-network:
driver: bridge
@@ -0,0 +1,63 @@
-- Add migration script here
CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- Table to store queued songs to process
CREATE TABLE IF NOT EXISTS "songQueue" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
filename TEXT NOT NULL,
status TEXT CHECK (status IN ('pending', 'ready', 'processing', 'done')),
data BYTEA NULL,
user_id UUID NULL
);
-- Table to store queued metadata
CREATE TABLE IF NOT EXISTS "metadataQueue" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
metadata jsonb NOT NULL,
created_at timestamptz DEFAULT now(),
song_queue_id UUID NOT NULL
);
-- Table to store queued coverart
CREATE TABLE IF NOT EXISTS "coverartQueue" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
data BYTEA NULL,
file_type TEXT NOT NULL,
song_queue_id UUID NULL
);
-- Create an index for better query performance
CREATE INDEX metadata_queue_data_metadata ON "metadataQueue" USING gin (metadata);
-- Table to store a song's info
CREATE TABLE IF NOT EXISTS "song" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
artist TEXT NOT NULL,
album_artist TEXT NOT NULL,
album TEXT NOT NULL,
genre TEXT NOT NULL,
-- TODO: Address discrepancy of date and year at some point
-- date TEXT NOT NULL,
year INT NOT NULL,
track INT NOT NULL,
disc INT NOT NULL,
track_count INT NOT NULL,
disc_count INT NOT NULL,
duration INT NOT NULL,
audio_type TEXT NOT NULL,
date_created timestamptz DEFAULT now(),
filename TEXT NOT NULL,
directory TEXT NOT NULL,
user_id UUID NULL
-- TODO: Add coverart id later. This will allow multiple songs to be linked to a single cover art
);
CREATE TABLE IF NOT EXISTS "coverart" (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
title TEXT NOT NULL,
directory TEXT NOT NULL,
filename TEXT NOT NULL,
file_type TEXT NOT NULL,
song_id UUID NOT NULL
);
-33
View File
@@ -1,33 +0,0 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogLevel="Info"
internalLogFile="Icarus.txt">
<!-- enable asp.net core layout renderers -->
<extensions>
<add assembly="NLog.Web.AspNetCore"/>
</extensions>
<!-- the targets to write to -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="Icarus-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}" />
<!-- another file log, only own logs. Uses some ASP.NET core renderers -->
<target xsi:type="File" name="ownFile-web" fileName="Icarus-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId_Id}|${uppercase:${level}}|${logger}|${message} ${exception:format=tostring}|url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- BlackHole without writeTo -->
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
</rules>
</nlog>
+59
View File
@@ -0,0 +1,59 @@
use axum::{
Json,
http::{Request, StatusCode},
middleware::Next,
response::IntoResponse,
};
use axum_extra::extract::cookie::CookieJar;
use jsonwebtoken::{DecodingKey, Validation, decode};
#[derive(Debug, serde::Serialize)]
pub struct ErrorResponse {
pub status: &'static str,
pub message: String,
}
pub async fn auth<B>(
cookie_jar: CookieJar,
req: Request<axum::body::Body>,
next: Next,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
let token = cookie_jar
.get("token")
.map(|cookie| cookie.value().to_string())
.or_else(|| {
req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|auth_header| auth_header.to_str().ok())
.and_then(|auth_value| auth_value.strip_prefix("Bearer ").map(String::from))
});
let token = token.ok_or_else(|| {
let json_error = ErrorResponse {
status: "fail",
message: "You are not logged in, please provide token".to_string(),
};
(StatusCode::UNAUTHORIZED, Json(json_error))
})?;
let secret_key = icarus_envy::environment::get_secret_main_key().await.value;
let mut validation = Validation::new(jsonwebtoken::Algorithm::HS256);
validation.set_audience(&["icarus"]); // Must match exactly what's in the token
let _claims = decode::<icarus_models::token::UserClaims>(
&token,
&DecodingKey::from_secret(secret_key.as_ref()),
&validation,
)
.map_err(|err| {
eprintln!("Error: {err:?}");
let json_error = ErrorResponse {
status: "fail",
message: "Invalid token - Error decoding claims".to_string(),
};
(StatusCode::UNAUTHORIZED, Json(json_error))
})?
.claims;
Ok(next.run(req).await)
}
+264
View File
@@ -0,0 +1,264 @@
pub mod request {
pub mod create_coverart {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub song_id: uuid::Uuid,
pub coverart_queue_id: uuid::Uuid,
}
}
pub mod get_coverart {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Params {
pub id: Option<uuid::Uuid>,
}
}
}
pub mod response {
pub mod create_coverart {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::coverart::CoverArt>,
}
}
pub mod get_coverart {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::coverart::CoverArt>,
}
}
}
pub mod endpoint {
use axum::response::IntoResponse;
use crate::repo;
use crate::repo::queue as repo_queue;
/// Endpoint to create cover art
#[utoipa::path(
post,
path = super::super::endpoints::CREATECOVERART,
request_body(
content = super::request::create_coverart::Request,
description = "Data required to create cover art",
content_type = "application/json"
),
responses(
(status = 200, description = "Cover art created", body = super::response::create_coverart::Response),
(status = 400, description = "Failure in creating cover art", body = super::response::create_coverart::Response)
)
)]
pub async fn create_coverart(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::create_coverart::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::create_coverart::Response>,
) {
let mut response = super::response::create_coverart::Response::default();
let id = payload.coverart_queue_id;
match repo_queue::coverart::get_coverart_queue_data_with_id(&pool, &id).await {
Ok(data) => {
let song_id = payload.song_id;
match crate::repo::song::get_song(&pool, &song_id).await {
Ok(song) => {
let directory = icarus_envy::environment::get_root_directory().await.value;
let file_type =
icarus_meta::detection::coverart::file_type_from_data(&data).unwrap();
let coverart_type = if file_type.file_type
== icarus_meta::detection::coverart::constants::JPEG_TYPE
{
icarus_models::types::CoverArtType::JpegExtension
} else if file_type.file_type
== icarus_meta::detection::coverart::constants::JPG_TYPE
{
icarus_models::types::CoverArtType::JpgExtension
} else if file_type.file_type
== icarus_meta::detection::coverart::constants::PNG_TYPE
{
icarus_models::types::CoverArtType::PngExtension
} else {
response.message = String::from("Invalid CoverArt type");
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
};
let filename =
icarus_models::coverart::generate_filename(coverart_type, true)
.unwrap();
let mut coverart =
icarus_models::coverart::init::init_coverart_dir_and_filename(
&directory, &filename,
);
coverart.title = song.album.clone();
coverart.file_type = file_type.file_type;
coverart.data = data;
match coverart.save_to_filesystem() {
Ok(_) => {
match repo::coverart::create(&pool, &coverart, &song.id).await {
Ok(id) => {
coverart.song_id = song_id;
coverart.id = id;
println!("Cover Art created");
response.message = String::from("Successful");
response.data.push(coverart);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to get cover art with criteria
#[utoipa::path(
get,
path = super::super::endpoints::GETCOVERART,
params(
("id" = uuid::Uuid, Path, description = "Cover art Id")
),
responses(
(status = 200, description = "Cover art retrieved", body = super::response::get_coverart::Response),
(status = 400, description = "Error retrieving cover art", body = super::response::get_coverart::Response)
)
)]
pub async fn get_coverart(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<super::request::get_coverart::Params>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::get_coverart::Response>,
) {
let mut response = super::response::get_coverart::Response::default();
match params.id {
Some(id) => match repo::coverart::get_coverart(&pool, &id).await {
Ok(coverart) => {
response.data.push(coverart);
response.message = String::from(super::super::response::SUCCESSFUL);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
None => {
response.message = String::from("Invalid parameters");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to download cover art
#[utoipa::path(
get,
path = super::super::endpoints::DOWNLOADCOVERART,
params(
("id" = uuid::Uuid, Path, description = "Cover art Id")
),
responses(
(status = 200, description = "Cover art downloading", body = Vec<u8>),
(status = 404, description = "Cover art not found", body = Vec<u8>)
)
)]
pub async fn download_coverart(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (axum::http::StatusCode, axum::response::Response) {
match repo::coverart::get_coverart(&pool, &id).await {
Ok(coverart) => match icarus_models::coverart::io::to_data(&coverart) {
Ok(data) => {
let (file_type, img_type) =
match icarus_meta::detection::coverart::file_type_from_data(&data) {
Ok(file_type) => {
if file_type.file_type
== icarus_meta::detection::coverart::constants::JPEG_TYPE
{
(file_type, icarus_models::types::CoverArtType::JpegExtension)
} else if file_type.file_type
== icarus_meta::detection::coverart::constants::JPG_TYPE
{
(file_type, icarus_models::types::CoverArtType::JpgExtension)
} else if file_type.file_type
== icarus_meta::detection::coverart::constants::PNG_TYPE
{
(file_type, icarus_models::types::CoverArtType::PngExtension)
} else {
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::response::Response::default(),
);
}
}
Err(err) => {
eprintln!("Error: {err:?}");
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::response::Response::default(),
);
}
};
let bytes = axum::body::Bytes::from(data);
let mut response = bytes.into_response();
let headers = response.headers_mut();
let filename =
icarus_models::coverart::generate_filename(img_type, true).unwrap();
headers.insert(
axum::http::header::CONTENT_TYPE,
file_type.mime.parse().unwrap(),
);
headers.insert(
axum::http::header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{filename}\"")
.parse()
.unwrap(),
);
(axum::http::StatusCode::OK, response)
}
Err(_err) => (
axum::http::StatusCode::NOT_FOUND,
axum::response::Response::default(),
),
},
Err(_err) => (
axum::http::StatusCode::NOT_FOUND,
axum::response::Response::default(),
),
}
}
}
+26
View File
@@ -0,0 +1,26 @@
pub mod coverart;
pub mod queue;
pub mod song;
pub mod endpoints {
pub const ROOT: &str = "/";
pub const CREATESONG: &str = "/api/v2/song";
pub const GETSONGS: &str = "/api/v2/song";
pub const GETALLSONGS: &str = "/api/v2/song/all";
pub const STREAMSONG: &str = "/api/v2/song/stream/{id}";
pub const DOWNLOADSONG: &str = "/api/v2/song/download/{id}";
pub const DELETESONG: &str = "/api/v2/song/{id}";
pub const CREATECOVERART: &str = "/api/v2/coverart";
pub const GETCOVERART: &str = "/api/v2/coverart";
pub const DOWNLOADCOVERART: &str = "/api/v2/coverart/download/{id}";
}
pub mod response {
pub const SUCCESSFUL: &str = "SUCCESSFUL";
}
/// Basic handler that responds with a static string
pub async fn root() -> &'static str {
"Hello, World!"
}
+412
View File
@@ -0,0 +1,412 @@
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct CoverArtQueue {
pub id: uuid::Uuid,
pub file_type: String,
pub song_queue_id: uuid::Uuid,
}
pub mod request {
pub mod queue {
#[derive(utoipa::ToSchema)]
pub struct Request {
/// Filename
pub file: String,
#[schema(rename = "type")]
/// File type. Should be a file and not a value
pub file_type: String,
/// Raw data of the cover art file
pub value: Vec<u8>,
}
}
pub mod link {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub coverart_id: uuid::Uuid,
pub song_queue_id: uuid::Uuid,
}
}
pub mod fetch_coverart_no_data {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Params {
pub id: Option<uuid::Uuid>,
pub song_queue_id: Option<uuid::Uuid>,
}
}
pub mod fetch_coverart_with_data {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Params {
pub id: Option<uuid::Uuid>,
pub song_queue_id: Option<uuid::Uuid>,
}
}
pub mod wipe_data_from_coverart_queue {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub coverart_queue_id: uuid::Uuid,
}
}
}
pub mod response {
pub mod queue {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
pub mod link {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Id {
pub coverart_id: uuid::Uuid,
pub song_queue_id: uuid::Uuid,
}
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<Id>,
}
}
pub mod fetch_coverart_no_data {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<super::super::CoverArtQueue>,
}
}
pub mod fetch_coverart_with_data {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<Vec<u8>>,
}
}
pub mod wipe_data_from_coverart_queue {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
}
mod helper {
pub fn is_coverart_file_type_valid(file_type: &String) -> bool {
let valid_file_types = vec![
String::from(icarus_meta::detection::coverart::constants::JPEG_TYPE),
String::from(icarus_meta::detection::coverart::constants::JPG_TYPE),
String::from(icarus_meta::detection::coverart::constants::PNG_TYPE),
];
for valid_file_type in valid_file_types {
if valid_file_type == *file_type {
return true;
}
}
false
}
}
pub mod endpoint {
use axum::response::IntoResponse;
use crate::repo::queue as repo;
/// Endpoint to queue cover art
#[utoipa::path(
post,
path = super::super::endpoints::QUEUECOVERART,
request_body(
content = super::request::queue::Request,
),
responses(
(status = 200, description = "Successful", body = super::response::queue::Response),
(status = 400, description = "Error queueing cover art", body = super::response::queue::Response)
)
)]
pub async fn queue(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
mut multipart: axum::extract::Multipart,
) -> (
axum::http::StatusCode,
axum::Json<super::response::queue::Response>,
) {
let mut response = super::response::queue::Response::default();
match multipart.next_field().await {
Ok(Some(field)) => {
let name = field.name().unwrap().to_string();
let file_name = field.file_name().unwrap().to_string();
let content_type = field.content_type().unwrap().to_string();
let data = field.bytes().await.unwrap();
let raw_data = data.to_vec();
let file_type =
match icarus_meta::detection::coverart::file_type_from_data(&raw_data) {
Ok(file_type) => file_type,
Err(err) => {
eprintln!("Error: {err:?}");
response.message = err.to_string();
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
}
};
if !super::helper::is_coverart_file_type_valid(&file_type.file_type) {
response.message = format!("CoverArt file type not supported: {file_type:?}");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
} else {
println!(
"Received file '{}' (name = '{}', content-type = '{}', size = {}, file-type = {:?})",
file_name,
name,
content_type,
data.len(),
file_type
);
match repo::coverart::insert(&pool, &raw_data, &file_type.file_type).await {
Ok(id) => {
response.message = String::from("Successful");
response.data.push(id);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
}
Ok(None) => (axum::http::StatusCode::BAD_REQUEST, axum::Json(response)),
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to link queued cover art
#[utoipa::path(
post,
path = super::super::endpoints::QUEUECOVERARTLINK,
request_body(
content = super::request::link::Request,
description = "Linking queued cover art to queued song",
content_type = "application/json"
),
responses(
(status = 200, description = "Queued cover art linked", body = super::response::link::Response),
(status = 400, description = "Linkage failed", body = super::response::link::Response)
)
)]
pub async fn link(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::link::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::link::Response>,
) {
let mut response = super::response::link::Response::default();
let id = payload.coverart_id;
let song_id = payload.song_queue_id;
match repo::coverart::update(&pool, &id, &song_id).await {
Ok(_o) => {
response.data.push(super::response::link::Id {
song_queue_id: song_id,
coverart_id: id,
});
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to fetch cover art details
#[utoipa::path(
get,
path = super::super::endpoints::QUEUECOVERART,
params(
("id" = uuid::Uuid, Path, description = "Queued cover art Id"),
("song_queue_id" = uuid::Uuid, Path, description = "Queued song Id")
),
responses(
(status = 200, description = "Queued song linked", body = super::response::fetch_coverart_no_data::Response),
(status = 400, description = "Linkage failed", body = super::response::fetch_coverart_no_data::Response)
)
)]
pub async fn fetch_coverart_no_data(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<
super::request::fetch_coverart_no_data::Params,
>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::fetch_coverart_no_data::Response>,
) {
let mut response = super::response::fetch_coverart_no_data::Response::default();
match params.id {
Some(id) => match repo::coverart::get_coverart_queue_with_id(&pool, &id).await {
Ok(cover_art_queue) => {
response.message = String::from("Successful");
response.data.push(cover_art_queue);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
_ => match params.song_queue_id {
Some(song_queue_id) => match repo::coverart::get_coverart_queue_with_song_queue_id(
&pool,
&song_queue_id,
)
.await
{
Ok(cover_art_queue) => {
response.message = String::from("Successful");
response.data.push(cover_art_queue);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
None => {
response.message = String::from("No valid id provided");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
}
}
/// Endpoint to fetch the queued cover art data
#[utoipa::path(
get,
path = super::super::endpoints::QUEUECOVERARTDATA,
params(("id" = uuid::Uuid, Path, description = "Queued cover art Id")),
responses(
(status = 200, description = "Queued cover art data", body = Vec<u8>),
(status = 400, description = "Error fetching queued cover art data", body = Vec<u8>)
)
)]
pub async fn fetch_coverart_with_data(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (axum::http::StatusCode, axum::response::Response) {
match repo::coverart::get_coverart_queue_data_with_id(&pool, &id).await {
Ok(data) => {
let file_type =
icarus_meta::detection::coverart::file_type_from_data(&data).unwrap();
let bytes = axum::body::Bytes::from(data);
let mut response = bytes.into_response();
let headers = response.headers_mut();
headers.insert(
axum::http::header::CONTENT_TYPE,
file_type.mime.parse().unwrap(),
);
let coverart_type = if file_type.file_type
== icarus_meta::detection::coverart::constants::JPEG_TYPE
{
icarus_models::types::CoverArtType::JpegExtension
} else if file_type.file_type
== icarus_meta::detection::coverart::constants::JPG_TYPE
{
icarus_models::types::CoverArtType::JpgExtension
} else if file_type.file_type
== icarus_meta::detection::coverart::constants::PNG_TYPE
{
icarus_models::types::CoverArtType::PngExtension
} else {
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::response::Response::default(),
);
};
let filename =
icarus_models::coverart::generate_filename(coverart_type, true).unwrap();
headers.insert(
axum::http::header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{filename}\"")
.parse()
.unwrap(),
);
(axum::http::StatusCode::OK, response)
}
Err(_err) => (
axum::http::StatusCode::BAD_REQUEST,
axum::response::Response::default(),
),
}
}
/// Endpoint to wipe data from the cover art queue
#[utoipa::path(
patch,
path = super::super::endpoints::QUEUECOVERARTDATAWIPE,
request_body(
content = super::request::wipe_data_from_coverart_queue::Request,
description = "Data required to wipe the data from the cover art queue",
content_type = "application/json"
),
responses(
(status = 200, description = "Data wiped from cover art queue", body = super::response::wipe_data_from_coverart_queue::Response),
(status = 400, description = "Error wiping the data", body = super::response::wipe_data_from_coverart_queue::Response),
(status = 404, description = "Cover art not found", body = super::response::wipe_data_from_coverart_queue::Response)
)
)]
pub async fn wipe_data_from_coverart_queue(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::wipe_data_from_coverart_queue::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::wipe_data_from_coverart_queue::Response>,
) {
let mut response = super::response::wipe_data_from_coverart_queue::Response::default();
let coverart_queue_id = payload.coverart_queue_id;
match repo::coverart::get_coverart_queue_with_id(&pool, &coverart_queue_id).await {
Ok(coverart_queue) => {
match repo::coverart::wipe_data(&pool, &coverart_queue.id).await {
Ok(id) => {
response.message = String::from("Success");
response.data.push(id);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
}
+185
View File
@@ -0,0 +1,185 @@
pub mod request {
pub mod queue_metadata {
#[derive(
Debug, Default, serde::Deserialize, serde::Serialize, sqlx::FromRow, utoipa::ToSchema,
)]
pub struct Request {
pub song_queue_id: uuid::Uuid,
pub album: String,
pub album_artist: String,
pub artist: String,
pub disc: i32,
pub disc_count: i32,
pub duration: i64,
pub genre: String,
pub title: String,
pub track: i32,
pub track_count: i32,
pub year: i32,
}
impl Request {
pub async fn to_json_value(&self) -> serde_json::Value {
serde_json::json!(
{
"song_queue_id": &self.song_queue_id,
"album": &self.album,
"album_artist": &self.album_artist,
"genre": &self.genre,
"year": &self.year,
"track_count": &self.track_count,
"disc_count": &self.disc_count,
"title": &self.title,
"artist": &self.artist,
"disc": &self.disc,
"track": &self.track,
"duration": &self.duration,
})
}
}
}
pub mod fetch_metadata {
#[derive(
Debug,
Default,
serde::Deserialize,
serde::Serialize,
sqlx::FromRow,
sqlx::Decode,
utoipa::ToSchema,
)]
pub struct Params {
pub id: Option<uuid::Uuid>,
pub song_queue_id: Option<uuid::Uuid>,
}
}
}
pub mod response {
pub mod queue_metadata {
#[derive(Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
pub mod fetch_metadata {
#[derive(Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<crate::repo::queue::metadata::MetadataQueue>,
}
}
}
/// Module for metadata related endpoints
pub mod endpoint {
use crate::repo::queue as repo_queue;
/// Endpoint to create queued metadata
#[utoipa::path(
post,
path = super::super::endpoints::QUEUEMETADATA,
request_body(
content = super::request::queue_metadata::Request,
description = "Data required to create queued metadata",
content_type = "application/json"
),
responses(
(status = 200, description = "Queued metadata created", body = super::response::queue_metadata::Response),
(status = 400, description = "Error creating queued metadata", body = super::response::queue_metadata::Response)
)
)]
pub async fn queue_metadata(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::queue_metadata::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::queue_metadata::Response>,
) {
let mut results: Vec<uuid::Uuid> = Vec::new();
let mut response = super::response::queue_metadata::Response::default();
let meta = payload.to_json_value().await;
match repo_queue::metadata::insert(&pool, &meta, &payload.song_queue_id).await {
Ok(metadata_queue_id) => {
results.push(metadata_queue_id);
response.data = results;
response.message = if response.data.is_empty() {
String::from("Error")
} else {
String::from(super::super::super::response::SUCCESSFUL)
};
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to get queued metadata
#[utoipa::path(
get,
path = super::super::endpoints::QUEUEMETADATA,
params(
("id" = uuid::Uuid, Path, description = "Id of queued metadata"),
("song_queue_id" = uuid::Uuid, Path, description = "Id of queued song")
),
responses(
(status = 200, description = "Queued metadata retrieved", body = super::response::fetch_metadata::Response),
(status = 400, description = "Error retrieving queued metadata", body = super::response::fetch_metadata::Response)
)
)]
pub async fn fetch_metadata(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<super::request::fetch_metadata::Params>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::fetch_metadata::Response>,
) {
let mut response = super::response::fetch_metadata::Response::default();
match params.id {
Some(id) => {
println!("Something works {id}");
match repo_queue::metadata::get_with_id(&pool, &id).await {
Ok(item) => {
response.message = String::from("Successful");
response.data.push(item);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
_ => match params.song_queue_id {
Some(song_queue_id) => {
println!("Song queue Id is probably not nil");
match repo_queue::metadata::get_with_song_queue_id(&pool, &song_queue_id).await
{
Ok(item) => {
response.message = String::from("Successful");
response.data.push(item);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
None => {
println!("What is going on?");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
}
}
}
+17
View File
@@ -0,0 +1,17 @@
pub mod coverart;
pub mod metadata;
pub mod song;
pub mod endpoints {
pub const QUEUESONG: &str = "/api/v2/song/queue";
pub const QUEUESONGLINKUSERID: &str = "/api/v2/song/queue/link";
pub const QUEUESONGDATA: &str = "/api/v2/song/queue/{id}";
pub const QUEUESONGUPDATE: &str = "/api/v2/song/queue/{id}";
pub const NEXTQUEUESONG: &str = "/api/v2/song/queue/next";
pub const QUEUEMETADATA: &str = "/api/v2/song/metadata/queue";
pub const QUEUECOVERART: &str = "/api/v2/coverart/queue";
pub const QUEUECOVERARTDATA: &str = "/api/v2/coverart/queue/data/{id}";
pub const QUEUECOVERARTLINK: &str = "/api/v2/coverart/queue/link";
pub const QUEUESONGDATAWIPE: &str = "/api/v2/song/queue/data/wipe";
pub const QUEUECOVERARTDATAWIPE: &str = "/api/v2/coverart/queue/data/wipe";
}
+517
View File
@@ -0,0 +1,517 @@
pub mod request {
pub mod song_queue {
#[derive(utoipa::ToSchema)]
pub struct SongQueueRequest {
/// Filename
pub file: String,
#[schema(rename = "type")]
/// File type. Should be a file and not a value
pub file_type: String,
/// Raw data of the flac file
pub value: Vec<u8>,
}
}
pub mod update_status {
#[derive(Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub id: uuid::Uuid,
pub status: String,
}
}
pub mod wipe_data_from_song_queue {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub song_queue_id: uuid::Uuid,
}
}
pub mod link_user_id {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub song_queue_id: uuid::Uuid,
pub user_id: uuid::Uuid,
}
}
}
pub mod response {
pub mod song_queue {
/// Song queue response
#[derive(Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
/// Id of the queued song
pub data: Vec<uuid::Uuid>,
}
}
pub mod fetch_queue_song {
use serde::{Deserialize, Serialize};
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<crate::repo::queue::song::dbtype::SongQueue>,
}
}
pub mod update_status {
#[derive(serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct ChangedStatus {
pub old_status: String,
pub new_status: String,
}
#[derive(Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<ChangedStatus>,
}
}
pub mod update_song_queue {
#[derive(Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
pub mod wipe_data_from_song_queue {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
pub mod link_user_id {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
}
}
pub async fn is_song_valid(data: &[u8]) -> Result<bool, std::io::Error> {
match icarus_meta::detection::song::file_type_from_data(data) {
Ok(file_type) => {
if file_type.file_type == icarus_meta::detection::song::constants::FLAC_TYPE {
Ok(true)
} else {
Ok(false)
}
}
Err(err) => Err(err),
}
}
pub mod endpoint {
use axum::response::IntoResponse;
use crate::repo::queue as repo;
/// Endpoint to queue a song. Starts the process and places the song in a queue
#[utoipa::path(
post,
path = super::super::endpoints::QUEUESONG,
request_body(
content = super::request::song_queue::SongQueueRequest,
description = "Multipart form data for uploading song",
content_type = "multipart/form-data"
),
responses(
(status = 201, description = "Song queued", body = super::response::song_queue::Response),
(status = 400, description = "Invalid request passed", body = super::response::song_queue::Response),
(status = 500, description = "Error queueing song", body = super::response::song_queue::Response)
)
)]
pub async fn queue_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
mut multipart: axum::extract::Multipart,
) -> (
axum::http::StatusCode,
axum::Json<super::response::song_queue::Response>,
) {
let mut results: Vec<uuid::Uuid> = Vec::new();
let mut response = super::response::song_queue::Response::default();
match multipart.next_field().await {
Ok(multipart_field) => {
if let Some(field) = multipart_field {
let name = field.name().unwrap().to_string();
let file_name = field.file_name().unwrap().to_string();
let content_type = field.content_type().unwrap().to_string();
let data = field.bytes().await.unwrap();
println!(
"Received file '{}' (name = '{}', content-type = '{}', size = {})",
file_name,
name,
content_type,
data.len()
);
let raw_data: Vec<u8> = data.to_vec();
match super::is_song_valid(&raw_data).await {
Ok(valid) => {
if valid {
match repo::song::insert(
&pool,
&raw_data,
&file_name,
&crate::repo::queue::song::status::PENDING.to_string(),
)
.await
{
Ok(queued_song) => {
results.push(queued_song);
}
Err(err) => {
response.message = err.to_string();
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
}
}
} else {
response.message = String::from("Invalid song type");
return (axum::http::StatusCode::BAD_REQUEST, axum::Json(response));
}
}
Err(err) => {
response.message = err.to_string();
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
}
}
response.data = results;
response.message = if response.data.is_empty() {
String::from("Error")
} else {
String::from(super::super::super::response::SUCCESSFUL)
};
(axum::http::StatusCode::CREATED, axum::Json(response))
} else {
response.message = String::from("No field found in multipart");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to link a user id to a queued song
#[utoipa::path(
patch,
path = super::super::endpoints::QUEUESONGLINKUSERID,
request_body(
content = super::request::link_user_id::Request,
description = "User Id and queued song id",
content_type = "application/json"
),
responses(
(status = 200, description = "Queued song linked", body = super::response::link_user_id::Response),
(status = 400, description = "Linkage failed", body = super::response::link_user_id::Response)
)
)]
pub async fn link_user_id(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::link_user_id::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::link_user_id::Response>,
) {
let mut response = super::response::link_user_id::Response::default();
match repo::song::get_song_queue(&pool, &payload.song_queue_id).await {
Ok(song_queue) => {
match repo::song::link_user_id(&pool, &song_queue.id, &payload.user_id).await {
Ok(user_id) => {
response.message = String::from(crate::callers::response::SUCCESSFUL);
response.data.push(user_id);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to fetch the next queued song as long as it is available
#[utoipa::path(
get,
path = super::super::endpoints::NEXTQUEUESONG,
responses(
(status = 200, description = "Queued song is present and available", body = super::response::fetch_queue_song::Response),
(status = 400, description = "Linkage failed", body = super::response::fetch_queue_song::Response)
)
)]
pub async fn fetch_queue_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::fetch_queue_song::Response>,
) {
let mut response = super::response::fetch_queue_song::Response::default();
match repo::song::get_most_recent_and_update(&pool).await {
Ok(item) => {
response.message = String::from("Successful");
response.data.push(item);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to download the queued song
#[utoipa::path(
get,
path = super::super::endpoints::QUEUESONGDATA,
params(("id" = uuid::Uuid, Path, description = "Queued song Id")),
responses(
(status = 200, description = "Queued song linked", body = Vec<u8>),
(status = 400, description = "Linkage failed", body = Vec<u8>)
)
)]
pub async fn download_queued_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (axum::http::StatusCode, axum::response::Response) {
println!("Id: {id}");
match repo::song::get_data(&pool, &id).await {
Ok(data) => {
let by = axum::body::Bytes::from(data);
let mut response = by.into_response();
let headers = response.headers_mut();
headers.insert(
axum::http::header::CONTENT_TYPE,
"audio/flac".parse().unwrap(),
);
headers.insert(
axum::http::header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{id}.flac\"")
.parse()
.unwrap(),
);
(axum::http::StatusCode::OK, response)
}
Err(_err) => (
axum::http::StatusCode::BAD_REQUEST,
axum::response::Response::default(),
),
}
}
/// Endpoint to update the status of a queued song
#[utoipa::path(
patch,
path = super::super::endpoints::QUEUESONG,
request_body(
content = super::request::update_status::Request,
description = "Update the status of a queued song",
content_type = "application/json"
),
responses(
(status = 200, description = "Status has been updated", body = super::response::update_status::Response),
(status = 400, description = "Error updating status of queued song", body = super::response::update_status::Response)
)
)]
pub async fn update_song_queue_status(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::update_status::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::update_status::Response>,
) {
let mut response = super::response::update_status::Response::default();
if repo::song::status::is_valid(&payload.status).await {
let id = payload.id;
if !id.is_nil() {
match repo::song::get_status_of_song_queue(&pool, &id).await {
Ok(old) => {
match repo::song::update_song_queue_status(&pool, &payload.status, &id)
.await
{
Ok(new) => {
response.message = String::from("Successful");
response
.data
.push(super::response::update_status::ChangedStatus {
old_status: old,
new_status: new,
});
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
} else {
response.message = String::from("Id is nil");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
} else {
response.message = String::from("Status not valid");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
/// Endpoint to update the queued song data
#[utoipa::path(
patch,
path = super::super::endpoints::QUEUESONGUPDATE,
request_body(
content = super::request::song_queue::SongQueueRequest,
description = "Multipart form data for uploading song",
content_type = "multipart/form-data"
),
params(("id" = uuid::Uuid, Path, description = "Queued song Id")),
responses(
(status = 200, description = "Queued song updated", body = super::response::update_song_queue::Response),
(status = 400, description = "Error updating queued song", body = super::response::update_song_queue::Response),
(status = 404, description = "Queued song not found", body = super::response::update_song_queue::Response),
(status = 500, description = "Error updating queued song", body = super::response::update_song_queue::Response)
)
)]
pub async fn update_song_queue(
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
mut multipart: axum::extract::Multipart,
) -> (
axum::http::StatusCode,
axum::Json<super::response::update_song_queue::Response>,
) {
let mut response = super::response::update_song_queue::Response::default();
if let Some(field) = multipart.next_field().await.unwrap() {
let name = field.name().unwrap().to_string();
let file_name = field.file_name().unwrap().to_string();
let content_type = match field.content_type() {
Some(ct) => ct.to_string(),
None => String::new(),
};
let data = field.bytes().await.unwrap();
println!(
"Received file '{}' (name = '{}', content-type = '{}', size = {})",
file_name,
name,
content_type,
data.len()
);
let raw_data: Vec<u8> = data.to_vec();
match super::is_song_valid(&raw_data).await {
Ok(valid) => {
if valid {
match repo::song::update(&pool, &raw_data, &id).await {
Ok(_) => {
response.message =
String::from(super::super::super::response::SUCCESSFUL);
response.data.push(id);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
} else {
response.message = String::from("Invalid song type");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
} else {
response.message = String::from("No data provided");
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
/// Endpoint to wipe the data from a queued song
#[utoipa::path(
patch,
path = super::super::endpoints::QUEUESONGDATAWIPE,
request_body(
content = super::request::wipe_data_from_song_queue::Request,
description = "Pass the queued song Id to wipe the data",
content_type = "application/json"
),
responses(
(status = 200, description = "Queued song data wiped", body = super::response::wipe_data_from_song_queue::Response),
(status = 404, description = "Queued song cannot be found", body = super::response::wipe_data_from_song_queue::Response)
)
)]
pub async fn wipe_data_from_song_queue(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::wipe_data_from_song_queue::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::wipe_data_from_song_queue::Response>,
) {
let mut response = super::response::wipe_data_from_song_queue::Response::default();
let id = payload.song_queue_id;
match repo::song::get_song_queue(&pool, &id).await {
Ok(song_queue) => match repo::song::wipe_data(&pool, &song_queue.id).await {
Ok(wiped_id) => {
response.message = String::from("Success");
response.data.push(wiped_id);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
},
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
}
+477
View File
@@ -0,0 +1,477 @@
pub mod request {
pub mod create_metadata {
#[derive(Debug, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Request {
pub title: String,
pub artist: String,
pub album_artist: String,
pub album: String,
pub genre: String,
pub date: String,
pub track: i32,
pub disc: i32,
pub track_count: i32,
pub disc_count: i32,
pub duration: i32,
pub audio_type: String,
pub user_id: uuid::Uuid,
pub song_queue_id: uuid::Uuid,
}
impl Request {
pub fn is_valid(&self) -> bool {
!self.title.is_empty()
|| !self.artist.is_empty()
|| !self.album_artist.is_empty()
|| !self.album.is_empty()
|| !self.genre.is_empty()
|| !self.date.is_empty()
|| self.track > 0
|| self.disc > 0
|| self.track_count > 0
|| self.disc_count > 0
|| self.duration > 0
|| !self.audio_type.is_empty()
|| !self.user_id.is_nil()
|| !self.song_queue_id.is_nil()
}
pub fn to_song(&self) -> icarus_models::song::Song {
icarus_models::song::Song {
id: uuid::Uuid::nil(),
title: self.title.clone(),
artist: self.artist.clone(),
album_artist: self.album_artist.clone(),
album: self.album.clone(),
genre: self.genre.clone(),
year: self.date[..3].parse().unwrap(),
track: self.track,
disc: self.disc,
track_count: self.track_count,
disc_count: self.disc_count,
duration: self.duration,
audio_type: self.audio_type.clone(),
user_id: self.user_id,
..Default::default()
}
}
}
}
pub mod get_songs {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Params {
pub id: Option<uuid::Uuid>,
}
}
}
pub mod response {
pub mod create_metadata {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::song::Song>,
}
}
pub mod get_songs {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<icarus_models::song::Song>,
}
}
pub mod delete_song {
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct SongAndCoverArt {
pub song: icarus_models::song::Song,
pub coverart: icarus_models::coverart::CoverArt,
}
#[derive(Debug, Default, serde::Deserialize, serde::Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<SongAndCoverArt>,
}
}
}
// TODO: Might make a distinction between year and date in a song's tag at some point
/// Module for song related endpoints
pub mod endpoint {
use axum::{Json, response::IntoResponse};
use crate::repo;
use crate::repo::queue as repo_queue;
// TODO: Change the name of this endpoint. Including the function name and path
/// Endpoint to create song
#[utoipa::path(
post,
path = super::super::queue::endpoints::QUEUEMETADATA,
request_body(
content = super::request::create_metadata::Request,
description = "Data needed to create the song and save it to the filesystem",
content_type = "application/json"
),
responses(
(status = 200, description = "Song created", body = super::response::create_metadata::Response),
(status = 400, description = "Error", body = super::response::create_metadata::Response),
(status = 505, description = "Error creating song", body = super::response::create_metadata::Response)
)
)]
pub async fn create_metadata(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<super::request::create_metadata::Request>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::create_metadata::Response>,
) {
let mut response = super::response::create_metadata::Response::default();
if payload.is_valid() {
let mut song = payload.to_song();
song.filename = icarus_models::song::generate_filename(
icarus_models::types::MusicType::FlacExtension,
true,
)
.unwrap();
song.directory = icarus_envy::environment::get_root_directory().await.value;
match repo_queue::song::get_data(&pool, &payload.song_queue_id).await {
Ok(data) => {
song.data = data;
let dir = std::path::Path::new(&song.directory);
if !dir.exists() {
println!("Creating directory");
match std::fs::create_dir_all(dir) {
Ok(_) => {
println!("Successfully created directory");
}
Err(err) => {
eprintln!("Error: Unable to create the directory {err:?}");
}
}
}
match song.save_to_filesystem() {
Ok(_) => match repo::song::insert(&pool, &song).await {
Ok((date_created, id)) => {
song.id = id;
song.date_created = Some(date_created);
response.message = String::from("Successful");
response.data.push(song);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = format!("{:?} song {:?}", err.to_string(), song);
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
} else {
response.message = String::from("Request body is not valid");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
// Endpoint to get songs
#[utoipa::path(
get,
path = super::super::endpoints::GETSONGS,
params(
("id" = uuid::Uuid, Path, description = "Id of song")
),
responses(
(status = 200, description = "Songs found", body = super::response::get_songs::Response),
(status = 400, description = "Error getting songs", body = super::response::get_songs::Response)
)
)]
pub async fn get_songs(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Query(params): axum::extract::Query<super::request::get_songs::Params>,
) -> (
axum::http::StatusCode,
Json<super::response::get_songs::Response>,
) {
let mut response = super::response::get_songs::Response::default();
match params.id {
Some(id) => match repo::song::get_song(&pool, &id).await {
Ok(song) => {
response.message = String::from(super::super::response::SUCCESSFUL);
response.data.push(song);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
},
None => {
response.message = String::from("Invalid parameters");
(axum::http::StatusCode::BAD_REQUEST, axum::Json(response))
}
}
}
/// Endpoint to get all songs
#[utoipa::path(
get,
path = super::super::endpoints::GETALLSONGS,
responses(
(status = 200, description = "Getting all songs", body = super::response::get_songs::Response),
(status = 404, description = "Song not found", body = super::response::get_songs::Response)
)
)]
pub async fn get_all_songs(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::get_songs::Response>,
) {
let mut response = super::response::get_songs::Response::default();
match repo::song::get_all_songs(&pool).await {
Ok(songs) => {
if songs.is_empty() {
response.message = String::from("No songs available");
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
} else {
response.message = String::from(super::super::response::SUCCESSFUL);
response.data = songs;
(axum::http::StatusCode::OK, axum::Json(response))
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
/// Ednpoint to stream song
#[utoipa::path(
get,
path = super::super::endpoints::STREAMSONG,
params(("id" = uuid::Uuid, Path, description = "Song Id")),
responses(
(status = 200, description = "Stream song", body = Vec<u8>),
(status = 500, description = "Error streaming song", body = (u64, String))
)
)]
pub async fn stream_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> impl IntoResponse {
match repo::song::get_song(&pool, &id).await {
Ok(song) => {
let song_path = song.song_path().unwrap();
let path = std::path::Path::new(&song_path);
if !path.starts_with(&song.directory) || !path.exists() {
return Err((axum::http::StatusCode::NOT_FOUND, "File not found"));
}
let file = match tokio::fs::File::open(&path).await {
Ok(file) => file,
Err(_) => return Err((axum::http::StatusCode::NOT_FOUND, "File not found")),
};
let file_size = match file.metadata().await {
Ok(meta) => meta.len(),
Err(_) => {
return Err((
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Could not read file",
));
}
};
let mime = mime_guess::from_path(path).first_or_octet_stream();
let stream = tokio_util::io::ReaderStream::new(file);
let rep = axum::response::Response::builder()
.header("content-type", mime.to_string())
.header("accept-ranges", "bytes")
.header("content-length", file_size.to_string())
.body(axum::body::Body::from_stream(stream))
.unwrap();
Ok(rep)
}
Err(_err) => Err((
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
"Could not find file",
)),
}
}
/// Endpoint to download song
#[utoipa::path(
get,
path = super::super::endpoints::DOWNLOADSONG,
params(("id" = uuid::Uuid, Path, description = "Song Id")),
responses(
(status = 200, description = "Download song", body = (u64, Vec<u8>)),
(status = 404, description = "Song not found", body = (u64, Vec<u8>)),
(status = 400, description = "Error downloading song", body = (u64, Vec<u8>))
)
)]
pub async fn download_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (axum::http::StatusCode, axum::response::Response) {
match repo::song::get_song(&pool, &id).await {
Ok(song) => match icarus_models::song::io::to_data(&song) {
Ok(data) => {
let bytes = axum::body::Bytes::from(data);
let mut response = bytes.into_response();
let headers = response.headers_mut();
headers.insert(
axum::http::header::CONTENT_TYPE,
"audio/flac".parse().unwrap(),
);
headers.insert(
axum::http::header::CONTENT_DISPOSITION,
format!("attachment; filename=\"{id}.flac\"")
.parse()
.unwrap(),
);
(axum::http::StatusCode::OK, response)
}
Err(_err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::response::Response::default(),
),
},
Err(_err) => (
axum::http::StatusCode::NOT_FOUND,
axum::response::Response::default(),
),
}
}
/// Endpoint to delete the song
#[utoipa::path(
delete,
path = super::super::endpoints::DELETESONG,
params(("id" = uuid::Uuid, Path, description = "Song Id")),
responses(
(status = 200, description = "Song deleted", body = super::response::delete_song::Response),
(status = 404, description = "Song not found", body = super::response::delete_song::Response),
(status = 500, description = "Error deleting song", body = super::response::delete_song::Response)
)
)]
pub async fn delete_song(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (
axum::http::StatusCode,
axum::Json<super::response::delete_song::Response>,
) {
let mut response = super::response::delete_song::Response::default();
match repo::song::get_song(&pool, &id).await {
Ok(song) => {
match repo::coverart::get_coverart_with_song_id(&pool, &song.id).await {
Ok(coverart) => {
let coverart_path_str = match coverart.get_path() {
Ok(path) => path,
Err(err) => {
response.message = err.to_string();
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
);
}
};
let coverart_path = std::path::Path::new(&coverart_path_str);
if coverart_path.exists() {
match repo::song::delete_song(&pool, &song.id).await {
Ok(deleted_song) => {
match repo::coverart::delete_coverart(&pool, &coverart.id).await
{
Ok(deleted_coverart) => {
match song.remove_from_filesystem() {
Ok(_) => match coverart.remove_from_filesystem() {
Ok(_) => {
response.message = String::from(
super::super::response::SUCCESSFUL,
);
response.data.push(super::response::delete_song::SongAndCoverArt{ song: deleted_song, coverart: deleted_coverart });
(
axum::http::StatusCode::OK,
axum::Json(response),
)
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response))
}
},
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::INTERNAL_SERVER_ERROR, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
Err(err) => {
response.message = err.to_string();
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
} else {
response.message =
String::from("Could not locate coverart on the filesystem");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
Err(err) => {
response.message = err.to_string();
(axum::http::StatusCode::NOT_FOUND, axum::Json(response))
}
}
}
}
+7
View File
@@ -0,0 +1,7 @@
/// Full hosting address that the application will be broadcasting
pub fn get_full() -> String {
format!("{ADDRESS}:{PORT}")
}
pub const ADDRESS: &str = "0.0.0.0";
pub const PORT: &str = "8000";
+257
View File
@@ -0,0 +1,257 @@
use std::time::Duration;
use axum::routing::{delete, get, patch, post};
use tower_http::timeout::TimeoutLayer;
use utoipa::OpenApi;
use crate::callers::coverart as coverart_caller;
use crate::callers::queue::coverart as coverart_queue_callers;
use crate::callers::queue::metadata as metadata_queue_caller;
use crate::callers::queue::song as song_queue_callers;
use crate::callers::song as song_caller;
use coverart_caller::endpoint as coverart_endpoints;
use coverart_caller::response as coverart_responses;
use coverart_queue_callers::endpoint as coverart_queue_endpoints;
use coverart_queue_callers::response as coverart_queue_responses;
use metadata_queue_caller::endpoint as metadata_queue_endpoints;
use metadata_queue_caller::response as metadata_queue_responses;
use song_caller::endpoint as song_endpoints;
use song_caller::response as song_responses;
use song_queue_callers::endpoint as song_queue_endpoints;
use song_queue_callers::response as song_queue_responses;
mod cors {
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
let cors = tower_http::cors::CorsLayer::new()
.allow_methods([
axum::http::Method::GET,
axum::http::Method::POST,
axum::http::Method::PUT,
axum::http::Method::DELETE,
]) // Specify allowed methods:cite[2]
.allow_headers([
axum::http::header::CONTENT_TYPE,
axum::http::header::AUTHORIZATION,
]) // Specify allowed headers:cite[2]
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2]
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2]
// Dynamically set the allowed origin based on the environment
match std::env::var(icarus_envy::keys::APP_ENV).as_deref() {
Ok("production") => {
// In production, allow only your specific, trusted origins
let allowed_origins_env = icarus_envy::environment::get_allowed_origins().await;
match icarus_envy::utility::delimitize(&allowed_origins_env) {
Ok(alwd) => {
let allowed_origins: Vec<axum::http::HeaderValue> = alwd
.into_iter()
.map(|a| a.parse::<axum::http::HeaderValue>().unwrap())
.collect();
cors.allow_origin(allowed_origins)
}
Err(err) => {
eprintln!("Error getting allowed origins: Error: {err:?}");
std::process::exit(-1);
}
}
}
_ => {
// Development (default): Allow localhost origins
cors.allow_origin(vec![
"http://localhost:8000".parse().unwrap(),
"http://127.0.0.1:8000".parse().unwrap(),
"http://localhost:4200".parse().unwrap(),
"http://127.0.0.1:4200".parse().unwrap(),
])
}
}
}
}
#[derive(utoipa::OpenApi)]
#[openapi(
paths(song_queue_endpoints::queue_song, song_queue_endpoints::link_user_id, song_queue_endpoints::fetch_queue_song, song_queue_endpoints::download_queued_song,
song_queue_endpoints::update_song_queue_status, song_queue_endpoints::update_song_queue, song_endpoints::create_metadata, song_queue_endpoints::wipe_data_from_song_queue, song_endpoints::get_songs, song_endpoints::get_all_songs, song_endpoints::stream_song, song_endpoints::download_song,
song_endpoints::delete_song, coverart_queue_endpoints::queue, coverart_queue_endpoints::link, coverart_queue_endpoints::fetch_coverart_no_data,
coverart_queue_endpoints::fetch_coverart_with_data, coverart_endpoints::create_coverart, coverart_queue_endpoints::wipe_data_from_coverart_queue,
coverart_endpoints::get_coverart, coverart_endpoints::download_coverart,
metadata_queue_endpoints::queue_metadata, metadata_queue_endpoints::fetch_metadata),
components(schemas(song_queue_callers::response::song_queue::Response, song_queue_callers::response::link_user_id::Response, song_queue_callers::response::fetch_queue_song::Response,
song_queue_responses::update_status::Response, song_queue_callers::response::update_song_queue::Response, song_responses::create_metadata::Response,
song_queue_callers::response::wipe_data_from_song_queue::Response, song_responses::get_songs::Response, song_responses::delete_song::Response,
coverart_queue_responses::queue::Response, coverart_queue_responses::link::Response, coverart_queue_responses::fetch_coverart_no_data::Response,
coverart_queue_responses::fetch_coverart_with_data::Response, coverart_responses::create_coverart::Response,
coverart_queue_responses::wipe_data_from_coverart_queue::Response, coverart_responses::get_coverart::Response,
metadata_queue_responses::queue_metadata::Response, metadata_queue_responses::fetch_metadata::Response)),
tags(
(name = "Icarus API", description = "Web API to manage music")
)
)]
struct ApiDoc;
pub async fn routes() -> axum::Router {
axum::Router::new()
.route(crate::callers::endpoints::ROOT, get(crate::callers::root))
.route(
crate::callers::queue::endpoints::QUEUESONG,
post(crate::callers::queue::song::endpoint::queue_song).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUESONG,
patch(crate::callers::queue::song::endpoint::update_song_queue_status).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUESONGLINKUSERID,
patch(crate::callers::queue::song::endpoint::link_user_id).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUESONGDATA,
get(crate::callers::queue::song::endpoint::download_queued_song).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::NEXTQUEUESONG,
get(crate::callers::queue::song::endpoint::fetch_queue_song).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUESONGUPDATE,
patch(crate::callers::queue::song::endpoint::update_song_queue).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUESONGDATAWIPE,
patch(crate::callers::queue::song::endpoint::wipe_data_from_song_queue).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUEMETADATA,
post(crate::callers::queue::metadata::endpoint::queue_metadata).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUEMETADATA,
get(crate::callers::queue::metadata::endpoint::fetch_metadata).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUECOVERART,
post(crate::callers::queue::coverart::endpoint::queue).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUECOVERARTDATA,
get(crate::callers::queue::coverart::endpoint::fetch_coverart_with_data).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUECOVERART,
get(crate::callers::queue::coverart::endpoint::fetch_coverart_no_data).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUECOVERARTLINK,
patch(crate::callers::queue::coverart::endpoint::link).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::queue::endpoints::QUEUECOVERARTDATAWIPE,
patch(crate::callers::queue::coverart::endpoint::wipe_data_from_coverart_queue)
.route_layer(axum::middleware::from_fn(
crate::auth::auth::<axum::body::Body>,
)),
)
.route(
crate::callers::endpoints::CREATESONG,
post(crate::callers::song::endpoint::create_metadata).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::CREATECOVERART,
post(crate::callers::coverart::endpoint::create_coverart).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::GETSONGS,
get(crate::callers::song::endpoint::get_songs).route_layer(axum::middleware::from_fn(
crate::auth::auth::<axum::body::Body>,
)),
)
.route(
crate::callers::endpoints::GETCOVERART,
get(crate::callers::coverart::endpoint::get_coverart).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::DOWNLOADCOVERART,
get(crate::callers::coverart::endpoint::download_coverart).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::STREAMSONG,
get(crate::callers::song::endpoint::stream_song).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::DOWNLOADSONG,
get(crate::callers::song::endpoint::download_song).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::DELETESONG,
delete(crate::callers::song::endpoint::delete_song).route_layer(
axum::middleware::from_fn(crate::auth::auth::<axum::body::Body>),
),
)
.route(
crate::callers::endpoints::GETALLSONGS,
get(crate::callers::song::endpoint::get_all_songs),
)
.layer(cors::configure_cors().await)
}
pub async fn app() -> axum::Router {
let pool = crate::db::create_pool()
.await
.expect("Failed to create pool");
crate::db::migrations(&pool).await;
let cors = cors::configure_cors().await;
routes()
.await
.merge(
utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
.url("/api-docs/openapi.json", ApiDoc::openapi()),
)
.layer(axum::Extension(pool))
.layer(axum::extract::DefaultBodyLimit::max(1024 * 1024 * 1024))
.layer(TimeoutLayer::with_status_code(
axum::http::StatusCode::OK,
Duration::from_secs(300),
))
.layer(cors)
}
+2
View File
@@ -0,0 +1,2 @@
pub mod host;
pub mod init;
+24
View File
@@ -0,0 +1,24 @@
use sqlx::postgres::PgPoolOptions;
pub mod connection_settings {
pub const MAXCONN: u32 = 10;
}
pub async fn create_pool() -> Result<sqlx::PgPool, sqlx::Error> {
let database_url = icarus_envy::environment::get_db_url().await.value;
println!("Database url: {database_url}");
PgPoolOptions::new()
.max_connections(connection_settings::MAXCONN)
.connect(&database_url)
.await
}
pub async fn migrations(pool: &sqlx::PgPool) {
// Run migrations using the sqlx::migrate! macro
// Assumes your migrations are in a ./migrations folder relative to Cargo.toml
sqlx::migrate!("./migrations")
.run(pool)
.await
.expect("Failed to run migrations");
}
+2412
View File
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More