Compare commits
134 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 703fc49f32 | |||
| e98e055de0 | |||
| a8603361c0 | |||
| dbda9a3897 | |||
| a987e438c4 | |||
| a150d34c6c | |||
| 34e292bea9 | |||
| c9bcea5f98 | |||
| 6c9e4809a9 | |||
| 4c5bd1ccde | |||
| 5a2639cb59 | |||
| fd9df41f51 | |||
| 7fdea3491f | |||
| 3cde57dca8 | |||
| 8c93429647 | |||
| 5721c387ea | |||
| a624702813 | |||
| 9c67bfd8a8 | |||
| fbec3305b1 | |||
| fa792be9cc | |||
| 6f2e8d6e17 | |||
| eb1f19a96e | |||
| bb766acf4e | |||
| 95688cccfa | |||
| e2485cec44 | |||
| df1562f5e7 | |||
| e00e9cf185 | |||
| f0d2b9de71 | |||
| f0a0bee22b | |||
| 0b73c055aa | |||
| d4c025511d | |||
| b2a4faec76 | |||
| 7d27aed314 | |||
| 961f99b744 | |||
| b1f5c5f604 | |||
| ddb0bf27f8 | |||
| d491767de4 | |||
| 8755276b48 | |||
| fd41d25c4c | |||
| 5e3ca1861d | |||
| db7350b550 | |||
| f823a99984 | |||
| 2823452198 | |||
| 0ba2d4e8b9 | |||
| 4fdd660988 | |||
| b6fe9a070c | |||
| 6e4eeafe13 | |||
| 6f320acb7c | |||
| 9dd7ffa2b6 | |||
| fbcbd41809 | |||
| 01d315e25e | |||
| caf9f08d8a | |||
| 7227eb9420 | |||
| 12c4f56a22 | |||
| 6d650b7962 | |||
| 73bb417bde | |||
| b0277077f4 | |||
| 3edf6424d0 | |||
| dcb51448aa | |||
| 9d90247bf8 | |||
| 86e54e086a | |||
| fd3ce9f96a | |||
| a89580ac70 | |||
| 8900afdfd2 | |||
| 4b3fa78336 | |||
| 71656aa940 | |||
| 562bc87822 | |||
| ebb15b7cdb | |||
| 270b7d059c | |||
| 23c50de468 | |||
| ececcb5ba3 | |||
| 8658dd34ab | |||
| c17c9cd329 | |||
| 37cfda84b5 | |||
| 3ee17a77a8 | |||
| 522be59973 | |||
| 712a0a9a4a | |||
| 74569d85b6 | |||
| b660f8361f | |||
| d460b5d5d6 | |||
| 4a1c1f1f78 | |||
| 66b5944f92 | |||
| 80628292e2 | |||
| 57f4ec1261 | |||
| c191d7ee7a | |||
| 73bfff3940 | |||
| 38c056cc99 | |||
| 1643f78720 | |||
| 06bb52dfa5 | |||
| ab89d1602f | |||
| 640971dea8 | |||
| 664b0d520b | |||
| 11fe1f29e1 | |||
| 05b5de0939 | |||
| d5944c470b | |||
| 00ef8d0242 | |||
| 77c6ee00ea | |||
| 1bfd0a4931 | |||
| 6c3ce69873 | |||
| a423e6e220 | |||
| f8ec65fd29 | |||
| 665407aac5 | |||
| e5bea187f4 | |||
| fd0f487615 | |||
| d48716a54f | |||
| 2cc13ac9bb | |||
| 467a9d7e0f | |||
| f0551a4801 | |||
| 2cd8c83e28 | |||
| 9797897b76 | |||
| 27cc80d114 | |||
| 27ee3d6ba5 | |||
| 1b6e70ce12 | |||
| 5669cdbdd0 | |||
| 3a6e0f64bc | |||
| aa0a1ab5fe | |||
| b529731c95 | |||
| 64e6f33d7c | |||
| 023298c6f8 | |||
| f8d9c8e4a7 | |||
| 471fa71789 | |||
| edaea68296 | |||
| 8600d9b6bc | |||
| 922e527819 | |||
| 46f0da4a5f | |||
| 16839b9bf8 | |||
| 552d5dcd25 | |||
| cadcf33ed6 | |||
| 4f46f2ed94 | |||
| 560773bfff | |||
| 43623d07c3 | |||
| b93d436c29 | |||
| d80842e517 | |||
| 2c3152a9a5 |
@@ -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/
|
||||
@@ -0,0 +1,7 @@
|
||||
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}
|
||||
@@ -0,0 +1,7 @@
|
||||
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}
|
||||
@@ -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@v3
|
||||
with:
|
||||
fetch-depth: 0 # Important for git describe --tags
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
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 }}
|
||||
@@ -0,0 +1,77 @@
|
||||
name: Rust CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ "v0.2" ]
|
||||
pull_request:
|
||||
branches: [ "v0.2" ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-24.04
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17.5
|
||||
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@v4
|
||||
|
||||
- name: Install Rust 1.88.0
|
||||
uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: 1.88.0
|
||||
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: cargo test --verbose
|
||||
|
||||
- name: Run clippy
|
||||
run: cargo clippy -- -D warnings
|
||||
|
||||
- name: Run rustfmt
|
||||
run: cargo fmt --all -- --check
|
||||
@@ -1,8 +1,9 @@
|
||||
################################################################################
|
||||
# This .gitignore file was automatically created by Microsoft(R) Visual Studio.
|
||||
################################################################################
|
||||
# Added by cargo
|
||||
|
||||
/.vs/Icarus
|
||||
/bin/Debug/netcoreapp2.2
|
||||
/Migrations
|
||||
/obj
|
||||
/target
|
||||
.env
|
||||
.env.docker
|
||||
.env.local
|
||||
|
||||
.DS_STORE
|
||||
Storage/
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"dev": {
|
||||
"migrations": "./migrations"
|
||||
},
|
||||
"test": {
|
||||
"migrations": "./test_migrations"
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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/
|
||||
@@ -0,0 +1,28 @@
|
||||
[package]
|
||||
name = "icarus"
|
||||
version = "0.1.97"
|
||||
edition = "2024"
|
||||
rust-version = "1.88"
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.8.4", features = ["multipart"] }
|
||||
serde = { version = "1.0.219", features = ["derive"] }
|
||||
serde_json = { version = "1.0.140" }
|
||||
tower = { version = "0.5.2", features = ["full"] }
|
||||
tokio = { version = "1.45.1", features = ["full"] }
|
||||
tokio-util = { version = "0.7.15", features = ["io"] }
|
||||
tower-http = { version = "0.6.6", features = ["timeout"] }
|
||||
tracing-subscriber = "0.3.19"
|
||||
futures = { version = "0.3.31" }
|
||||
mime_guess = { version = "2.0.5" }
|
||||
uuid = { version = "1.17.0", features = ["v4", "serde"] }
|
||||
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio-native-tls", "time", "uuid"] }
|
||||
time = { version = "0.3.41", features = ["formatting", "macros", "parsing", "serde"] }
|
||||
icarus_meta = { git = "ssh://git@git.kundeng.us/phoenix/icarus_meta.git", tag = "v0.3.0-devel-f4b71de969-680" }
|
||||
icarus_models = { git = "ssh://git@git.kundeng.us/phoenix/icarus_models.git", tag = "v0.5.1-devel-1c5de9dc26-111" }
|
||||
icarus_envy = { git = "ssh://git@git.kundeng.us/phoenix/icarus_envy.git", tag = "v0.3.0-devel-d73fba9899-006" }
|
||||
|
||||
[dev-dependencies]
|
||||
common-multipart-rfc7578 = { version = "0.7.0" }
|
||||
url = { version = "2.5.4" }
|
||||
tempfile = { version = "3.20.0" }
|
||||
@@ -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";
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
|
||||
using Icarus.Controllers.Utilities;
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Contexts;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class AlbumManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
|
||||
using Icarus.Controllers.Utilities;
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Contexts;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class ArtistManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
using System;
|
||||
|
||||
using NLog;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class BaseManager
|
||||
{
|
||||
#region Fields
|
||||
protected static Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,127 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
using Icarus.Constants;
|
||||
using Icarus.Controllers.Utilities;
|
||||
using Icarus.Database.Repositories;
|
||||
using Icarus.Models;
|
||||
using Icarus.Types;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class CoverArtManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
private string _rootCoverArtPath;
|
||||
private byte[] _stockCoverArt = null;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public CoverArtManager(string rootPath)
|
||||
{
|
||||
_rootCoverArtPath = rootPath;
|
||||
Initialize();
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public void SaveCoverArtToDatabase(ref Song song, ref CoverArt coverArt,
|
||||
CoverArtRepository coverArtRepository)
|
||||
{
|
||||
_logger.Info("Saving cover art record to the database");
|
||||
coverArtRepository.SaveCoverArt(coverArt);
|
||||
|
||||
coverArt = coverArtRepository.GetCoverArt(CoverArtField.SongTitle,
|
||||
coverArt);
|
||||
|
||||
song.CoverArtId = coverArt.CoverArtId;
|
||||
}
|
||||
public void DeleteCoverArtFromDatabase(CoverArt coverArt,
|
||||
CoverArtRepository coverArtRepository)
|
||||
{
|
||||
_logger.Info("Attempting to delete cover art from the database");
|
||||
coverArtRepository.DeleteCoverArt(coverArt);
|
||||
}
|
||||
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);
|
||||
dirMgr.CreateDirectory(song);
|
||||
var imagePath = dirMgr.SongDirectory + song.Title + ".png";
|
||||
var coverArt = new CoverArt
|
||||
{
|
||||
SongTitle = song.Title,
|
||||
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 + "CoverArt.png";
|
||||
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;
|
||||
}
|
||||
|
||||
private void Initialize()
|
||||
{
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -1,241 +0,0 @@
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
|
||||
using Icarus.Models;
|
||||
using Icarus.Types;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class DirectoryManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
private IConfiguration _config;
|
||||
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()
|
||||
{
|
||||
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)
|
||||
{
|
||||
Console.WriteLine($"An error occurred {ex.Message}");
|
||||
}
|
||||
}
|
||||
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()
|
||||
{
|
||||
string directory = _rootSongDirectory;
|
||||
directory += $@"{_song.Artist}/{_song.AlbumTitle}/";
|
||||
|
||||
return directory;
|
||||
}
|
||||
private string AlbumDirectory(Song song)
|
||||
{
|
||||
var directory = _rootSongDirectory;
|
||||
directory += $@"{song.Artist}/{song.AlbumTitle}/";
|
||||
Console.WriteLine($"Album directory {directory}");
|
||||
|
||||
return directory;
|
||||
}
|
||||
private string ArtistDirectory()
|
||||
{
|
||||
var directory = _rootSongDirectory;
|
||||
directory += $@"{_song.Artist}/";
|
||||
|
||||
return directory;
|
||||
}
|
||||
private string ArtistDirectory(Song song)
|
||||
{
|
||||
var directory = _rootSongDirectory;
|
||||
directory += $@"{song.Artist}/";
|
||||
Console.WriteLine($"Artist directory {directory}");
|
||||
|
||||
return directory;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
|
||||
using Icarus.Controllers.Utilities;
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Contexts;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class GenreManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Newtonsoft.Json;
|
||||
using RestSharp;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class TokenManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
private IConfiguration _config;
|
||||
private string _clientId;
|
||||
private string _clientSecret;
|
||||
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<Token>(response.Content);
|
||||
_logger.Info("Response deserialized");
|
||||
|
||||
return new LoginResult
|
||||
{
|
||||
UserId = user.Id, Username = user.Username, Token = tokenResult.AccessToken,
|
||||
TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration,
|
||||
Message = "Successfully retrieved token"
|
||||
};
|
||||
}
|
||||
|
||||
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"]}";
|
||||
|
||||
PrintCredentials();
|
||||
}
|
||||
|
||||
#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 Token
|
||||
{
|
||||
[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
|
||||
}
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
|
||||
using Icarus.Controllers.Utilities;
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Contexts;
|
||||
|
||||
namespace Icarus.Controllers.Managers
|
||||
{
|
||||
public class YearManager : BaseManager
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,321 +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.Id}");
|
||||
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($"YearId: {song.YearId}");
|
||||
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;
|
||||
|
||||
song.Title = _title;
|
||||
song.Artist = _artist;
|
||||
song.AlbumTitle = _album;
|
||||
song.Genre = _genre;
|
||||
song.Year = _year;
|
||||
song.Duration = _duration;
|
||||
}
|
||||
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 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 song)
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.WriteLine("Updating song metadata");
|
||||
_logger.Info("Updating song metadata");
|
||||
var filePath = song.SongPath;
|
||||
TagLib.File fileTag = TagLib.File.Create(filePath);
|
||||
fileTag.Tag.Title = song.Title;
|
||||
fileTag.Tag.Genres = new []{song.Genre};
|
||||
fileTag.Save();
|
||||
Console.WriteLine("Song metadata updated");
|
||||
_logger.Info("Song metadata updated");
|
||||
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
Console.WriteLine($"An error occurred: \n{msg}");
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
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;
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
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 = new Song
|
||||
{
|
||||
Id = song.Id,
|
||||
Title = song.Title,
|
||||
AlbumTitle = song.AlbumTitle,
|
||||
Artist = song.Artist,
|
||||
Genre = song.Genre,
|
||||
Year = song.Year,
|
||||
Duration = song.Duration,
|
||||
Filename = song.Filename,
|
||||
SongPath = song.SongPath
|
||||
};
|
||||
}
|
||||
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.Album}");
|
||||
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);
|
||||
|
||||
if (song.Year == null)
|
||||
songValues["Year"] = true;
|
||||
else if (song.Year==0)
|
||||
songValues["Year"] = true;
|
||||
else
|
||||
songValues["Year"] = false;
|
||||
|
||||
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;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -1,129 +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 = System.IO.File.ReadAllBytes(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
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/album")]
|
||||
[ApiController]
|
||||
public class AlbumController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private readonly ILogger<AlbumController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public AlbumController(ILogger<AlbumController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP Routes
|
||||
[HttpGet]
|
||||
[Authorize("read:albums")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
List<Album> albums = new List<Album>();
|
||||
|
||||
AlbumRepository albumStoreContext = HttpContext.RequestServices
|
||||
.GetService(typeof(AlbumRepository)) as AlbumRepository;
|
||||
|
||||
albums = albumStoreContext.GetAlbums();
|
||||
|
||||
if (albums.Count > 0)
|
||||
return Ok(albums);
|
||||
else
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("read:albums")]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
Album album = new Album
|
||||
{
|
||||
AlbumId = id
|
||||
};
|
||||
|
||||
AlbumRepository albumStoreContext = HttpContext.RequestServices
|
||||
.GetService(typeof(AlbumRepository)) as AlbumRepository;
|
||||
|
||||
if (albumStoreContext.DoesAlbumExist(album))
|
||||
{
|
||||
album = albumStoreContext.GetAlbum(album);
|
||||
|
||||
return Ok(album);
|
||||
}
|
||||
else
|
||||
return NotFound();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
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.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/artist")]
|
||||
[ApiController]
|
||||
public class ArtistController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private readonly ILogger<ArtistController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public ArtistController(ILogger<ArtistController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP Routes
|
||||
[HttpGet]
|
||||
[Authorize("read:artists")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
ArtistRepository artistStoreContext = HttpContext.RequestServices
|
||||
.GetService(typeof(ArtistRepository)) as ArtistRepository;
|
||||
|
||||
var artists = artistStoreContext.GetArtists();
|
||||
|
||||
if (artists.Count > 0)
|
||||
return Ok(artists);
|
||||
else
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("read:artists")]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
Artist artist = new Artist
|
||||
{
|
||||
ArtistId = id
|
||||
};
|
||||
|
||||
ArtistRepository artistStoreContext = HttpContext.RequestServices
|
||||
.GetService(typeof(ArtistRepository)) as ArtistRepository;
|
||||
|
||||
if (artistStoreContext.DoesArtistExist(artist))
|
||||
{
|
||||
artist = artistStoreContext.GetArtist(artist);
|
||||
|
||||
return Ok(artist);
|
||||
}
|
||||
else
|
||||
return NotFound();
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Icarus.Controllers.Managers;
|
||||
using Icarus.Database.Repositories;
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/coverart")]
|
||||
[ApiController]
|
||||
public class CoverArtController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private readonly ILogger<CoverArtController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public CoverArtController(ILogger<CoverArtController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP Routes
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("download:cover_art")]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
var coverArt = new CoverArt { CoverArtId = id };
|
||||
|
||||
var coverArtRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService(
|
||||
typeof(CoverArtRepository)) as CoverArtRepository;
|
||||
|
||||
coverArt = coverArtRepository.GetCoverArt(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
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/genre")]
|
||||
[ApiController]
|
||||
public class GenreController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private readonly ILogger<GenreController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public GenreController(ILogger<GenreController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP Routes
|
||||
[HttpGet]
|
||||
[Authorize("read:genre")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
var genres = new List<Genre>();
|
||||
|
||||
var genreStore = HttpContext.RequestServices
|
||||
.GetService(typeof(GenreRepository)) as GenreRepository;
|
||||
|
||||
genres = genreStore.GetGenres();
|
||||
|
||||
if (genres.Count > 0)
|
||||
return Ok(genres);
|
||||
else
|
||||
return NotFound(new List<Genre>());
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("read:genre")]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
var genre = new Genre
|
||||
{
|
||||
GenreId = id
|
||||
};
|
||||
|
||||
var genreStore = HttpContext.RequestServices
|
||||
.GetService(typeof(GenreRepository)) as GenreRepository;
|
||||
|
||||
if (genreStore.DoesGenreExist(genre))
|
||||
{
|
||||
genre = genreStore.GetGenre(genre);
|
||||
|
||||
return Ok(genre);
|
||||
}
|
||||
else
|
||||
return NotFound(new Genre());
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,88 +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 Microsoft.Extensions.Logging;
|
||||
|
||||
using Icarus.Controllers.Managers;
|
||||
using Icarus.Controllers.Utilities;
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/login")]
|
||||
[ApiController]
|
||||
public class LoginController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private IConfiguration _config;
|
||||
private ILogger<LoginController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Contructors
|
||||
public LoginController(IConfiguration config, ILogger<LoginController> logger)
|
||||
{
|
||||
_config = config;
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP endpoints
|
||||
public IActionResult Post([FromBody] User user)
|
||||
{
|
||||
UserRepository context = HttpContext.RequestServices
|
||||
.GetService(typeof(UserRepository)) as UserRepository;
|
||||
|
||||
_logger.LogInformation("Starting process of validating credentials");
|
||||
|
||||
var message = "Invalid credentials";
|
||||
var password = user.Password;
|
||||
|
||||
var loginRes = new LoginResult
|
||||
{
|
||||
Username = user.Username
|
||||
};
|
||||
|
||||
if (context.DoesUserExist(user))
|
||||
{
|
||||
user = context.RetrieveUser(user);
|
||||
|
||||
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.RetrieveLoginResult(user);
|
||||
|
||||
return Ok(loginRes);
|
||||
}
|
||||
else
|
||||
{
|
||||
loginRes.Message = message;
|
||||
|
||||
return NotFound(loginRes);
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,70 +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.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/register")]
|
||||
[ApiController]
|
||||
public class RegisterController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private IConfiguration _config;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructor
|
||||
public RegisterController(IConfiguration config)
|
||||
{
|
||||
_config = config;
|
||||
}
|
||||
#endregion
|
||||
|
||||
[HttpPost]
|
||||
public IActionResult Post([FromBody] User user)
|
||||
{
|
||||
PasswordEncryption pe = new PasswordEncryption();
|
||||
user.Password = pe.HashPassword(user);
|
||||
user.EmailVerified = false;
|
||||
|
||||
UserRepository context = HttpContext.RequestServices
|
||||
.GetService(typeof(UserRepository)) as UserRepository;
|
||||
|
||||
context.SaveUser(user);
|
||||
|
||||
var registerResult = new RegisterResult
|
||||
{
|
||||
Username = user.Username
|
||||
};
|
||||
|
||||
if (context.DoesUserExist(user))
|
||||
{
|
||||
registerResult.Message = "Successful registration";
|
||||
registerResult.SuccessfullyRegistered = true;
|
||||
|
||||
return Ok(registerResult);
|
||||
}
|
||||
else
|
||||
{
|
||||
registerResult.Message = "Registration failed";
|
||||
registerResult.SuccessfullyRegistered = false;
|
||||
|
||||
return Ok(registerResult);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/song/compressed/data")]
|
||||
[ApiController]
|
||||
public class SongCompressedDataController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private IConfiguration _config;
|
||||
private string _songTempDir;
|
||||
private string _archiveDir;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructor
|
||||
public SongCompressedDataController(IConfiguration config)
|
||||
{
|
||||
_config = config;
|
||||
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
|
||||
_archiveDir = _config.GetValue<string>("ArchivePath");
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region API Routes
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("download:songs")]
|
||||
public async Task<IActionResult> Get(int id)
|
||||
{
|
||||
SongRepository context = HttpContext.RequestServices
|
||||
.GetService(typeof(SongRepository)) as SongRepository;
|
||||
|
||||
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.GetSong(id));
|
||||
|
||||
return File(song.Data, "application/x-msdownload", cmp.CompressedSongFilename);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,116 +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.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/song")]
|
||||
[ApiController]
|
||||
public class SongController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private readonly ILogger<SongController> _logger;
|
||||
private IConfiguration _config;
|
||||
private SongManager _songMgr;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructor
|
||||
public SongController(IConfiguration config, ILogger<SongController> logger)
|
||||
{
|
||||
_config = config;
|
||||
_logger = logger;
|
||||
_songMgr = new SongManager(config);
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
[HttpGet]
|
||||
[Authorize("read:song_details")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
List<Song> songs = new List<Song>();
|
||||
Console.WriteLine("Attemtping to retrieve songs");
|
||||
_logger.LogInformation("Attempting to retrieve songs");
|
||||
|
||||
SongRepository context = HttpContext.RequestServices
|
||||
.GetService(typeof(SongRepository)) as SongRepository;
|
||||
|
||||
songs = context.GetAllSongs();
|
||||
|
||||
if (songs.Count > 0)
|
||||
return Ok(songs);
|
||||
else
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("read:song_details")]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
SongRepository context = HttpContext.RequestServices
|
||||
.GetService(typeof(SongRepository)) as SongRepository;
|
||||
|
||||
Song song = new Song { Id = id };
|
||||
song = context.GetSong(song);
|
||||
|
||||
Console.WriteLine("Here");
|
||||
|
||||
if (song.Id != 0)
|
||||
return Ok(song);
|
||||
else
|
||||
return NotFound();
|
||||
}
|
||||
|
||||
[Authorize("update:songs")]
|
||||
[HttpPut("{id}")]
|
||||
public IActionResult Put(int id, [FromBody] Song song)
|
||||
{
|
||||
SongRepository context = HttpContext.RequestServices
|
||||
.GetService(typeof(SongRepository)) as SongRepository;
|
||||
|
||||
ArtistRepository artistStore = HttpContext.RequestServices
|
||||
.GetService(typeof(ArtistRepository)) as ArtistRepository;
|
||||
|
||||
AlbumRepository albumStore = HttpContext.RequestServices
|
||||
.GetService(typeof(AlbumRepository)) as AlbumRepository;
|
||||
|
||||
GenreRepository genreStore = HttpContext.RequestServices
|
||||
.GetService(typeof(GenreRepository)) as GenreRepository;
|
||||
|
||||
YearRepository yearStore = HttpContext.RequestServices
|
||||
.GetService(typeof(YearRepository)) as YearRepository;
|
||||
|
||||
song.Id = id;
|
||||
Console.WriteLine("Retrieving filepath of song");
|
||||
_logger.LogInformation("Retrieving filepath of song");
|
||||
|
||||
if (!context.DoesSongExist(song))
|
||||
return NotFound(new SongResult
|
||||
{
|
||||
Message = "Song does not exist"
|
||||
});
|
||||
|
||||
var songRes = _songMgr.UpdateSong(song, context, albumStore, artistStore, genreStore,
|
||||
yearStore);
|
||||
|
||||
return Ok(songRes);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,154 +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 Icarus.Controllers.Managers;
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Contexts;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/song/data")]
|
||||
[ApiController]
|
||||
public class SongDataController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private SongRepository _songRepository;
|
||||
private AlbumRepository _albumRepository;
|
||||
private ArtistRepository _artistRepository;
|
||||
private GenreRepository _genreRepository;
|
||||
private YearRepository _yearRepository;
|
||||
private CoverArtRepository _coverArtRepository;
|
||||
private IConfiguration _config;
|
||||
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;
|
||||
_logger = logger;
|
||||
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
|
||||
_songMgr = new SongManager(config, _songTempDir);
|
||||
}
|
||||
#endregion
|
||||
|
||||
private void Initialize()
|
||||
{
|
||||
_songRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService
|
||||
(typeof(SongRepository)) as SongRepository;
|
||||
|
||||
_albumRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService(typeof(AlbumRepository)) as AlbumRepository;
|
||||
|
||||
_artistRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService(typeof(ArtistRepository)) as ArtistRepository;
|
||||
|
||||
_genreRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService(typeof(GenreRepository)) as GenreRepository;
|
||||
|
||||
_yearRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService(typeof(YearRepository)) as YearRepository;
|
||||
|
||||
_coverArtRepository = HttpContext
|
||||
.RequestServices
|
||||
.GetService(typeof(CoverArtRepository)) as CoverArtRepository;
|
||||
}
|
||||
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Route("private-scoped")]
|
||||
[Authorize("download:songs")]
|
||||
public async Task<IActionResult> Get(int id)
|
||||
{
|
||||
Initialize();
|
||||
var songMetaData = _songRepository.GetSong(id);
|
||||
|
||||
SongData song = await _songMgr.RetrieveSong(songMetaData);
|
||||
|
||||
return File(song.Data, "application/x-msdownload", songMetaData.Filename);
|
||||
}
|
||||
|
||||
[HttpPost]
|
||||
[Authorize("upload:songs")]
|
||||
public async Task Post([FromForm(Name = "file")] List<IFormFile> songData)
|
||||
{
|
||||
try
|
||||
{
|
||||
Initialize();
|
||||
|
||||
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}");
|
||||
|
||||
await _songMgr.SaveSongToFileSystem(sng, _songRepository,
|
||||
_albumRepository, _artistRepository,
|
||||
_genreRepository, _yearRepository, _coverArtRepository);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.LogError(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
[HttpDelete("{id}")]
|
||||
[Authorize("delete:songs")]
|
||||
public IActionResult Delete(int id)
|
||||
{
|
||||
Initialize();
|
||||
|
||||
var songMetaData = new Song{ Id = id };
|
||||
Console.WriteLine($"Id {songMetaData.Id}");
|
||||
songMetaData = _songRepository.GetSong(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, _songRepository,
|
||||
_albumRepository, _artistRepository,
|
||||
_genreRepository, _yearRepository,
|
||||
_coverArtRepository);
|
||||
|
||||
return Ok();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,64 +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.Logging;
|
||||
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus.Controllers.V1
|
||||
{
|
||||
[Route("api/v1/song/stream")]
|
||||
[ApiController]
|
||||
public class SongStreamController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private ILogger<SongStreamController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructor
|
||||
public SongStreamController(ILogger<SongStreamController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP endpoints
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("stream:songs")]
|
||||
public async Task<IActionResult> Get(int id)
|
||||
{
|
||||
var songStore= HttpContext.RequestServices
|
||||
.GetService(typeof(SongRepository)) as SongRepository;
|
||||
|
||||
var song = songStore.GetSong(new Song { Id = id });
|
||||
|
||||
var mem = new MemoryStream();
|
||||
|
||||
using (var stream = new FileStream(song.SongPath, FileMode.Open, FileAccess.Read))
|
||||
await stream.CopyToAsync(mem);
|
||||
|
||||
mem.Position = 0;
|
||||
|
||||
_logger.LogInformation("Starting to stream song...>");
|
||||
Console.WriteLine("Starting to streamsong...");
|
||||
|
||||
return File(mem, "application/octet-stream", Path.GetFileName(song.SongPath));
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
using Icarus.Models;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus.Controller.V1
|
||||
{
|
||||
[Route("api/v1/year")]
|
||||
[ApiController]
|
||||
public class YearController : ControllerBase
|
||||
{
|
||||
#region Fields
|
||||
private readonly ILogger<YearController> _logger;
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public YearController(ILogger<YearController> logger)
|
||||
{
|
||||
_logger = logger;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region HTTP Routes
|
||||
[HttpGet]
|
||||
[Authorize("read:year")]
|
||||
public IActionResult Get()
|
||||
{
|
||||
var yearValues = new List<Year>();
|
||||
|
||||
var yearStore = HttpContext.RequestServices
|
||||
.GetService(typeof(YearRepository)) as YearRepository;
|
||||
|
||||
yearValues = yearStore.GetSongYears();
|
||||
|
||||
if (yearValues.Count > 0)
|
||||
return Ok(yearValues);
|
||||
else
|
||||
return NotFound(new List<Year>());
|
||||
}
|
||||
|
||||
[HttpGet("{id}")]
|
||||
[Authorize("read:year")]
|
||||
public IActionResult Get(int id)
|
||||
{
|
||||
var year = new Year
|
||||
{
|
||||
YearId = id
|
||||
};
|
||||
|
||||
var yearStore = HttpContext.RequestServices
|
||||
.GetService(typeof(YearRepository)) as YearRepository;
|
||||
|
||||
if (yearStore.DoesYearExist(year))
|
||||
{
|
||||
year = yearStore.GetSongYear(year);
|
||||
|
||||
return Ok(year);
|
||||
}
|
||||
else
|
||||
return NotFound(new Year());
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class AlbumContext : DbContext
|
||||
{
|
||||
public DbSet<Album> Albums { get; set; }
|
||||
|
||||
public AlbumContext(DbContextOptions<AlbumContext> options) : base(options) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Album>()
|
||||
.ToTable("Album");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class ArtistContext : DbContext
|
||||
{
|
||||
public DbSet<Artist> Artists { get; set; }
|
||||
|
||||
public ArtistContext(DbContextOptions<ArtistContext> options) : base (options) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Artist>()
|
||||
.ToTable("Artist");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class CoverArtContext : DbContext
|
||||
{
|
||||
public DbSet<CoverArt> CoverArtImages { get; set; }
|
||||
|
||||
public CoverArtContext(DbContextOptions<CoverArtContext> options) : base(options) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<CoverArt>()
|
||||
.ToTable("CoverArt");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class GenreContext : DbContext
|
||||
{
|
||||
public DbSet<Genre> Genres { get; set; }
|
||||
public GenreContext(DbContextOptions<GenreContext> options) : base(options) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Genre>()
|
||||
.ToTable("Genre");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class SongContext : DbContext
|
||||
{
|
||||
public DbSet<Song> Songs { get; set; }
|
||||
|
||||
|
||||
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.YearId)
|
||||
.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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class UserContext : DbContext
|
||||
{
|
||||
public DbSet<User> Users { get; set; }
|
||||
|
||||
|
||||
public UserContext(DbContextOptions<UserContext> options) : base(options) { }
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Contexts
|
||||
{
|
||||
public class YearContext : DbContext
|
||||
{
|
||||
public DbSet<Year> YearValues { get; set; }
|
||||
|
||||
public YearContext(DbContextOptions<YearContext> options) : base(options) { }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
modelBuilder.Entity<Year>()
|
||||
.ToTable("Year");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,385 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class AlbumRepository : BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public AlbumRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public List<Album> GetAlbumWithoutCount()
|
||||
{
|
||||
var albums = new List<Album>();
|
||||
|
||||
if (AnyAlbums())
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT * FROM Album";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
albums = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return albums;
|
||||
}
|
||||
public List<Album> GetAlbums()
|
||||
{
|
||||
List<Album> albums = new List<Album>();
|
||||
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT alb.*,COUNT(*) AS SongCount FROM Album alb " +
|
||||
"LEFT JOIN Song sng ON alb.AlbumId=sng.AlbumId WHERE " +
|
||||
"alb.AlbumId=sng.AlbumId GROUP BY alb.AlbumId";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
albums = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return albums;
|
||||
}
|
||||
|
||||
public Album GetAlbum(Album album)
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT alb.*, COUNT(*) AS SongCount FROM Album alb " +
|
||||
"LEFT JOIN Song sng ON alb.AlbumId=sng.AlbumId WHERE "+
|
||||
"alb.AlbumId=@AlbumId LIMIT 1";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@AlbumId", album.AlbumId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
album = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return album;
|
||||
}
|
||||
public Album GetAlbum(Song song)
|
||||
{
|
||||
var album = new Album();
|
||||
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT alb.*, 0 AS SongCount FROM Album alb " +
|
||||
"WHERE alb.Title=@Title LIMIT 1";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
Console.WriteLine($"Album title {song.AlbumTitle}");
|
||||
cmd.Parameters.AddWithValue("@Title", song.AlbumTitle);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
album = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return album;
|
||||
}
|
||||
public Album GetAlbum(Song song, bool retrieveCount)
|
||||
{
|
||||
var album = new Album();
|
||||
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = string.Empty;
|
||||
if (retrieveCount)
|
||||
query = "SELECT alb.*, COUNT(*) AS SongCount FROM Album alb " +
|
||||
"LEFT JOIN Song sng ON alb.AlbumId=sng.AlbumId WHERE " +
|
||||
"alb.Title=@Title GROUP BY alb.AlbumId LIMIT 1";
|
||||
else
|
||||
query = "SELECT alb.*, 0 AS SongCount FROM Album alb WHERE " +
|
||||
"alb.Title=@Title LIMIT 1";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Title", song.AlbumTitle);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
album = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return album;
|
||||
}
|
||||
|
||||
public bool DoesAlbumExist(Album album)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT alb.*, 0 AS SongCount FROM Album alb WHERE alb.AlbumId=@AlbumId";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@AlbumId", album.AlbumId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
album = ParseSingleData(reader);
|
||||
|
||||
if (album.Title != null)
|
||||
{
|
||||
_logger.Info($"Album {album.Title} exists");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
public bool DoesAlbumExist(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT alb.*, 0 AS SongCount FROM Album alb WHERE alb.Title=@Title";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Title", song.AlbumTitle);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
var album = ParseSingleData(reader);
|
||||
|
||||
if (!String.IsNullOrEmpty(album.Title))
|
||||
{
|
||||
_logger.Info($"Album {album.Title} exists");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public void SaveAlbum(Album album)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "INSERT INTO Album(Title, AlbumArtist)" +
|
||||
" VALUES (@Title, @AlbumArtist)";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Title", album.Title);
|
||||
cmd.Parameters.AddWithValue("@AlbumArtist", album.AlbumArtist);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void UpdateAlbum(Album album)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "UPDATE Album SET Title=@Title, AlbumArtist=" +
|
||||
"@AlbumArtist WHERE AlbumId=@AlbumId";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Title", album.Title);
|
||||
cmd.Parameters.AddWithValue("@AlbumArtist", album.AlbumArtist);
|
||||
cmd.Parameters.AddWithValue("@AlbumId", album.AlbumId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteAlbum(Album album)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "DELETE FROM Album WHERE AlbumId=@AlbumId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@AlbumId", album.AlbumId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Album> ParseData(MySqlDataReader reader)
|
||||
{
|
||||
List<Album> albums = new List<Album>();
|
||||
_logger.Info("Retrieving album records");
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["AlbumId"]);
|
||||
var title = reader["Title"].ToString();
|
||||
var albumArtist = reader["AlbumArtist"].ToString();
|
||||
var songCount = Convert.ToInt32(reader["SongCount"]);
|
||||
albums.Add(new Album
|
||||
{
|
||||
AlbumId = id,
|
||||
Title = title,
|
||||
AlbumArtist = albumArtist,
|
||||
SongCount = songCount
|
||||
});
|
||||
}
|
||||
|
||||
_logger.Info("Album records retrieved");
|
||||
|
||||
return albums;
|
||||
}
|
||||
private Album ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
Album album = new Album();
|
||||
_logger.Info("Retrieving single album record");
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["AlbumId"]);
|
||||
var title = reader["Title"].ToString();
|
||||
var albumArtist = reader["AlbumArtist"].ToString();
|
||||
var songCount = Convert.ToInt32(reader["SongCount"]);
|
||||
album = new Album
|
||||
{
|
||||
AlbumId = id,
|
||||
Title = title,
|
||||
AlbumArtist = albumArtist,
|
||||
SongCount = songCount
|
||||
};
|
||||
}
|
||||
_logger.Info("Single ablum retreived");
|
||||
|
||||
return album;
|
||||
}
|
||||
|
||||
private bool AnyAlbums()
|
||||
{
|
||||
var albums = new List<Album>();
|
||||
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT * FROM Album";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
albums = ParseData(reader);
|
||||
}
|
||||
|
||||
if (albums.Count > 0)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,355 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
using Microsoft.Extensions.Logging;
|
||||
using MySql.Data.MySqlClient;
|
||||
//using NLog;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class ArtistRepository : BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public ArtistRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public List<Artist> GetArtists()
|
||||
{
|
||||
List<Artist> artists = new List<Artist>();
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT art.*, COUNT(*) AS SongCount FROM Artist " +
|
||||
"art LEFT JOIN Song sng ON art.ArtistId=sng.ArtistId " +
|
||||
"GROUP BY art.ArtistId";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
artists = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return artists;
|
||||
}
|
||||
|
||||
public Artist GetArtist(Artist artist)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving artist record from the database");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT art.*, COUNT(*) AS SongCount FROM Artist " +
|
||||
"art LEFT JOIN Song sng ON art.ArtistId=sng.ArtistId " +
|
||||
"WHERE art.ArtistId=@ArtistId";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@ArtistId", artist.ArtistId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
artist = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return artist;
|
||||
}
|
||||
public Artist GetArtist(Song song)
|
||||
{
|
||||
Artist artist = new Artist();
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving artist record from the database");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT art.*, 0 AS SongCount FROM Artist " +
|
||||
"art WHERE art.Name=@Name";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Name", song.Artist);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
artist = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return artist;
|
||||
}
|
||||
public Artist GetArtist(Song song, bool retrieveCount)
|
||||
{
|
||||
var artist = new Artist();
|
||||
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving artist record from the database");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = string.Empty;
|
||||
|
||||
if (retrieveCount)
|
||||
query = "SELECT art.*, COUNT(*) AS SongCount FROM Artist " +
|
||||
"art LEFT JOIN Song sng ON art.ArtistId=sng.ArtistId " +
|
||||
"WHERE art.Name=@Name GROUP BY art.ArtistId LIMIT 1";
|
||||
else
|
||||
query = "SELECT art.*, 0 AS SongCount FROM Artist art " +
|
||||
"WHERE art.Name=@Name LIMIT 1";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Name", song.Artist);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
artist = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return artist;
|
||||
}
|
||||
|
||||
public bool DoesArtistExist(Artist artist)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Checking to see if Artist exists");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT art.*, 0 AS SongCount FROM Artist art WHERE art.ArtistId=@ArtistId";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@ArtistId", artist.ArtistId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
artist = ParseSingleData(reader);
|
||||
|
||||
if (artist.Name != null)
|
||||
{
|
||||
_logger.Info($"Artist {artist.Name} exists");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("Could not successfully retrieve Artist");
|
||||
|
||||
return false;
|
||||
}
|
||||
public bool DoesArtistExist(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Checking to see if Artist exists");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT art.*, 0 AS SongCount FROM Artist art WHERE art.Name=@Name";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Name", song.Artist);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
var artist = ParseSingleData(reader);
|
||||
|
||||
if (!String.IsNullOrEmpty(artist.Name))
|
||||
{
|
||||
_logger.Info($"Artist {artist.Name} exists");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("Could not successfully retrieve Artist");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public void SaveArtist(Artist artist)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Saving artist record");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "INSERT INTO Artist(Name) VALUES(@Name)";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Name", artist.Name);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Info("Artist record has successfully been saved");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void UpdateArtist(Artist artist)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Updating artist record");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "UPDATE Artist SET Name=@Name WHERE ArtistId=@ArtistId";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Name", artist.Name);
|
||||
cmd.Parameters.AddWithValue("@ArtistId", artist.ArtistId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Info("Artist record has successfully been saved");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteArtist(Artist artist)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Deleting artist record");
|
||||
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "DELETE FROM Artist WHERE ArtistId=@ArtistId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@ArtistId", artist.ArtistId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Artist> ParseData(MySqlDataReader reader)
|
||||
{
|
||||
List<Artist> artists = new List<Artist>();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["ArtistId"]);
|
||||
var name = reader["Name"].ToString();
|
||||
var songCount = Convert.ToInt32(reader["SongCount"].ToString());
|
||||
artists.Add(new Artist
|
||||
{
|
||||
ArtistId = id,
|
||||
Name = name,
|
||||
SongCount = songCount
|
||||
});
|
||||
}
|
||||
|
||||
_logger.Info("Artist records retrieved");
|
||||
|
||||
return artists;
|
||||
}
|
||||
|
||||
private Artist ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
Artist artist = new Artist();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["ArtistId"]);
|
||||
var name = reader["Name"].ToString();
|
||||
var songCount = Convert.ToInt32(reader["SongCount"].ToString());
|
||||
artist.ArtistId = id;
|
||||
artist.Name = name;
|
||||
artist.SongCount = songCount;
|
||||
}
|
||||
|
||||
_logger.Info("Single artist record retrieved");
|
||||
|
||||
return artist;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
using System;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
using NLog;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
protected string _connectionString;
|
||||
protected static Logger _logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
protected MySqlConnection GetConnection()
|
||||
{
|
||||
return new MySqlConnection(_connectionString);
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,255 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
using Icarus.Types;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class CoverArtRepository : BaseRepository
|
||||
{
|
||||
#region Constructors
|
||||
public CoverArtRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public CoverArt GetCoverArt(CoverArt cover)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
_logger.Info("Querying cover art record");
|
||||
|
||||
var query = "SELECT * FROM CoverArt WHERE " +
|
||||
"CoverArtId=@CoverArtId";
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters
|
||||
.AddWithValue("@CoverArtId", cover.CoverArtId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
return ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
public CoverArt GetCoverArt(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
_logger.Info("Querying cover art record");
|
||||
|
||||
var query = "SELECT cov.* FROM CoverArt cov LEFT JOIN " +
|
||||
"Song sng ON cov.CoverArtId=sng.CoverArtId WHERE " +
|
||||
"sng.Id=@SongId";
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@SongId", song.Id);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
return ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
public CoverArt GetCoverArt(CoverArtField field, CoverArt cover)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
_logger.Info("Querying cover art record");
|
||||
|
||||
using (var cmd = new MySqlCommand(BuildQuery(field), conn))
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case CoverArtField.SongTitle:
|
||||
cmd.Parameters.AddWithValue("@SongTitle",
|
||||
cover.SongTitle);
|
||||
break;
|
||||
case CoverArtField.ImagePath:
|
||||
cmd.Parameters.AddWithValue("@ImagePath",
|
||||
cover.ImagePath);
|
||||
break;
|
||||
}
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
return ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool DoesCoverArtExist(CoverArt cover)
|
||||
{
|
||||
return GetCoverArt(cover) != null ? true : false;
|
||||
}
|
||||
public bool DoesCoverArtExist(Song song)
|
||||
{
|
||||
return GetCoverArt(song) != null ? true : false;
|
||||
}
|
||||
|
||||
public void SaveCoverArt(CoverArt coverArt)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
_logger.Info("Saving cover art record");
|
||||
|
||||
var query = "INSERT INTO CoverArt(SongTitle, ImagePath) " +
|
||||
"VALUES(@SongTitle, @ImagePath)";
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters
|
||||
.AddWithValue("@SongTitle", coverArt.SongTitle);
|
||||
cmd.Parameters
|
||||
.AddWithValue("@ImagePath", coverArt.ImagePath);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteCoverArt(CoverArt cover)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
_logger.Info("Deleting cover art record");
|
||||
|
||||
var query = "DELETE FROM CoverArt WHERE " +
|
||||
"CoverArtId=@CoverArtId";
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters
|
||||
.AddWithValue("@CoverArtId", cover.CoverArtId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
private List<CoverArt> ParseData(MySqlDataReader reader)
|
||||
{
|
||||
if (reader.HasRows)
|
||||
{
|
||||
var coverArtList = new List<CoverArt>();
|
||||
_logger.Info("Parsing cover art records");
|
||||
while (reader.Read())
|
||||
coverArtList.Add(new CoverArt
|
||||
{
|
||||
CoverArtId = Convert.ToInt32(reader["CoverArtId"]),
|
||||
SongTitle = reader["SongTitle"].ToString(),
|
||||
ImagePath = reader["ImagePath"].ToString()
|
||||
});
|
||||
|
||||
return coverArtList;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private CoverArt ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
if (reader.HasRows)
|
||||
{
|
||||
_logger.Info("Parsing single cover art record");
|
||||
reader.Read();
|
||||
|
||||
return new CoverArt
|
||||
{
|
||||
CoverArtId = Convert.ToInt32(reader["CoverArtId"]),
|
||||
SongTitle = reader["SongTitle"].ToString(),
|
||||
ImagePath = reader["ImagePath"].ToString()
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private string BuildQuery(CoverArtField field)
|
||||
{
|
||||
switch (field)
|
||||
{
|
||||
case CoverArtField.SongTitle:
|
||||
return "SELECT * FROM CoverArt WHERE SongTitle=@SongTitle";
|
||||
case CoverArtField.ImagePath:
|
||||
return "SELECT * FROM CoverArt WHERE ImagePath=" +
|
||||
"@ImagePath";
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private bool? AnyCoverArt()
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
_logger.Info("Checking to see if there are any cover art " +
|
||||
"records");
|
||||
|
||||
var query = "SELECT * FROM CoverArt";
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
return reader.HasRows;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,447 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class GenreRepository : BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public GenreRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public List<Genre> GetGenresWithoutCount()
|
||||
{
|
||||
_logger.Info("Retrieving all genre records without song counts");
|
||||
|
||||
var genres = new List<Genre>();
|
||||
|
||||
if (AnyGenre())
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT * FROM Genre";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
genres = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
return genres;
|
||||
}
|
||||
public List<Genre> GetGenres()
|
||||
{
|
||||
_logger.Info("Retrieving Genre records");
|
||||
|
||||
var genres = new List<Genre>();
|
||||
|
||||
if (AnyGenre())
|
||||
{
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT gnr.*, COUNT(*) AS SongCount FROM Genre " +
|
||||
"gnr LEFT JOIN Song sng ON gnr.GenreId=sng.GenreId " +
|
||||
"GROUP BY gnr.GenreId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
genres = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
return genres;
|
||||
}
|
||||
|
||||
public Genre GetGenre(Genre genre)
|
||||
{
|
||||
_logger.Info("Retrieving Genre record");
|
||||
|
||||
if (DoesGenreExist(genre))
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT gnr.*, COUNT(*) AS SongCount FROM Genre " +
|
||||
"gnr LEFT JOIN Song sng ON gnr.GenreId=sng.GenreId " +
|
||||
"WHERE gnr.GenreId=@GenreId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreId", genre.GenreId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
genre = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
return genre;
|
||||
}
|
||||
public Genre GetGenre(Song song)
|
||||
{
|
||||
_logger.Info("Retrieving Genre record");
|
||||
|
||||
var genre = new Genre();
|
||||
|
||||
if (DoesGenreExist(song))
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT gnr.*, 0 AS SongCount FROM Genre " +
|
||||
"gnr WHERE gnr.GenreName=@GenreName";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreName", song.Genre);
|
||||
_logger.Info($"Song genre:\n\n\n {song.Genre}");
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
genre = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
return genre;
|
||||
}
|
||||
public Genre GetGenre(Song song, bool retrieveCount)
|
||||
{
|
||||
_logger.Info("Retrieving Genre record");
|
||||
|
||||
var genre = new Genre();
|
||||
|
||||
if (DoesGenreExist(song))
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = string.Empty;
|
||||
|
||||
if (retrieveCount)
|
||||
query = "SELECT gnr.*, COUNT(*) AS SongCount FROM Genre gnr " +
|
||||
"LEFT JOIN Song sng ON gnr.GenreId=sng.GenreId " +
|
||||
"WHERE gnr.GenreName=@GenreName GROUP BY gnr.GenreId " +
|
||||
"LIMIT 1";
|
||||
else
|
||||
query = "SELECT gnr.*, 0 AS SongCount FROM Genre gnr " +
|
||||
"WHERE gnr.GenreName=@GenreName LIMIT 1";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreName", song.Genre);
|
||||
_logger.Info($"Song genre:\n\n\n {song.Genre}");
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
genre = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
return genre;
|
||||
}
|
||||
|
||||
public bool DoesGenreExist(Genre genre)
|
||||
{
|
||||
_logger.Info("Checking to see if Genre record exists");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT gnr.*, 0 AS SongCount FROM Genre gnr WHERE " +
|
||||
"gnr.GenreId=@GenreId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreId", genre.GenreId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
genre = ParseSingleData(reader);
|
||||
var genreName = genre.GenreName;
|
||||
|
||||
if (!string.IsNullOrEmpty(genreName))
|
||||
{
|
||||
_logger.Info("Genre exists");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("Genre does not exist");
|
||||
|
||||
return false;
|
||||
}
|
||||
public bool DoesGenreExist(Song song)
|
||||
{
|
||||
_logger.Info("Checking to see if Genre record exists");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT gnr.*, 0 AS SongCount FROM Genre gnr WHERE " +
|
||||
"gnr.GenreName=@GenreName";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreName", song.Genre);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
var genre = ParseSingleData(reader);
|
||||
var genreName = genre.GenreName;
|
||||
|
||||
if (!string.IsNullOrEmpty(genreName))
|
||||
{
|
||||
_logger.Info("Genre exists");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("Genre does not exist");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void SaveGenre(Genre genre)
|
||||
{
|
||||
_logger.Info("Saving Genre record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "INSERT INTO Genre(GenreName) VALUES(@GenreName)";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreName", genre.GenreName);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void UpdateGenre(Genre genre)
|
||||
{
|
||||
_logger.Info("Updating Genre record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "UPDATE Genre SET GenreName=@GenreName " +
|
||||
"WHERE GenreId=@GenreId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreName", genre.GenreName);
|
||||
cmd.Parameters.AddWithValue("@GenreId", genre.GenreId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteGenre(Genre genre)
|
||||
{
|
||||
_logger.Info("Deleting Genre record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "DELETE FROM Genre WHERE GenreId=@GenreId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@GenreId", genre.GenreId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Genre> ParseData(MySqlDataReader reader)
|
||||
{
|
||||
var genres = new List<Genre>();
|
||||
_logger.Info("Retrieving genre records");
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["GenreId"].ToString());
|
||||
var genreName = reader["GenreName"].ToString();
|
||||
var songCount = Convert.ToInt32(reader["SongCount"].ToString());
|
||||
|
||||
genres.Add(new Genre
|
||||
{
|
||||
GenreId = id,
|
||||
GenreName = genreName,
|
||||
SongCount = songCount
|
||||
});
|
||||
}
|
||||
|
||||
_logger.Info("Genre records retrieved");
|
||||
|
||||
return genres;
|
||||
}
|
||||
|
||||
private Genre ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
var genre = new Genre();
|
||||
_logger.Info("Retrieving single genre record");
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["GenreId"].ToString());
|
||||
var genreName = reader["GenreName"].ToString();
|
||||
var songCount = Convert.ToInt32(reader["SongCount"].ToString());
|
||||
genre.GenreId = id;
|
||||
genre.GenreName = genreName;
|
||||
genre.SongCount = songCount;
|
||||
}
|
||||
|
||||
_logger.Info("Single genre record retrieved");
|
||||
|
||||
return genre;
|
||||
}
|
||||
|
||||
private bool AnyGenre()
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT * FROM Genre";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
return reader.HasRows;
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("No genre records found");
|
||||
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,324 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class SongRepository : BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public SongRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public void SaveSong(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Saving song to the database");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
string query = "INSERT INTO Song(Title, AlbumTitle, Artist," +
|
||||
" Year, Genre, Duration, Filename, SongPath, AlbumId, " +
|
||||
"ArtistId, GenreId, YearId, CoverArtId) VALUES(@Title," +
|
||||
" @AlbumTitle, @Artist, @Year, @Genre, @Duration, " +
|
||||
"@Filename, @SongPath, @AlbumId, @ArtistId, @GenreId," +
|
||||
" @YearId, @CoverArtId)";
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Title", song.Title);
|
||||
cmd.Parameters.AddWithValue("@AlbumTitle", song.AlbumTitle);
|
||||
cmd.Parameters.AddWithValue("@Artist", song.Artist);
|
||||
cmd.Parameters.AddWithValue("@Year", song.Year);
|
||||
cmd.Parameters.AddWithValue("@Genre", song.Genre);
|
||||
cmd.Parameters.AddWithValue("@Duration", song.Duration);
|
||||
cmd.Parameters.AddWithValue("@Filename", song.Filename);
|
||||
cmd.Parameters.AddWithValue("@SongPath", song.SongPath);
|
||||
cmd.Parameters.AddWithValue("@AlbumId", song.AlbumId);
|
||||
cmd.Parameters.AddWithValue("@ArtistId", song.ArtistId);
|
||||
cmd.Parameters.AddWithValue("@GenreId", song.GenreId);
|
||||
cmd.Parameters.AddWithValue("@YearId", song.YearId);
|
||||
cmd.Parameters.AddWithValue("@CoverArtId", song.CoverArtId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
_logger.Info("Successfully saved song to the database");
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
var exMsg = ex.Message;
|
||||
Console.WriteLine($"An error occurred:\n{exMsg}");
|
||||
_logger.Error(exMsg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void UpdateSong(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
string query = "UPDATE Song SET Title=@Title, AlbumTitle=@AlbumTitle, " +
|
||||
"Artist=@Artist, Year=@Year, Genre=@Genre, Duration=@Duration, " +
|
||||
"Filename=@Filename, SongPath=@SongPath, AlbumId=@AlbumId, " +
|
||||
"ArtistId=@ArtistId, GenreId=@GenreId, YearId=@YearId WHERE Id=@Id";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Title", song.Title);
|
||||
cmd.Parameters.AddWithValue("@AlbumTitle", song.AlbumTitle);
|
||||
cmd.Parameters.AddWithValue("@Artist", song.Artist);
|
||||
cmd.Parameters.AddWithValue("@Year", song.Year);
|
||||
cmd.Parameters.AddWithValue("@Genre", song.Genre);
|
||||
cmd.Parameters.AddWithValue("@Duration", song.Duration);
|
||||
cmd.Parameters.AddWithValue("@Filename", song.Filename);
|
||||
cmd.Parameters.AddWithValue("@SongPath", song.SongPath);
|
||||
cmd.Parameters.AddWithValue("@Id", song.Id);
|
||||
cmd.Parameters.AddWithValue("@AlbumId", song.AlbumId);
|
||||
cmd.Parameters.AddWithValue("@ArtistId", song.ArtistId);
|
||||
cmd.Parameters.AddWithValue("@GenreId", song.GenreId);
|
||||
cmd.Parameters.AddWithValue("@YearId", song.YearId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
_logger.Info("Updated song");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
Console.WriteLine("An error occurred in SongRepository:");
|
||||
Console.WriteLine(msg);
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteSong(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Deleting song record");
|
||||
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "Delete FROM Song WHERE Id=@Id";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Id", song.Id);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteSong(int id)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Deleting song record");
|
||||
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
string query = "DELETE FROM Song WHERE Id=@Id";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Id", id);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var exMsg = ex.Message;
|
||||
Console.WriteLine($"An error occurred:\n{exMsg}");
|
||||
_logger.Error(exMsg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
public List<Song> GetAllSongs()
|
||||
{
|
||||
List<Song> songs = new List<Song>();
|
||||
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving songs from the database");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT * FROM Song";
|
||||
Console.WriteLine("ffff");
|
||||
MySqlCommand cmd = new MySqlCommand(query, conn);
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
songs = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var exMsg = ex.Message;
|
||||
Console.WriteLine($"An error ocurred:\n{exMsg}");
|
||||
songs.Clear();
|
||||
_logger.Error(exMsg, "An error occurred");
|
||||
}
|
||||
|
||||
return songs;
|
||||
}
|
||||
|
||||
public Song GetSong(Song song)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving song from database");
|
||||
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT * FROM Song WHERE Id=@Id";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Id", song.Id);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
song = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return song;
|
||||
}
|
||||
public Song GetSong(int id)
|
||||
{
|
||||
Song song = new Song();
|
||||
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving song from database");
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT * FROM Song WHERE Id=@Id";
|
||||
|
||||
MySqlCommand cmd = new MySqlCommand(query, conn);
|
||||
cmd.Parameters.AddWithValue("@Id", id);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
song = ParseSingleData(reader);
|
||||
}
|
||||
_logger.Info("Song found");
|
||||
}
|
||||
catch(Exception ex)
|
||||
{
|
||||
var exMsg = ex.Message;
|
||||
Console.WriteLine($"An error ocurred: {exMsg}");
|
||||
_logger.Error(exMsg, "An error occurred");
|
||||
}
|
||||
|
||||
return song;
|
||||
}
|
||||
|
||||
public bool DoesSongExist(Song song)
|
||||
{
|
||||
_logger.Info("Checking to see if the song exists");
|
||||
var songInDatabase = GetSong(song);
|
||||
var title = songInDatabase.Title;
|
||||
|
||||
if (!string.IsNullOrEmpty(title))
|
||||
{
|
||||
_logger.Info("Song exists");
|
||||
return true;
|
||||
}
|
||||
|
||||
_logger.Info("Song does not exists");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private List<Song> ParseData(MySqlDataReader reader)
|
||||
{
|
||||
|
||||
List<Song> songs = new List<Song>();
|
||||
while (reader.Read())
|
||||
{
|
||||
songs.Add(new Song
|
||||
{
|
||||
Id = Convert.ToInt32(reader["Id"]),
|
||||
Title = reader["Title"].ToString(),
|
||||
AlbumTitle = reader["AlbumTitle"].ToString(),
|
||||
Artist = reader["Artist"].ToString(),
|
||||
Year = Convert.ToInt32(reader["Year"]),
|
||||
Genre = reader["Genre"].ToString(),
|
||||
Duration = Convert.ToInt32(reader["Duration"]),
|
||||
Filename = reader["Filename"].ToString(),
|
||||
SongPath = reader["SongPath"].ToString(),
|
||||
AlbumId = Convert.ToInt32(reader["AlbumId"].ToString()),
|
||||
ArtistId = Convert.ToInt32(reader["ArtistId"].ToString()),
|
||||
GenreId = Convert.ToInt32(reader["GenreId"].ToString()),
|
||||
YearId = Convert.ToInt32(reader["YearId"].ToString()),
|
||||
CoverArtId = Convert.ToInt32(reader["CoverArtId"].ToString())
|
||||
});
|
||||
}
|
||||
|
||||
return songs;
|
||||
}
|
||||
|
||||
private Song ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
Song song = new Song();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
song.Id = Convert.ToInt32(reader["Id"]);
|
||||
song.Title = reader["Title"].ToString();
|
||||
song.AlbumTitle = reader["AlbumTitle"].ToString();
|
||||
song.Artist = reader["Artist"].ToString();
|
||||
song.Year = Convert.ToInt32(reader["Year"].ToString());
|
||||
song.Genre = reader["Genre"].ToString();
|
||||
song.Duration = Convert.ToInt32(reader["Duration"]);
|
||||
song.Filename = reader["Filename"].ToString();
|
||||
song.SongPath = reader["SongPath"].ToString();
|
||||
song.AlbumId = Convert.ToInt32(reader["AlbumId"].ToString());
|
||||
song.ArtistId = Convert.ToInt32(reader["ArtistId"].ToString());
|
||||
song.GenreId = Convert.ToInt32(reader["GenreId"].ToString());
|
||||
song.YearId = Convert.ToInt32(reader["YearId"].ToString());
|
||||
song.CoverArtId = Convert.ToInt32(reader["CoverArtId"].ToString());
|
||||
}
|
||||
|
||||
return song;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,229 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class UserRepository: BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructor
|
||||
public UserRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public void SaveUser(User user)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Saving user");
|
||||
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
string query = "INSERT INTO User(Username, Password, Nickname, Email" +
|
||||
", PhoneNumber, Firstname, Lastname, EmailVerified) " +
|
||||
"VALUES(@Username, @Password, @Nickname, @Email, @PhoneNumber," +
|
||||
" @Firstname, @Lastname, @EmailVerified)";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Username", user.Username);
|
||||
cmd.Parameters.AddWithValue("@Password", user.Password);
|
||||
cmd.Parameters.AddWithValue("@Nickname", user.Nickname);
|
||||
cmd.Parameters.AddWithValue("@Email", user.Email);
|
||||
cmd.Parameters.AddWithValue("@PhoneNumber", user.PhoneNumber);
|
||||
cmd.Parameters.AddWithValue("@Firstname", user.Firstname);
|
||||
cmd.Parameters.AddWithValue("@Lastname", user.Lastname);
|
||||
cmd.Parameters.AddWithValue("@EmailVerified", user.EmailVerified);
|
||||
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Info("Successfully saved user");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var exMsg = ex.Message;
|
||||
Console.WriteLine($"An error occurred:\n{exMsg}");
|
||||
_logger.Error(exMsg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
public User RetrieveUser(User user)
|
||||
{
|
||||
try
|
||||
{
|
||||
_logger.Info("Retrieving user");
|
||||
|
||||
using (MySqlConnection conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT * FROM User WHERE Username=@Username";
|
||||
|
||||
using (MySqlCommand cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Username", user.Username);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
user = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
|
||||
_logger.Info("Successfully retrieved user");
|
||||
|
||||
return user;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var exMsg = ex.Message;
|
||||
Console.WriteLine($"An error occurred:\n{exMsg}");
|
||||
_logger.Error(exMsg, "An error occurred");
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public bool DoesUserExist(User user)
|
||||
{
|
||||
var username = user.Username;
|
||||
try
|
||||
{
|
||||
_logger.Info($"Checking to see if {user.Username} exists");
|
||||
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
var query = "SELECT * FROM User WHERE Username=@Username";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@Username", user.Username);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
user = ParseSingleData(reader, true);
|
||||
username = user.Username;
|
||||
|
||||
if (!string.IsNullOrEmpty(username))
|
||||
{
|
||||
_logger.Info($"The user {username} exists");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info($"The user {username} does not exists");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private User ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
var user = new User();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["Id"].ToString());
|
||||
var username = reader["Username"].ToString();
|
||||
var password = reader["Password"].ToString();
|
||||
var nickname = reader["Nickname"].ToString();
|
||||
var email = reader["Email"].ToString();
|
||||
var phoneNumber = reader["PhoneNumber"].ToString();
|
||||
var emailVerified = reader["EmailVerified"].ToString() == "1";
|
||||
var firstname = reader["Firstname"].ToString();
|
||||
var lastname = reader["Lastname"].ToString();
|
||||
var rawLastLogin = reader["LastLogin"].ToString();
|
||||
|
||||
var parsedDateCreated = DateTime.Parse(reader["DateCreated"].ToString());
|
||||
|
||||
var dateCreated = DateTime.Parse(parsedDateCreated.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
if (!string.IsNullOrEmpty(rawLastLogin))
|
||||
{
|
||||
var parsedLastLogin = DateTime.Parse(rawLastLogin);
|
||||
var lastLogin = DateTime.Parse(parsedLastLogin.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
user.LastLogin = lastLogin;
|
||||
}
|
||||
|
||||
user.Id = id;
|
||||
user.Username = username;
|
||||
user.Password = password;
|
||||
user.Nickname = nickname;
|
||||
user.Email = email;
|
||||
user.PhoneNumber = phoneNumber;
|
||||
user.EmailVerified = emailVerified;
|
||||
user.Firstname = firstname;
|
||||
user.Lastname = lastname;
|
||||
user.DateCreated = dateCreated;
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
private User ParseSingleData(MySqlDataReader reader, bool ignoreLastLogin)
|
||||
{
|
||||
var user = new User();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["Id"].ToString());
|
||||
var username = reader["Username"].ToString();
|
||||
var nickname = reader["Nickname"].ToString();
|
||||
var email = reader["Email"].ToString();
|
||||
var phoneNumber = reader["PhoneNumber"].ToString();
|
||||
var emailVerified = reader["EmailVerified"].ToString() == "1";
|
||||
var firstname = reader["Firstname"].ToString();
|
||||
var lastname = reader["Lastname"].ToString();
|
||||
|
||||
var parsedDateCreated = DateTime.Parse(reader["DateCreated"].ToString());
|
||||
|
||||
var dateCreated = DateTime.Parse(parsedDateCreated.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
|
||||
if (!ignoreLastLogin)
|
||||
{
|
||||
var parsedLastLogin = DateTime.Parse(reader["LastLogin"].ToString());
|
||||
var lastLogin = DateTime.Parse(parsedLastLogin.ToString("yyyy-MM-dd HH:mm:ss"));
|
||||
user.LastLogin = lastLogin;
|
||||
}
|
||||
|
||||
user.Id = id;
|
||||
user.Username = username;
|
||||
user.Nickname = nickname;
|
||||
user.Email = email;
|
||||
user.PhoneNumber = phoneNumber;
|
||||
user.EmailVerified = emailVerified;
|
||||
user.Firstname = firstname;
|
||||
user.Lastname = lastname;
|
||||
user.DateCreated = dateCreated;
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -1,367 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
|
||||
using MySql.Data.MySqlClient;
|
||||
|
||||
using Icarus.Models;
|
||||
|
||||
namespace Icarus.Database.Repositories
|
||||
{
|
||||
public class YearRepository : BaseRepository
|
||||
{
|
||||
#region Fields
|
||||
#endregion
|
||||
|
||||
|
||||
#region Properties
|
||||
#endregion
|
||||
|
||||
|
||||
#region Constructors
|
||||
public YearRepository(string connectionString)
|
||||
{
|
||||
_connectionString = connectionString;
|
||||
}
|
||||
#endregion
|
||||
|
||||
|
||||
#region Methods
|
||||
public List<Year> GetSongYears()
|
||||
{
|
||||
_logger.Info("Retrieving Year records");
|
||||
|
||||
var yearValues = new List<Year>();
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT yr.*, COUNT(*) AS SongCount FROM Year " +
|
||||
"yr LEFT JOIN Song sng ON yr.YearId=sng.YearId " +
|
||||
"GROUP BY yr.YearId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
yearValues = ParseData(reader);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return yearValues;
|
||||
}
|
||||
|
||||
public Year GetSongYear(Year year)
|
||||
{
|
||||
_logger.Info("Retrieving Year record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT yr.*, COUNT(*) AS SongCount FROM Year " +
|
||||
"yr LEFT JOIN Song sng ON yr.YearId=sng.YearId WHERE " +
|
||||
"YearId=@YearId GROUP BY yr.YearId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearId", year.YearId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
year = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return year;
|
||||
}
|
||||
public Year GetSongYear(Song song)
|
||||
{
|
||||
var year = new Year();
|
||||
|
||||
_logger.Info("Retrieving Year record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT yr.*, 0 AS SongCount FROM Year " +
|
||||
"yr WHERE yr.YearValue=@YearValue";
|
||||
|
||||
using(var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearValue", song.Year);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
year = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return year;
|
||||
}
|
||||
public Year GetSongYear(Song song, bool retrieveCount)
|
||||
{
|
||||
var year = new Year();
|
||||
|
||||
_logger.Info("Retrieving year record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = string.Empty;
|
||||
|
||||
if (retrieveCount)
|
||||
query = "SELECT yr.*, COUNT(*) AS SongCount FROM Year yr " +
|
||||
"LEFT JOIN Song sng ON yr.YearValue=sng.Year WHERE " +
|
||||
"yr.YearValue=@YearValue GROUP BY yr.YearId LIMIT 1";
|
||||
else
|
||||
query = "SELECT yr.*, 0 AS SongCount FROM Year yr " +
|
||||
"WHERE yr.YearValue=@YearValue LIMIT 1";
|
||||
|
||||
using(var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearValue", song.Year);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
year = ParseSingleData(reader);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
return year;
|
||||
}
|
||||
|
||||
public bool DoesYearExist(Year year)
|
||||
{
|
||||
_logger.Info("Checking to see if Year record exists");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT yr.*, 0 AS SongCount FROM Year yr WHERE " +
|
||||
"yr.YearId=@YearId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearId", year.YearId);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
year = ParseSingleData(reader);
|
||||
|
||||
if (year.YearValue > 0)
|
||||
{
|
||||
_logger.Info("Year record exists");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("Year record does not exist");
|
||||
|
||||
return false;
|
||||
}
|
||||
public bool DoesYearExist(Song song)
|
||||
{
|
||||
_logger.Info("Checking to see if Year record exists");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "SELECT yr.*, 0 AS SongCount FROM Year yr WHERE " +
|
||||
"yr.YearValue=@YearValue";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearValue", song.Year);
|
||||
|
||||
using (var reader = cmd.ExecuteReader())
|
||||
{
|
||||
var year = ParseSingleData(reader);
|
||||
|
||||
if (year.YearValue > 0)
|
||||
{
|
||||
_logger.Info("Year record exists");
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
|
||||
_logger.Info("Year record does not exist");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void SaveYear(Year year)
|
||||
{
|
||||
_logger.Info("Saving Year record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "INSERT INTO Year(YearValue) VALUES(@YearValue)";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearValue", year.YearValue);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void UpdateYear(Year year)
|
||||
{
|
||||
_logger.Info("Deleting Year record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "UPDATE Year SET YearValue=@YearValue WHERE YearId=@YearId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearId", year.YearId);
|
||||
cmd.Parameters.AddWithValue("@YearValue", year.YearValue);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
public void DeleteYear(Year year)
|
||||
{
|
||||
_logger.Info("Deleting Year record");
|
||||
|
||||
try
|
||||
{
|
||||
using (var conn = GetConnection())
|
||||
{
|
||||
conn.Open();
|
||||
|
||||
var query = "DELETE FROM Year WHERE YearId=@YearId";
|
||||
|
||||
using (var cmd = new MySqlCommand(query, conn))
|
||||
{
|
||||
cmd.Parameters.AddWithValue("@YearId", year.YearId);
|
||||
|
||||
cmd.ExecuteNonQuery();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
var msg = ex.Message;
|
||||
_logger.Error(msg, "An error occurred");
|
||||
}
|
||||
}
|
||||
|
||||
private List<Year> ParseData(MySqlDataReader reader)
|
||||
{
|
||||
var yearValues = new List<Year>();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["YearId"].ToString());
|
||||
var year = Convert.ToInt32(reader["YearValue"].ToString());
|
||||
var songCount = Convert.ToInt32(reader["SongCount"].ToString());
|
||||
|
||||
yearValues.Add(new Year
|
||||
{
|
||||
YearId = id,
|
||||
YearValue = year,
|
||||
SongCount = songCount
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
return yearValues;
|
||||
}
|
||||
|
||||
private Year ParseSingleData(MySqlDataReader reader)
|
||||
{
|
||||
var yearValue = new Year();
|
||||
|
||||
while (reader.Read())
|
||||
{
|
||||
var id = Convert.ToInt32(reader["YearId"].ToString());
|
||||
var year = Convert.ToInt32(reader["YearValue"].ToString());
|
||||
var songCount = Convert.ToInt32(reader["SongCount"].ToString());
|
||||
|
||||
yearValue.YearId = id;
|
||||
yearValue.YearValue = year;
|
||||
yearValue.SongCount = songCount;
|
||||
}
|
||||
|
||||
return yearValue;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
# Stage 1: Build the application
|
||||
FROM rust:1.88 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 ubuntu:24.04
|
||||
|
||||
# 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 3000
|
||||
|
||||
# Set the command to run your application
|
||||
# Ensure this matches the binary name copied above
|
||||
CMD ["./icarus"]
|
||||
@@ -1,36 +0,0 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>netcoreapp2.2</TargetFramework>
|
||||
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="3.1.3" />
|
||||
<PackageReference Include="DotNetZip" Version="1.13.3" />
|
||||
<PackageReference Include="EntityFramework" Version="6.2.0" />
|
||||
<PackageReference Include="ID3" Version="0.6.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.App" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.2.3">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="mysql.data" Version="8.0.15" />
|
||||
<PackageReference Include="MySql.Data.Entity" Version="7.0.7-m61" />
|
||||
<PackageReference Include="MySql.Data.EntityFrameworkCore" Version="8.0.15" />
|
||||
<PackageReference Include="MySql.Data.EntityFrameworkCore.Design" Version="8.0.15" />
|
||||
<PackageReference Include="Newtonsoft.Json" Version="12.0.1" />
|
||||
<PackageReference Include="NLog.Web.AspNetCore" Version="4.8.1" />
|
||||
<PackageReference Include="RestSharp" Version="106.6.9" />
|
||||
<PackageReference Include="SevenZip" Version="19.0.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="5.4.0" />
|
||||
<PackageReference Include="taglib" Version="2.1.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Update="nlog.config" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="Images/Stock/*.*" CopyToOutputDirectory="PreserveNewest" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,9 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
|
||||
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ActiveDebugProfile>Icarus</ActiveDebugProfile>
|
||||
</PropertyGroup>
|
||||
</Project>
|
||||
@@ -1,34 +0,0 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 15
|
||||
VisualStudioVersion = 15.0.26124.0
|
||||
MinimumVisualStudioVersion = 15.0.26124.0
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Icarus", "Icarus.csproj", "{3BEBAB33-17BF-4183-9664-3D537A684138}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Debug|x64 = Debug|x64
|
||||
Debug|x86 = Debug|x86
|
||||
Release|Any CPU = Release|Any CPU
|
||||
Release|x64 = Release|x64
|
||||
Release|x86 = Release|x86
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Debug|x86.ActiveCfg = Debug|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Debug|x86.Build.0 = Debug|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Release|x64.ActiveCfg = Release|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Release|x64.Build.0 = Release|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Release|x86.ActiveCfg = Release|Any CPU
|
||||
{3BEBAB33-17BF-4183-9664-3D537A684138}.Release|x86.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
@@ -1,313 +0,0 @@
|
||||
2019-05-23 20:25:46.2420 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:25:46.2666 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:25:46.3926 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:25:46.4144 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:25:46.4351 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:25:46.4703 Info Found 45 configuration items
|
||||
2019-05-23 20:26:13.6466 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:26:13.6651 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:26:13.8165 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:26:13.8351 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:26:13.8552 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:26:13.8939 Info Found 45 configuration items
|
||||
2019-05-23 20:33:39.8295 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:33:39.8438 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:33:39.9198 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:33:39.9238 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:33:39.9238 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:33:39.9871 Info Found 45 configuration items
|
||||
2019-05-23 20:33:40.2458 Info Configuration initialized.
|
||||
2019-05-23 20:33:40.2602 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:33:42.2086 Info Shutting down logging...
|
||||
2019-05-23 20:33:42.2458 Info Logger has been shut down.
|
||||
2019-05-23 20:34:06.6746 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:34:06.6896 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:34:06.7827 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:34:06.7827 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:34:06.8010 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:34:06.8321 Info Found 45 configuration items
|
||||
2019-05-23 20:34:06.8673 Info Configuration initialized.
|
||||
2019-05-23 20:34:06.8673 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:34:07.7083 Info Shutting down logging...
|
||||
2019-05-23 20:34:07.7346 Info Logger has been shut down.
|
||||
2019-05-23 20:35:03.8649 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:35:03.8783 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:35:03.9596 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:35:03.9596 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:35:03.9745 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:35:03.9958 Info Found 45 configuration items
|
||||
2019-05-23 20:35:04.0200 Info Configuration initialized.
|
||||
2019-05-23 20:35:04.0200 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:35:04.5747 Info Shutting down logging...
|
||||
2019-05-23 20:35:04.6042 Info Logger has been shut down.
|
||||
2019-05-23 20:35:41.2884 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:35:41.3011 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:35:41.3629 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:35:41.3629 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:35:41.3755 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:35:41.3973 Info Found 45 configuration items
|
||||
2019-05-23 20:35:41.4257 Info Configuration initialized.
|
||||
2019-05-23 20:35:41.4257 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:35:42.0181 Info Shutting down logging...
|
||||
2019-05-23 20:35:42.0437 Info Logger has been shut down.
|
||||
2019-05-23 20:36:03.3664 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:36:03.3803 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:36:03.4469 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:36:03.4469 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:36:03.4634 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:36:03.4897 Info Found 45 configuration items
|
||||
2019-05-23 20:36:03.5214 Info Configuration initialized.
|
||||
2019-05-23 20:36:03.5214 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:36:04.0862 Info Shutting down logging...
|
||||
2019-05-23 20:36:04.1162 Info Logger has been shut down.
|
||||
2019-05-23 20:37:13.4449 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:37:13.4578 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:37:13.5222 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:37:13.5222 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:37:13.5349 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:37:13.5575 Info Found 45 configuration items
|
||||
2019-05-23 20:37:13.5870 Info Configuration initialized.
|
||||
2019-05-23 20:37:13.5870 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:37:14.1141 Info Shutting down logging...
|
||||
2019-05-23 20:37:14.1395 Info Logger has been shut down.
|
||||
2019-05-23 20:37:38.9373 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:37:38.9373 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:37:39.0239 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:37:39.0239 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:37:39.0371 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:37:39.0624 Info Found 45 configuration items
|
||||
2019-05-23 20:37:39.0916 Info Configuration initialized.
|
||||
2019-05-23 20:37:39.0984 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:37:39.2254 Info Shutting down logging...
|
||||
2019-05-23 20:37:39.2461 Info Logger has been shut down.
|
||||
2019-05-23 20:38:15.2217 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:38:15.2426 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:38:15.3307 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:38:15.3307 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:38:15.3434 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:38:15.3733 Info Found 45 configuration items
|
||||
2019-05-23 20:38:15.4046 Info Configuration initialized.
|
||||
2019-05-23 20:38:15.4103 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:38:16.3887 Info Shutting down logging...
|
||||
2019-05-23 20:38:16.4170 Info Logger has been shut down.
|
||||
2019-05-23 20:38:56.3096 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:38:56.3228 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:38:56.3991 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:38:56.3991 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:38:56.4137 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:38:56.4412 Info Found 45 configuration items
|
||||
2019-05-23 20:38:56.4662 Info Configuration initialized.
|
||||
2019-05-23 20:38:56.4711 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:38:57.5659 Info Shutting down logging...
|
||||
2019-05-23 20:38:57.5921 Info Logger has been shut down.
|
||||
2019-05-23 20:39:33.6137 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:39:33.6328 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:39:33.7158 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:39:33.7209 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:39:33.7349 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\NLog.config...
|
||||
2019-05-23 20:39:33.7661 Info Found 45 configuration items
|
||||
2019-05-23 20:39:33.7984 Info Configuration initialized.
|
||||
2019-05-23 20:39:33.7984 Info NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.5.11.8645. Product version: 4.5.11.
|
||||
2019-05-23 20:39:35.3535 Info Shutting down logging...
|
||||
2019-05-23 20:39:35.3853 Info Logger has been shut down.
|
||||
2019-05-23 20:41:03.9531 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:41:04.0224 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:41:04.2489 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:41:04.2638 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:41:04.2801 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:41:04.3178 Info Found 45 configuration items
|
||||
2019-05-23 20:42:20.8771 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:42:20.8771 Info Found 45 configuration items
|
||||
2019-05-23 20:42:20.8771 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:42:20.8771 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:42:20.8771 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:42:20.8771 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:42:20.8912 Info Closing old configuration.
|
||||
2019-05-23 20:42:20.9264 Info Found 45 configuration items
|
||||
2019-05-23 20:44:09.2436 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:44:09.2625 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:44:09.5033 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:44:09.5221 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:44:09.5436 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:44:09.5955 Info Found 45 configuration items
|
||||
2019-05-23 20:44:22.9386 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:44:22.9386 Info Found 45 configuration items
|
||||
2019-05-23 20:44:22.9386 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:44:22.9525 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:44:22.9525 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:44:22.9525 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:44:22.9525 Info Closing old configuration.
|
||||
2019-05-23 20:44:22.9920 Info Found 45 configuration items
|
||||
2019-05-23 20:45:56.3589 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:45:56.3781 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:45:56.5714 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:45:56.5830 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:45:56.5944 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:45:56.6232 Info Found 45 configuration items
|
||||
2019-05-23 20:46:59.8334 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:46:59.8559 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:47:00.0588 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:47:00.0756 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:47:00.1007 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:47:00.1455 Info Found 45 configuration items
|
||||
2019-05-23 20:48:14.1040 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:48:14.1282 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:48:14.2899 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:48:14.3059 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:48:14.3273 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:48:14.3764 Info Found 45 configuration items
|
||||
2019-05-23 20:49:07.1970 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:49:07.2494 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:49:07.4433 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:49:07.4565 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:49:07.4760 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:49:07.5338 Info Found 45 configuration items
|
||||
2019-05-23 20:49:20.7109 Info Message Template Auto Format enabled
|
||||
2019-05-23 20:49:20.7109 Info Found 45 configuration items
|
||||
2019-05-23 20:49:20.7109 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 20:49:20.7184 Info Adding target File Target[allfile]
|
||||
2019-05-23 20:49:20.7184 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 20:49:20.7184 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 20:49:20.7184 Info Closing old configuration.
|
||||
2019-05-23 20:49:20.7514 Info Found 45 configuration items
|
||||
2019-05-23 21:24:18.4464 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:24:18.4889 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:24:18.7399 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:24:18.7604 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:24:18.7838 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:24:18.8238 Info Found 45 configuration items
|
||||
2019-05-23 21:25:06.3861 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:25:06.3904 Info Found 45 configuration items
|
||||
2019-05-23 21:25:06.3904 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:25:06.4052 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:25:06.4052 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:25:06.4052 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:25:06.4243 Info Closing old configuration.
|
||||
2019-05-23 21:25:06.4727 Info Found 45 configuration items
|
||||
2019-05-23 21:26:26.1707 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:26:26.1964 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:26:26.3688 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:26:26.3866 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:26:26.4195 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:26:26.4805 Info Found 45 configuration items
|
||||
2019-05-23 21:27:58.0534 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:27:58.0751 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:27:58.2630 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:27:58.2786 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:27:58.2977 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:27:58.3440 Info Found 45 configuration items
|
||||
2019-05-23 21:28:30.3852 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:28:30.3901 Info Found 45 configuration items
|
||||
2019-05-23 21:28:30.3901 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:28:30.4094 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:28:30.4094 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:28:30.4094 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:28:30.4256 Info Closing old configuration.
|
||||
2019-05-23 21:28:30.4744 Info Found 45 configuration items
|
||||
2019-05-23 21:28:35.1110 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:28:35.1110 Info Found 45 configuration items
|
||||
2019-05-23 21:28:35.1110 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:28:35.1110 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:28:35.1110 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:28:35.1110 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:28:35.1110 Info Closing old configuration.
|
||||
2019-05-23 21:28:35.1110 Info Found 45 configuration items
|
||||
2019-05-23 21:33:27.3097 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:33:27.3317 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:33:27.6071 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:33:27.6230 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:33:27.6409 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:33:27.6860 Info Found 45 configuration items
|
||||
2019-05-23 21:34:21.2749 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:34:21.2749 Info Found 45 configuration items
|
||||
2019-05-23 21:34:21.2822 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:34:21.2822 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:34:21.2977 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:34:21.2977 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:34:21.2977 Info Closing old configuration.
|
||||
2019-05-23 21:34:21.3496 Info Found 45 configuration items
|
||||
2019-05-23 21:34:44.8361 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:34:44.8361 Info Found 45 configuration items
|
||||
2019-05-23 21:34:44.8361 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:34:44.8475 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:34:44.8475 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:34:44.8475 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:34:44.8475 Info Closing old configuration.
|
||||
2019-05-23 21:34:49.8402 Info Found 45 configuration items
|
||||
2019-05-23 21:36:39.6643 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:36:39.6956 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:36:39.9527 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:36:39.9527 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:36:39.9854 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:36:40.0214 Info Found 45 configuration items
|
||||
2019-05-23 21:37:11.5126 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:37:11.5149 Info Found 45 configuration items
|
||||
2019-05-23 21:37:11.5149 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:37:11.5149 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:37:11.5149 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:37:11.5149 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:37:11.5149 Info Closing old configuration.
|
||||
2019-05-23 21:37:11.5688 Info Found 45 configuration items
|
||||
2019-05-23 21:37:55.3893 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:37:55.3912 Info Found 45 configuration items
|
||||
2019-05-23 21:37:55.3912 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:37:55.3912 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:37:55.4088 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:37:55.4088 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:37:55.4088 Info Closing old configuration.
|
||||
2019-05-23 21:37:55.4088 Info Found 45 configuration items
|
||||
2019-05-23 21:44:40.0208 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:44:40.0474 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:44:40.2073 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:44:40.2186 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:44:40.2186 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:44:40.2868 Info Found 45 configuration items
|
||||
2019-05-23 21:45:19.6595 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:45:19.6595 Info Found 45 configuration items
|
||||
2019-05-23 21:45:19.6595 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:45:19.6595 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:45:19.6595 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:45:19.6595 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:45:19.6740 Info Closing old configuration.
|
||||
2019-05-23 21:45:19.7116 Info Found 45 configuration items
|
||||
2019-05-23 21:51:00.1698 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:51:00.1840 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:51:00.2721 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:51:00.2721 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:51:00.2920 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:51:00.3152 Info Found 45 configuration items
|
||||
2019-05-23 21:51:25.1256 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:51:25.1256 Info Found 45 configuration items
|
||||
2019-05-23 21:51:25.1256 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:51:25.1256 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:51:25.1256 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:51:25.1256 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:51:25.1412 Info Closing old configuration.
|
||||
2019-05-23 21:51:25.1648 Info Found 45 configuration items
|
||||
2019-05-23 21:51:25.2103 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:51:25.2103 Info Found 45 configuration items
|
||||
2019-05-23 21:51:25.2103 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:51:25.2103 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:51:25.2103 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:51:25.2103 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:51:25.2103 Info Closing old configuration.
|
||||
2019-05-23 21:51:25.2182 Info Found 45 configuration items
|
||||
2019-05-23 21:53:11.2368 Info Logger closing down...
|
||||
2019-05-23 21:53:11.2368 Info Closing old configuration.
|
||||
2019-05-23 21:53:11.2368 Info Logger has been closed down.
|
||||
2019-05-23 21:53:11.2368 Info Shutting down logging...
|
||||
2019-05-23 21:53:11.2555 Info Logger has been shut down.
|
||||
2019-05-23 21:54:25.6441 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:54:25.6761 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:54:25.9546 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:54:25.9757 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:54:25.9951 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:54:26.0361 Info Found 45 configuration items
|
||||
2019-05-23 21:54:55.6086 Info Message Template Auto Format enabled
|
||||
2019-05-23 21:54:55.6086 Info Found 45 configuration items
|
||||
2019-05-23 21:54:55.6086 Info Loading assembly: NLog.Web.AspNetCore
|
||||
2019-05-23 21:54:55.6086 Info Adding target File Target[allfile]
|
||||
2019-05-23 21:54:55.6086 Info Adding target File Target[ownFile-web]
|
||||
2019-05-23 21:54:55.6086 Info Configured from an XML element in C:\Users\user0\Programming\C#\Icarus\bin\Debug\netcoreapp2.2\nlog.config...
|
||||
2019-05-23 21:54:55.6280 Info Closing old configuration.
|
||||
2019-05-23 21:54:55.6926 Info Found 45 configuration items
|
||||
|
Before Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 52 KiB |
|
Before Width: | Height: | Size: 123 KiB |
|
Before Width: | Height: | Size: 74 KiB |
|
Before Width: | Height: | Size: 86 KiB |
|
Before Width: | Height: | Size: 49 KiB |
|
Before Width: | Height: | Size: 102 KiB |
|
Before Width: | Height: | Size: 24 KiB |
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2019 Kun Deng
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,24 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class Album
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int AlbumId { get; set; }
|
||||
[JsonProperty("title")]
|
||||
public string Title { get; set; }
|
||||
[JsonProperty("album_artist")]
|
||||
public string AlbumArtist { get; set; }
|
||||
[JsonProperty("song_count")]
|
||||
[NotMapped]
|
||||
public int SongCount { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public List<Song> Songs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class Artist
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int ArtistId { get; set; }
|
||||
[JsonProperty("name")]
|
||||
public string Name { get; set; }
|
||||
[JsonProperty("song_count")]
|
||||
[NotMapped]
|
||||
public int SongCount { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public List<Song> Songs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
using System;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class BaseResult
|
||||
{
|
||||
[JsonProperty("message")]
|
||||
public string Message { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class CoverArt
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int CoverArtId { get; set; }
|
||||
[JsonProperty("title")]
|
||||
public string SongTitle { get; set; }
|
||||
[JsonIgnore]
|
||||
public string ImagePath { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public List<Song> Songs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class Genre
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int GenreId { get; set; }
|
||||
[JsonProperty("genre")]
|
||||
public string GenreName { get; set; }
|
||||
[JsonProperty("song_count")]
|
||||
[NotMapped]
|
||||
public int SongCount { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public List<Song> Songs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
using System;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class LoginResult : BaseResult
|
||||
{
|
||||
[JsonProperty("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; }
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
using System;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class Song
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int Id { get; set; }
|
||||
[JsonProperty("title")]
|
||||
public string Title { get; set; }
|
||||
[JsonProperty("album")]
|
||||
public string AlbumTitle { get; set; }
|
||||
[JsonProperty("artist")]
|
||||
public string Artist { 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; }
|
||||
[JsonProperty("song_path")]
|
||||
public string SongPath { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public Album Album { get; set; }
|
||||
[JsonIgnore]
|
||||
public int? AlbumId { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public Artist SongArtist { get; set; }
|
||||
[JsonIgnore]
|
||||
public int? ArtistId { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public Genre SongGenre { get; set; }
|
||||
[JsonIgnore]
|
||||
public int? GenreId { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public Year SongYear { get; set; }
|
||||
[JsonIgnore]
|
||||
public int? YearId { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public CoverArt SongCoverArt { get; set; }
|
||||
[JsonIgnore]
|
||||
public int? CoverArtId { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -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; }
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
using System;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class User
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int Id { get; set; }
|
||||
[JsonProperty("username")]
|
||||
public string Username { get; set; }
|
||||
[JsonProperty("nickname")]
|
||||
public string Nickname { get; set; }
|
||||
[JsonProperty("password")]
|
||||
public string Password { get; set; }
|
||||
[JsonProperty("email")]
|
||||
public string Email { get; set; }
|
||||
[JsonProperty("phone_number")]
|
||||
public string PhoneNumber { get; set; }
|
||||
[JsonProperty("first_name")]
|
||||
public string Firstname { get; set; }
|
||||
[JsonProperty("last_name")]
|
||||
public string Lastname { get; set; }
|
||||
[JsonProperty("email_verified")]
|
||||
public bool EmailVerified { get; set; }
|
||||
[JsonProperty("date_created")]
|
||||
public DateTime DateCreated { get; set; }
|
||||
[JsonProperty("last_login")]
|
||||
public DateTime? LastLogin { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace Icarus.Models
|
||||
{
|
||||
public class Year
|
||||
{
|
||||
[JsonProperty("id")]
|
||||
public int YearId { get; set; }
|
||||
[JsonProperty("year")]
|
||||
public int YearValue { get; set; }
|
||||
[JsonProperty("song_count")]
|
||||
[NotMapped]
|
||||
public int SongCount { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public List<Song> Songs { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,47 +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.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");
|
||||
CreateWebHostBuilder(args).Build().Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.Error(ex, "An error occurred");
|
||||
throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
NLog.LogManager.Shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
|
||||
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>()
|
||||
.UseUrls("http://localhost:5002")
|
||||
.ConfigureLogging(logging =>
|
||||
{
|
||||
logging.ClearProviders();
|
||||
logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
|
||||
})
|
||||
.UseNLog();
|
||||
}
|
||||
}
|
||||
@@ -1,30 +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": "api/values",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"Icarus": {
|
||||
"commandName": "Project",
|
||||
"launchBrowser": true,
|
||||
"launchUrl": "api/values",
|
||||
"applicationUrl": "http://localhost:5002",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,164 +1,17 @@
|
||||
# Icarus
|
||||
|
||||
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)
|
||||
|
||||
|
||||
# Getting Started
|
||||
## Docker
|
||||
Make sure `icarus_auth` is located in the root of the parent directory if using docker.
|
||||
|
||||
## Built With
|
||||
Create a `.env` file for both projects - `icarus_auth` and `icarus` - in the root of each project.
|
||||
|
||||
|
||||
* C#
|
||||
* [.NET Core](https://dotnet.microsoft.com/) 2.2
|
||||
* .NET Web RESTful API
|
||||
* [MySql](https://www.nuget.org/packages/MySql.Data/)
|
||||
* [Newtonsoft.Json](https://www.newtonsoft.com/json)
|
||||
* [TagLib#](https://github.com/mono/taglib-sharp)
|
||||
|
||||

|
||||
|
||||
## Getting started
|
||||
There are several things that need to be completed to properly setup and secure the API.
|
||||
1. Auth0 API configuration
|
||||
2. API filesystem paths
|
||||
3. Database connection string
|
||||
4. Migrations
|
||||
|
||||
### Auth0 API configuration
|
||||
|
||||
Securing Icarus is required, preventing the API from being publicly accessible. To do so, create an Auth0 account (it's free), for the sake of this section of the documentation, I will not go over how to create an Auth0 account. Once created, create a tentant and proceed to create an API
|
||||
<h1 align=center>
|
||||
<img src="Images/Configuration/create_api.png" width=100%>
|
||||
</h1>
|
||||
|
||||
Create the API and enter an approrpiate name and identified. For the identified, append **api** like in the example
|
||||
<h1 align="center">
|
||||
<img src="Images/Configuration/enter_api_info.png" width=100%>
|
||||
</h1>
|
||||
Replace [domain] with the domain name of the created tenant. This can be found in the Default App from the Application menu. 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.
|
||||
|
||||
```Json
|
||||
"Auth0": {
|
||||
"Domain": "[domain].auth0.com",
|
||||
"ApiIdentifier": "https://[identifier]/api"
|
||||
},
|
||||
Build containers
|
||||
```
|
||||
docker compose build --ssh default api auth_api
|
||||
```
|
||||
|
||||
For the sake of this section, I will not go over configuring the API to accept the signing algorithm since it has already been configured in the [Startip](Startup.cs).cs file. Click on permissions to create the permissions for the API.
|
||||
<h1 align "center">
|
||||
<img src="Images/Configuration/configure_api.png" width=100%>
|
||||
</h1>
|
||||
|
||||
The permissions ensure that a validated user can interact with the API with a token that has not expired. Ensure that the permissions match, the description can change but the permission identifier must match.
|
||||
<h1 align="center">
|
||||
<img src="Images/Configuration/permissions.png" width=100%>
|
||||
</h1>
|
||||
|
||||
On the left side, click on Application and create a new Application. Choose the Machine to Machine Application
|
||||
<h1 align="center">
|
||||
<img src="Images/Configuration/create_m2m.png" width=100%>
|
||||
</h1>
|
||||
|
||||
With the grant permissions you created from the API, enable all the permissions. This is important because if they are not enabled then even with a valid token the request will return 403 (unauthorized)
|
||||
<h1 align="center">
|
||||
<img src="Images/Configuration/authorize_app.png" width=100%>
|
||||
</h1>
|
||||
|
||||
From the Application page, copy the client id and client secret. These values will be used for the API to interact with API.
|
||||
<h1 align="center">
|
||||
<img src="Images/Configuration/api_cred.png" width=100%>
|
||||
</h1>
|
||||
Enter the information in the corresponding appsettings json file
|
||||
```Json
|
||||
"Auth0": {
|
||||
"ClientId":"",
|
||||
"ClientSecret":""
|
||||
},
|
||||
Bring it up
|
||||
```
|
||||
|
||||
### 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/"
|
||||
}
|
||||
docker compose up -d --force-recreate api auth_api
|
||||
```
|
||||
* 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
|
||||
|
||||
|
||||
**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.
|
||||
|
||||
## Versioning
|
||||
|
||||
* [v0.1](https://github.com/amazing-username/Icarus/releases/tag/v0.1)
|
||||
|
||||
## Authors
|
||||
|
||||
* **Kun Deng** - [amazing-username](https://github.com/amazing-username)
|
||||
|
||||
See also the list of [contributors](https://github.com/amazing-username/Icarus/graphs/contributors) who participated in this project.
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -1,6 +0,0 @@
|
||||
delete from Song;
|
||||
delete from Album;
|
||||
delete from Artist;
|
||||
delete from Genre;
|
||||
delete from Year;
|
||||
delete from CoverArt;
|
||||
@@ -1 +0,0 @@
|
||||
select * from Song;
|
||||
@@ -1,157 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.HttpsPolicy;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using MySql.Data;
|
||||
using MySql.Data.EntityFrameworkCore.Extensions;
|
||||
using MySql.Data.MySqlClient;
|
||||
using NLog;
|
||||
using NLog.Web;
|
||||
using NLog.Web.AspNetCore;
|
||||
|
||||
using Icarus.Authorization;
|
||||
using Icarus.Authorization.Handlers;
|
||||
using Icarus.Database.Contexts;
|
||||
using Icarus.Database.Repositories;
|
||||
|
||||
namespace Icarus
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public Startup(IConfiguration configuration)
|
||||
{
|
||||
Configuration = configuration;
|
||||
}
|
||||
|
||||
public IConfiguration Configuration { get; }
|
||||
|
||||
// This method gets called by the runtime. Use this method to add services to the container.
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
|
||||
services.AddSingleton<IConfiguration>(Configuration);
|
||||
|
||||
string domain = $"https://{Configuration["Auth0:Domain"]}/";
|
||||
|
||||
services.AddAuthentication(options =>
|
||||
{
|
||||
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||
}).AddJwtBearer(options =>
|
||||
{
|
||||
options.Authority = domain;
|
||||
options.Audience = Configuration["Auth0:ApiIdentifier"];
|
||||
});
|
||||
|
||||
services.AddAuthorization(options =>
|
||||
{
|
||||
options.AddPolicy("download:songs", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("download:songs", domain)));
|
||||
|
||||
options.AddPolicy("download:cover_art", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("download:cover_art", domain)));
|
||||
|
||||
options.AddPolicy("upload:songs", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("upload:songs", domain)));
|
||||
|
||||
options.AddPolicy("delete:songs", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("delete:songs", domain)));
|
||||
|
||||
options.AddPolicy("read:song_details", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("read:song_details", domain)));
|
||||
|
||||
options.AddPolicy("update:songs", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("update:songs", domain)));
|
||||
|
||||
options.AddPolicy("read:artists", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("read:artists", domain)));
|
||||
|
||||
options.AddPolicy("read:albums", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("read:albums", domain)));
|
||||
|
||||
options.AddPolicy("read:genre", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("read:genre", domain)));
|
||||
|
||||
options.AddPolicy("read:year", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("read:year", domain)));
|
||||
|
||||
options.AddPolicy("stream:songs", policy =>
|
||||
policy.Requirements
|
||||
.Add(new HasScopeRequirement("stream:songs", domain)));
|
||||
});
|
||||
|
||||
|
||||
services.AddSingleton<IAuthorizationHandler, HasScopeHandler>();
|
||||
|
||||
var connString = Configuration.GetConnectionString("DefaultConnection");
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(SongRepository),
|
||||
new SongRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(AlbumRepository),
|
||||
new AlbumRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(ArtistRepository),
|
||||
new ArtistRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(GenreRepository),
|
||||
new GenreRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(YearRepository),
|
||||
new YearRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(CoverArtRepository),
|
||||
new CoverArtRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
services.Add(new ServiceDescriptor(typeof(UserRepository),
|
||||
new UserRepository(Configuration.GetConnectionString("DefaultConnection"))));
|
||||
|
||||
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<YearContext>(options => options.UseMySQL(connString));
|
||||
services.AddDbContext<CoverArtContext>(options => options.UseMySQL(connString));
|
||||
}
|
||||
|
||||
// Called by the runtime. Use this method to configure the HTTP request pipeline.
|
||||
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
|
||||
{
|
||||
if (env.IsDevelopment())
|
||||
app.UseDeveloperExceptionPage();
|
||||
else
|
||||
// The default HSTS value is 30 days.
|
||||
// You may want to change this for production scenarios
|
||||
app.UseHsts();
|
||||
|
||||
app.UseAuthentication();
|
||||
|
||||
app.UseHttpsRedirection();
|
||||
app.UseMvc();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Icarus.Types
|
||||
{
|
||||
public enum CoverArtField
|
||||
{
|
||||
SongTitle = 0,
|
||||
ImagePath
|
||||
};
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace Icarus.Types
|
||||
{
|
||||
public enum DirectoryType
|
||||
{
|
||||
Music = 0,
|
||||
CoverArt
|
||||
};
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Debug",
|
||||
"System": "Information",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
},
|
||||
"Auth0": {
|
||||
"Domain": "[domain].auth0.com",
|
||||
"ApiIdentifier": "https://[identifier]/api",
|
||||
"ClientId": "",
|
||||
"ClientSecret": ""
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=;Database=;Uid=;Pwd=;"
|
||||
},
|
||||
"RootMusicPath": "/music/path/",
|
||||
"TemporaryMusicPath": "/music/temp/path/",
|
||||
"ArchivePath": "/archive/path/",
|
||||
"CoverArtPath": "/cover/art/path/"
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Trace",
|
||||
"Microsoft": "Information"
|
||||
}
|
||||
},
|
||||
"AllowedHosts": "*",
|
||||
"Auth0": {
|
||||
"Domain": "[domain].auth0.com",
|
||||
"ApiIdentifier": "https://[identifier]/api",
|
||||
"ClientId": "",
|
||||
"ClientSecret": ""
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=;Database=;Uid=;Pwd=;"
|
||||
},
|
||||
"RootMusicPath": "/music/path/",
|
||||
"TemporaryMusicPath": "/music/temp/path/",
|
||||
"ArchivePath": "/archive/path/",
|
||||
"CoverArtPath": "/cover/art/path/"
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
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)
|
||||
# Format: "HOST_PORT:CONTAINER_PORT"
|
||||
- "8000:3000"
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
main_db:
|
||||
condition: service_healthy
|
||||
networks:
|
||||
- main-api-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:3000" # 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:
|
||||
- auth-api-network
|
||||
# Optional: Mount local code for development (live reload)
|
||||
# volumes:
|
||||
# - ./path/to/your/web-api-repo:/app
|
||||
|
||||
# PostgreSQL Database Service
|
||||
# --- icarus web api db ---
|
||||
main_db:
|
||||
image: postgres:17.5-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/data
|
||||
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:
|
||||
- main-api-network
|
||||
|
||||
# --- icarus web auth api db ---
|
||||
auth_db:
|
||||
image: postgres:17.5-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/data
|
||||
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:
|
||||
- auth-api-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:
|
||||
main-api-network:
|
||||
driver: bridge
|
||||
auth-api-network:
|
||||
driver: bridge
|
||||
@@ -0,0 +1,62 @@
|
||||
-- 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,
|
||||
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,
|
||||
-- TODO: Separate path later
|
||||
path TEXT NOT NULL,
|
||||
song_id UUID NOT NULL
|
||||
-- TODO: Add type later
|
||||
);
|
||||
@@ -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>
|
||||
@@ -0,0 +1,649 @@
|
||||
// TODO: Separate queue and coverart endpoints
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
pub struct CoverArtQueue {
|
||||
pub id: uuid::Uuid,
|
||||
pub song_queue_id: uuid::Uuid,
|
||||
}
|
||||
|
||||
pub mod request {
|
||||
|
||||
pub mod link {
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
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)]
|
||||
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)]
|
||||
pub struct Params {
|
||||
pub id: Option<uuid::Uuid>,
|
||||
pub song_queue_id: Option<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod create_coverart {
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Request {
|
||||
pub song_id: uuid::Uuid,
|
||||
pub coverart_queue_id: uuid::Uuid,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod wipe_data_from_coverart_queue {
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Request {
|
||||
pub coverart_queue_id: uuid::Uuid,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod get_coverart {
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Params {
|
||||
pub id: Option<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod response {
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<uuid::Uuid>,
|
||||
}
|
||||
|
||||
pub mod link {
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Id {
|
||||
pub coverart_id: uuid::Uuid,
|
||||
pub song_queue_id: uuid::Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<Id>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod fetch_coverart_no_data {
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
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)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<Vec<u8>>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod create_coverart {
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<icarus_models::coverart::CoverArt>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod wipe_data_from_coverart_queue {
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod get_coverart {
|
||||
#[derive(Debug, Default, serde::Deserialize, serde::Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<icarus_models::coverart::CoverArt>,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod db {
|
||||
use sqlx::Row;
|
||||
|
||||
pub async fn insert(pool: &sqlx::PgPool, data: &Vec<u8>) -> Result<uuid::Uuid, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO "coverartQueue" (data) VALUES($1) RETURNING id;
|
||||
"#,
|
||||
)
|
||||
.bind(data)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error inserting: {e:?}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => {
|
||||
let id: uuid::Uuid = row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap();
|
||||
Ok(id)
|
||||
}
|
||||
Err(_err) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn update(
|
||||
pool: &sqlx::PgPool,
|
||||
coverart_id: &uuid::Uuid,
|
||||
song_queue_id: &uuid::Uuid,
|
||||
) -> Result<i32, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
UPDATE "coverartQueue" SET song_queue_id = $1 WHERE id = $2;
|
||||
"#,
|
||||
)
|
||||
.bind(song_queue_id)
|
||||
.bind(coverart_id)
|
||||
.execute(pool)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(_) => Ok(0),
|
||||
Err(_err) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_coverart_queue_with_id(
|
||||
pool: &sqlx::PgPool,
|
||||
id: &uuid::Uuid,
|
||||
) -> Result<super::CoverArtQueue, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT id, song_queue_id FROM "coverartQueue" WHERE id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error querying data: {e:?}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(super::CoverArtQueue {
|
||||
id: row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
song_queue_id: row
|
||||
.try_get("song_queue_id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
}),
|
||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_coverart_queue_with_song_queue_id(
|
||||
pool: &sqlx::PgPool,
|
||||
song_queue_id: &uuid::Uuid,
|
||||
) -> Result<super::CoverArtQueue, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT id, song_queue_id FROM "coverartQueue" WHERE song_queue_id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(song_queue_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error querying data: {e:?}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(super::CoverArtQueue {
|
||||
id: row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
song_queue_id: row
|
||||
.try_get("song_queue_id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
}),
|
||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_coverart_queue_data_with_id(
|
||||
pool: &sqlx::PgPool,
|
||||
id: &uuid::Uuid,
|
||||
) -> Result<Vec<u8>, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT data FROM "coverartQueue" WHERE id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error querying data: {e:?}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(row
|
||||
.try_get("data")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap()),
|
||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_coverart_queue_data_with_song_queue_id(
|
||||
pool: &sqlx::PgPool,
|
||||
song_queue_id: &uuid::Uuid,
|
||||
) -> Result<Vec<u8>, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT data FROM "coverartQueue" WHERE song_queue_id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(song_queue_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error querying data: {e}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(row
|
||||
.try_get("data")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap()),
|
||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn wipe_data(
|
||||
pool: &sqlx::PgPool,
|
||||
coverart_queue_id: &uuid::Uuid,
|
||||
) -> Result<uuid::Uuid, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
UPDATE "coverartQueue" SET data = NULL WHERE id = $1 RETURNING id;
|
||||
"#,
|
||||
)
|
||||
.bind(coverart_queue_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error updating query: {e}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap()),
|
||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod cov_db {
|
||||
use sqlx::Row;
|
||||
|
||||
pub async fn create(
|
||||
pool: &sqlx::PgPool,
|
||||
coverart: &icarus_models::coverart::CoverArt,
|
||||
song_id: &uuid::Uuid,
|
||||
) -> Result<uuid::Uuid, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO "coverart" (title, path, song_id) VALUES($1, $2, $3) RETURNING id;
|
||||
"#,
|
||||
)
|
||||
.bind(&coverart.title)
|
||||
.bind(&coverart.path)
|
||||
.bind(song_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error inserting: {e}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => {
|
||||
let id: uuid::Uuid = row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap();
|
||||
Ok(id)
|
||||
}
|
||||
Err(_err) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_coverart(
|
||||
pool: &sqlx::PgPool,
|
||||
id: &uuid::Uuid,
|
||||
) -> Result<icarus_models::coverart::CoverArt, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT id, title, path, song_id FROM "coverart" WHERE id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error querying data: {e:?}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(icarus_models::coverart::CoverArt {
|
||||
id: row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
title: row
|
||||
.try_get("title")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
path: row
|
||||
.try_get("path")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
data: Vec::new(),
|
||||
song_id: row
|
||||
.try_get("song_id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
}),
|
||||
Err(_) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod endpoint {
|
||||
use std::io::Write;
|
||||
|
||||
use axum::response::IntoResponse;
|
||||
|
||||
pub async fn queue(
|
||||
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
|
||||
mut multipart: axum::extract::Multipart,
|
||||
) -> (
|
||||
axum::http::StatusCode,
|
||||
axum::Json<super::response::Response>,
|
||||
) {
|
||||
let mut response = super::response::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();
|
||||
|
||||
println!(
|
||||
"Received file '{}' (name = '{}', content-type = '{}', size = {})",
|
||||
file_name,
|
||||
name,
|
||||
content_type,
|
||||
data.len()
|
||||
);
|
||||
|
||||
match super::db::insert(&pool, &raw_data).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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 super::db::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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 super::db::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 super::db::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))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
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 super::db::get_coverart_queue_data_with_id(&pool, &id).await {
|
||||
Ok(data) => {
|
||||
let bytes = axum::body::Bytes::from(data);
|
||||
let mut response = bytes.into_response();
|
||||
let headers = response.headers_mut();
|
||||
// TODO: Address this hard coding for the coverart content type
|
||||
headers.insert(axum::http::header::CONTENT_TYPE, "image".parse().unwrap());
|
||||
// TODO: Make the conent disposition more dynamic
|
||||
headers.insert(
|
||||
axum::http::header::CONTENT_DISPOSITION,
|
||||
format!("attachment; filename=\"{id}.jpg\"")
|
||||
.parse()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
(axum::http::StatusCode::OK, response)
|
||||
}
|
||||
Err(_err) => (
|
||||
axum::http::StatusCode::BAD_REQUEST,
|
||||
axum::response::Response::default(),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
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 super::db::get_coverart_queue_data_with_id(&pool, &id).await {
|
||||
Ok(data) => {
|
||||
let song_id = payload.song_id;
|
||||
match crate::callers::song::song_db::get_song(&pool, &song_id).await {
|
||||
Ok(song) => {
|
||||
let directory = icarus_envy::environment::get_root_directory().await;
|
||||
let dir = std::path::Path::new(&directory);
|
||||
|
||||
// TODO: Make this random and the file extension should not be hard coded
|
||||
let filename = format!("{}-coverart.jpeg", &song.filename[..8]);
|
||||
let save_path = dir.join(&filename);
|
||||
let path = String::from(save_path.to_str().unwrap());
|
||||
let mut coverart =
|
||||
icarus_models::coverart::init::init_coverart_only_path(path);
|
||||
coverart.title = song.album.clone();
|
||||
coverart.data = data;
|
||||
|
||||
let mut file = std::fs::File::create(&save_path).unwrap();
|
||||
file.write_all(&coverart.data).unwrap();
|
||||
|
||||
match super::cov_db::create(&pool, &coverart, &song.id).await {
|
||||
Ok(id) => {
|
||||
// TODO: Populate 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::BAD_REQUEST, axum::Json(response))
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
response.message = err.to_string();
|
||||
(axum::http::StatusCode::BAD_REQUEST, axum::Json(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 super::db::get_coverart_queue_with_id(&pool, &coverart_queue_id).await {
|
||||
Ok(coverart_queue) => match super::db::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))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 super::cov_db::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))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
// TODO: Explicitly make this module target queueing a song's metadata
|
||||
pub mod request {
|
||||
|
||||
pub mod queue_metadata {
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Default, Deserialize, Serialize, sqlx::FromRow)]
|
||||
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,
|
||||
)]
|
||||
pub struct Params {
|
||||
pub id: Option<uuid::Uuid>,
|
||||
pub song_queue_id: Option<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod response {
|
||||
|
||||
pub mod queue_metadata {
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<uuid::Uuid>,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod fetch_metadata {
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Default, Deserialize, Serialize)]
|
||||
pub struct Response {
|
||||
pub message: String,
|
||||
pub data: Vec<crate::callers::metadata::metadata_queue::MetadataQueue>,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod metadata_queue {
|
||||
use sqlx::Row;
|
||||
|
||||
#[derive(Debug, serde::Serialize, sqlx::FromRow)]
|
||||
pub struct InsertedData {
|
||||
pub id: uuid::Uuid,
|
||||
}
|
||||
|
||||
#[derive(Debug, serde::Deserialize, serde::Serialize, sqlx::FromRow)]
|
||||
pub struct MetadataQueue {
|
||||
pub id: uuid::Uuid,
|
||||
pub metadata: serde_json::Value,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub created_at: time::OffsetDateTime,
|
||||
pub song_queue_id: uuid::Uuid,
|
||||
}
|
||||
|
||||
pub async fn insert(
|
||||
pool: &sqlx::PgPool,
|
||||
metadata: &serde_json::Value,
|
||||
song_queue_id: &uuid::Uuid,
|
||||
) -> Result<uuid::Uuid, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
INSERT INTO "metadataQueue" (metadata, song_queue_id) VALUES($1, $2) RETURNING id;
|
||||
"#,
|
||||
)
|
||||
.bind(metadata)
|
||||
.bind(song_queue_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error inserting: {e}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => {
|
||||
let id: uuid::Uuid = row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap();
|
||||
Ok(id)
|
||||
}
|
||||
Err(_err) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_with_song_queue_id(
|
||||
pool: &sqlx::PgPool,
|
||||
song_queue_id: &uuid::Uuid,
|
||||
) -> Result<MetadataQueue, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT * FROM "metadataQueue" WHERE song_queue_id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(song_queue_id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error inserting: {e}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => Ok(MetadataQueue {
|
||||
id: row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
metadata: row
|
||||
.try_get("metadata")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
created_at: row
|
||||
.try_get("created_at")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
song_queue_id: row
|
||||
.try_get("song_queue_id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
}),
|
||||
Err(_err) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn get_with_id(
|
||||
pool: &sqlx::PgPool,
|
||||
id: &uuid::Uuid,
|
||||
) -> Result<MetadataQueue, sqlx::Error> {
|
||||
let result = sqlx::query(
|
||||
r#"
|
||||
SELECT id, metadata, created_at, song_queue_id FROM "metadataQueue" WHERE id = $1;
|
||||
"#,
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
eprintln!("Error inserting: {e}");
|
||||
});
|
||||
|
||||
match result {
|
||||
Ok(row) => {
|
||||
let data: serde_json::Value = row
|
||||
.try_get("metadata")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap();
|
||||
Ok(MetadataQueue {
|
||||
id: row
|
||||
.try_get("id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
metadata: data,
|
||||
created_at: row
|
||||
.try_get("created_at")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
song_queue_id: row
|
||||
.try_get("song_queue_id")
|
||||
.map_err(|_e| sqlx::Error::RowNotFound)
|
||||
.unwrap(),
|
||||
})
|
||||
}
|
||||
Err(_err) => Err(sqlx::Error::RowNotFound),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod endpoint {
|
||||
use axum::{Json, http::StatusCode};
|
||||
|
||||
pub async fn queue_metadata(
|
||||
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
|
||||
Json(payload): Json<super::request::queue_metadata::Request>,
|
||||
) -> (StatusCode, 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 super::metadata_queue::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("Success")
|
||||
};
|
||||
|
||||
(StatusCode::OK, Json(response))
|
||||
}
|
||||
Err(err) => {
|
||||
response.message = err.to_string();
|
||||
(StatusCode::BAD_REQUEST, Json(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>,
|
||||
) -> (StatusCode, 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 super::metadata_queue::get_with_id(&pool, &id).await {
|
||||
Ok(item) => {
|
||||
response.message = String::from("Successful");
|
||||
response.data.push(item);
|
||||
(StatusCode::OK, Json(response))
|
||||
}
|
||||
Err(err) => {
|
||||
response.message = err.to_string();
|
||||
(StatusCode::BAD_REQUEST, Json(response))
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => match params.song_queue_id {
|
||||
Some(song_queue_id) => {
|
||||
println!("Song queue Id is probably not nil");
|
||||
match super::metadata_queue::get_with_song_queue_id(&pool, &song_queue_id).await
|
||||
{
|
||||
Ok(item) => {
|
||||
response.message = String::from("Successful");
|
||||
response.data.push(item);
|
||||
(StatusCode::OK, Json(response))
|
||||
}
|
||||
Err(err) => {
|
||||
response.message = err.to_string();
|
||||
(StatusCode::BAD_REQUEST, Json(response))
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {
|
||||
println!("What is going on?");
|
||||
(StatusCode::BAD_REQUEST, Json(response))
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
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";
|
||||
|
||||
pub const CREATESONG: &str = "/api/v2/song";
|
||||
pub const GETSONGS: &str = "/api/v2/song";
|
||||
pub const STREAMSONG: &str = "/api/v2/song/stream/{id}";
|
||||
pub const DOWNLOADSONG: &str = "/api/v2/song/download/{id}";
|
||||
pub const CREATECOVERART: &str = "/api/v2/coverart";
|
||||
pub const GETCOVERART: &str = "/api/v2/coverart";
|
||||
}
|
||||
|
||||
pub mod response {
|
||||
pub const SUCCESSFUL: &str = "SUCCESSFUL";
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
-- 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,
|
||||
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,
|
||||
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
|
||||
);
|
||||
|
||||
|
||||
CREATE TABLE IF NOT EXISTS "coverart" (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
song_id UUID NOT NULL
|
||||
);
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Add migration script here
|
||||
INSERT INTO "song" (id, title, artist, album_artist, album, genre, year, track, disc, track_count, disc_count, duration, audio_type, date_created, filename, directory, user_id) VALUES('44cf7940-34ff-489f-9124-d0ec90a55af9', 'Hypocrite Like The Rest', 'Kuoth', 'Kuoth', 'I', 'Alternative Hip-Hop', 2020, 1, 1, 9, 1, 139, 'flac', '2020-01-01 13:00:00-05', 'track01.flac', 'tests/I', '47491f9b-725a-4ba4-b9a5-711e1be46670');
|
||||
INSERT INTO "coverart" VALUES('996122cd-5ae9-4013-9934-60768d3006ed', 'I', 'tests/I/Coverart.jpg', '44cf7940-34ff-489f-9124-d0ec90a55af9');
|
||||