Compare commits

..

106 Commits

Author SHA1 Message Date
Kun Deng 01faa60699 Update README.md 2019-10-26 10:31:46 -04:00
amazing-username 8714d76a2a Changes to response returns when song does not exist. The cause of a segmentation fault 2019-10-26 14:23:42 +00:00
kdeng00 e764bc45de When song is uploaded the response returned is info about the song and a response 2019-10-22 20:30:43 -04:00
kdeng00 5fefc451d5 Adding coverart id field to Song dto object to return the coverart id that the song is associated with so it is easier to get the cover art 2019-10-21 21:54:50 -04:00
kdeng00 024134b801 some changes 2019-10-13 11:29:40 -04:00
kdeng00 32ed611112 Authorized endpoints and updated README 2019-09-25 23:03:38 -04:00
kdeng00 698ccf9099 slight change in README.md 2019-09-24 22:31:23 -04:00
kdeng00 1b8c28e67b added user authentication and updated README.md 2019-09-24 22:29:09 -04:00
kdeng00 e936c2da17 Solved issue where I couldn't retirever a user record from the database. Didn't correctly set the MYSql type to string. 2019-09-23 21:38:33 -04:00
kdeng00 4bd794c288 Working on User authentication 2019-09-22 23:57:14 -04:00
kdeng00 89ed9f9252 Updated README.md and completed verification process 2019-09-20 20:56:24 -04:00
kdeng00 8ee39e13c0 Confirmed database connectivity 2019-09-19 22:03:23 -04:00
kdeng00 6a5ebc0078 path configuration file is verified at the start of execution 2019-09-17 20:47:53 -04:00
kdeng00 bb783c61ad started working on function to verify the configuration settings 2019-09-16 22:26:17 -04:00
kdeng00 6e570cd495 finished updating song functionality 2019-09-15 20:57:41 -04:00
kdeng00 9a894487ad Almost done with updating metadata of song, just need to handle records that have no related records associated with them 2019-09-15 00:23:08 -04:00
kdeng00 a82e66ff83 Working on updating a song's metadata 2019-09-13 23:12:09 -04:00
kdeng00 2fdc86e0b3 Figured out how to check if Int32 values from the ObjectWrapper have any values. Just get the pointer of it and see if it is a nullptr 2019-09-12 21:59:29 -04:00
kdeng00 0a97f695e3 Working on updating a song's metadata 2019-09-11 22:12:41 -04:00
kdeng00 a00a70029e Implemented deletion functionality, and lingering records are removed fixes #49 2019-09-10 22:27:28 -04:00
kdeng00 8c1c2340b2 Working on HTTP endpoint to delete songs. Finished with album. Need to work on the Artist, Genre, and Year aspects 2019-09-09 21:57:04 -04:00
kdeng00 19ddb9be0b Added song streamingh endpoint and removed redundant making oatpp::String shared when it already is a shared object #61 2019-09-08 18:48:14 -04:00
kdeng00 949abf8244 stream does not contain the whole song, also when the stream is terminated on the client's side, the service crashed on the server side 2019-09-07 18:30:03 -04:00
kdeng00 fd3a84fbea Working on streaming the song, running into issues trying to figure this out. Wanted to at least commit the work 2019-09-07 15:41:38 -04:00
kdeng00 7ec88397c0 Able to retrieve single and multiple records (Album, Artist, Genre, Year) 2019-09-07 12:00:12 -04:00
kdeng00 e9241cf6a5 Need to work on the ability to fetch records for Artist, Genre, and Year 2019-09-06 22:38:14 -04:00
kdeng00 de838da040 Can fetch cover art records and download a single cover art 2019-09-06 22:13:52 -04:00
kdeng00 ada50b3d5c Still in the process of switching to prepared statements. Left TODO for removing the make_shared_ptr for the raw song data. Added feature to retrieve a sing cover art record in json format 2019-09-05 20:57:13 -04:00
kdeng00 5b9f2a0505 fix for duplicate records being saved. I'm going to continually monitor it, some minor changes might need to be made. The changes are changing to prepared statements for queries 2019-09-04 23:48:37 -04:00
amazing-username d4e9b8c71f Tidied up code, going to put up the coding convention later on 2019-09-04 15:41:43 +00:00
Kun Deng dd995269df Merge pull request #60 from kdeng00/experiment
Switching to C++
2019-09-03 16:17:19 -04:00
kdeng00 12a53ed2b1 Added some TODO's. Need to switch to prepared statements for album, artist, genre, and year repositories 2019-09-03 16:15:37 -04:00
kdeng00 c55d8261a2 Added TODO in the albumRepository.cpp on where to pick up from. Short story: duplicate related records 2019-09-02 20:16:30 -04:00
kdeng00 4306c174b3 Able to save and retrieve records (Artist, Album, Genre, etc.) 2019-09-02 13:59:49 -04:00
kdeng00 fafb39326b Left off at adding album record to the database and retrieving the album record to assign the album id to the song record's album id foreign key 2019-09-01 18:46:02 -04:00
kdeng00 ab3000c2a0 Moved controllers to include directory 2019-09-01 17:13:31 -04:00
kdeng00 c0fba2c9d8 Move Dto's to Dto in include directory and created Dto namespace 2019-09-01 17:08:00 -04:00
kdeng00 dfd4906371 Added Utility and Type namespaces 2019-09-01 16:56:52 -04:00
kdeng00 1ec3511bc5 Added Controller namespace 2019-09-01 16:16:06 -04:00
kdeng00 f75ebe14a7 Added manager classes for song metadata 2019-09-01 15:10:46 -04:00
kdeng00 d16b8dc3c9 Added Manager namespace 2019-09-01 14:14:46 -04:00
kdeng00 d44a5bb1bc Added Model namespace 2019-09-01 13:54:16 -04:00
kdeng00 1255aa0ff7 track and disc numbers are now part of the song's metadata and saved to the database 2019-08-28 22:16:33 -04:00
kdeng00 b885e3d2c8 Ok 2019-08-27 20:33:00 -04:00
amazing-username d0d1008044 Fixed bug that caused a failure in retrieving records. Empty directories are deleted when deleting a song. If the song contains the stock cover art, the stock cover art will not be deleted 2019-08-27 20:13:18 +00:00
kdeng00 ed6f98eb5a Added song delete endpoint 2019-08-26 23:10:24 -04:00
kdeng00 48e97e7cd1 Added support for saving downloading song. It doesn't work outside of curl from the command line. The response body is empty, I'll look into it 2019-08-25 22:21:21 -04:00
kdeng00 fb03354189 Working on downloading the song 2019-08-25 16:47:52 -04:00
kdeng00 540d665a7e Can retrieve all song records 2019-08-25 15:26:47 -04:00
kdeng00 2145adb039 Some clean up for insert song records into the database 2019-08-25 14:54:09 -04:00
kdeng00 d54715ac25 Able to insert song records into the database. Left TODO for clean up 2019-08-25 01:30:13 -04:00
kdeng00 1db3eb2f8c Cover art record saved in the database. Next is to save the song record to the database and then try to download the song afterwards 2019-08-24 18:41:01 -04:00
kdeng00 9281293fad Working on interfacing with the database. Could do queryies via string/cstring but I'm going to try prepared statements 2019-08-23 23:16:42 -04:00
kdeng00 764185da7d Able to save song and cover art to the appropriate paths. Next is saving it to the database 2019-08-22 22:40:49 -04:00
kdeng00 592853695d Added paths.json file that contain paths 2019-08-22 19:49:17 -04:00
kdeng00 2a8290a929 Added script to create database 2019-08-21 07:09:39 -04:00
kdeng00 92f0d4702b Factoring 2019-08-20 22:45:25 -04:00
kdeng00 e42a551193 Now have to check to see if the token has the correct scope 2019-08-20 19:56:26 -04:00
kdeng00 3e94e0e22e Left some TODO's. Next thing is to check if the token is valid 2019-08-19 22:19:47 -04:00
kdeng00 4072526d35 Able to upload song. Left TODO on what's next 2019-08-18 22:58:04 -04:00
kdeng00 bbd8186114 Added songcontroller, work on uploading a song 2019-08-18 16:44:59 -04:00
kdeng00 e9aa5f799c Added database configuration file 2019-08-18 16:15:47 -04:00
kdeng00 10b546d8b8 removed mysqlconnector c++ submodule. Linking issues, using the C API instead 2019-08-18 16:13:14 -04:00
kdeng00 d26c16aa69 database stuff 2019-08-18 11:57:08 -04:00
kdeng00 5230e69832 more changes 2019-08-17 18:53:50 -04:00
kdeng00 9ae9b08520 changed path of jwt-cpp submodule 2019-08-17 16:17:43 -04:00
kdeng00 0fc16daf86 Tying something out 2019-08-17 16:04:54 -04:00
kdeng00 533a8d81a9 Finished up #55 2019-08-13 21:05:11 -04:00
amazing-username 4d59b311e6 Removed TagLib# and RestSharp dependencies. Updated README.md 2019-08-13 14:38:34 +00:00
amazing-username a561ab0642 Fixed bug where user was not being authenticated 2019-08-13 14:08:03 +00:00
kdeng00 f0a50ba70a Implemented TokenManager #57 2019-08-13 00:11:04 -04:00
kdeng00 da8d4a9002 Implemented #56 2019-08-11 23:24:23 -04:00
kdeng00 51d40f270d Tricky implementing taglib's APIC extracting/saving feature, but I got it. Left some TODO's on where to pick up #56 2019-08-11 17:51:42 -04:00
kdeng00 023c467a9d Fixed issue where stock cover art was not correctly being copied 2019-08-11 16:10:18 -04:00
kdeng00 ea25480ad1 #56 2019-08-10 12:40:26 -04:00
kdeng00 5b19cdaa46 Working on #56 2019-08-10 01:03:52 -04:00
kdeng00 16f0c1aed0 Minor changes to metadata reading 2019-08-08 21:31:13 -04:00
kdeng00 ead71da802 Working on migrating metadata over to c++ 2019-08-08 18:40:15 -04:00
kdeng00 47723c7d94 Starting to switch Metadata portion to c++. Switching from TagLibSharp to Taglib (c++) 2019-08-06 22:51:20 -04:00
kdeng00 02bc671883 Code cleanup, removed some unused dependencies, adding more to C++ lib. #54 and #55 2019-08-05 23:47:43 -04:00
kdeng00 1531cad134 Handling song being moved on the c++ side #55 2019-08-04 17:08:49 -04:00
kdeng00 610d4fb08d Contining work on #55 2019-08-04 14:25:45 -04:00
amazing-username 15948c4783 Directories are created using C++ when a song is uploaded 2019-08-04 14:04:40 +00:00
kdeng00 2d984813ec Updated Entity Framework to 2.2.6, Removed PrintCredentials() Method call on login, working on #55 2019-08-03 14:26:18 -04:00
kdeng00 d80842e517 Changed song streaming to use only FileStream instead of FileStream and MemoryStream 2019-07-29 20:59:22 -04:00
amazing-username 2c3152a9a5 Added functionality to retrieve cover art records in json format 2019-07-29 01:07:16 +00:00
amazing-username 3948e25fc3 Incorrect method call for logging fixed 2019-07-20 01:47:16 +00:00
amazing-username a39c232c34 Added logging for cover art functionality 2019-07-17 20:15:07 -04:00
amazing-username 8ec7092272 Implemented Cover Art functionality #50 #52 2019-07-16 20:44:53 -04:00
amazing-username 84615472ef Cover art image gets deleted when the song has been deleted #50 2019-07-15 22:12:49 -04:00
amazing-username e4be56101a Added functionality to save the stock cover art to a song if the song does not contain a cover art #50 2019-07-14 22:40:49 -04:00
amazing-username 59895af3b4 Can download a cover art via the cover art's id. Just need to have a stock cover art for songs without any and update the documentation. #50 2019-07-13 16:04:39 -04:00
amazing-username 1004f6c93d Can successfully save the coverart record, now need to work on downloading the cover art #50 2019-07-13 10:13:15 -04:00
amazing-username 026a528a81 Cover art functionality added. Left TODO's on where to continue on. #50 2019-07-12 23:13:32 -04:00
amazing-username 226ca44206 Mover Cover Art work. #50 2019-07-11 23:15:45 -04:00
amazing-username 4940768d22 All the necessary functionality for the Cover Art repo added #51 2019-07-10 17:54:17 -04:00
amazing-username f7963237fd Added TODO's for checking if Cover art already exists. Added functionality in DirectoryManager to switch to the CoverArt path when explicitly request, otherwise defaults to the music root path. Added skeleton function for CoverArtRepository in the CoverArtRepository and SongManager 2019-07-09 21:03:52 -04:00
amazing-username 0ee1473639 Finished Cover art repository #51 2019-07-09 19:44:40 -04:00
amazing-username 2b59bfac32 Updates to the Cover art repository #51 2019-07-08 18:42:44 -04:00
amazing-username 0932be2f2b Added but did not complete the repository for cover art, updated migration script to create migration for CoverArt, and prepping for the cover art api 2019-07-07 15:02:38 -04:00
amazing-username 82686f5c33 Added cover art path to json files #53 2019-07-07 11:05:53 -04:00
amazing-username b5501e323f Added a cover art model. Better to do it now and not wait til later 2019-07-06 22:26:55 -04:00
amazing-username 089bd1191c Adding Cover art support #50 2019-07-05 20:37:38 -04:00
amazing-username 56fe805f80 Code cleanup and conforming to a coding covention 2019-07-04 17:19:40 -04:00
amazing-username ada8fa79d3 Cleaning up code convention inconsistencies 2019-07-04 15:57:43 -04:00
Kun Deng bc209c2363 Update README.md
#30
2019-06-23 13:11:55 -04:00
150 changed files with 7633 additions and 6592 deletions
+21
View File
@@ -0,0 +1,21 @@
[submodule "Libs/cpr"]
path = 3rdparty/cpr
url = https://github.com/whoshuu/cpr.git
[submodule "3rdparty/taglib"]
path = 3rdparty/taglib
url = https://github.com/taglib/taglib
[submodule "3rdparty/oatpp"]
path = 3rdparty/oatpp
url = https://github.com/oatpp/oatpp
[submodule "build/3rdparty/jwt-cpp"]
path = build/3rdparty/jwt-cpp
url = https://github.com/Thalhammer/jwt-cpp
[submodule "3rdparty/jwt-cpp"]
path = 3rdparty/jwt-cpp
url = https://github.com/Thalhammer/jwt-cpp
[submodule "3rdparty/ormpp"]
path = 3rdparty/ormpp
url = https://github.com/qicosmos/ormpp
[submodule "3rdparty/libbcrypt"]
path = 3rdparty/libbcrypt
url = https://github.com/rg3/libbcrypt
Vendored Submodule
+1
Submodule 3rdparty/cpr added at feebd2fd54
Vendored Submodule
+1
Submodule 3rdparty/jwt-cpp added at 27f32983fb
Vendored Submodule
+1
Submodule 3rdparty/libbcrypt added at 8aa32ad94e
Vendored Submodule
+1
Submodule 3rdparty/oatpp added at 5b4b313a0b
Vendored Submodule
+1
Submodule 3rdparty/taglib added at 79bc9ccf8e
-32
View File
@@ -1,32 +0,0 @@
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Icarus.Authorization;
namespace Icarus.Authorization.Handlers
{
public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context,
HasScopeRequirement requirement)
{
if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))
{
return Task.CompletedTask;
}
var scopes = context.User.FindFirst(c => c.Type == "scope" &&
c.Issuer == requirement.Issuer).Value.Split(' ');
if (scopes.Any(s => s == requirement.Scope))
{
context.Succeed(requirement);
}
return Task.CompletedTask;
}
}
}
-19
View File
@@ -1,19 +0,0 @@
using System;
using Microsoft.AspNetCore.Authorization;
namespace Icarus.Authorization
{
public class HasScopeRequirement : IAuthorizationRequirement
{
public string Issuer { get; }
public string Scope { get; }
public HasScopeRequirement(string scope, string issuer)
{
Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
}
}
}
+149
View File
@@ -0,0 +1,149 @@
cmake_minimum_required(VERSION 3.10)
project(icarus)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_STANDARD 17)
set(SOURCES
src/callback/StreamCallback.cpp
src/database/AlbumRepository.cpp
src/database/ArtistRepository.cpp
src/database/BaseRepository.cpp
src/database/CoverArtRepository.cpp
src/database/GenreRepository.cpp
src/database/SongRepository.cpp
src/database/UserRepository.cpp
src/database/YearRepository.cpp
src/dto/conversion/DtoConversions.cpp
src/Main.cpp
src/manager/AlbumManager.cpp
src/manager/ArtistManager.cpp
src/manager/CoverArtManager.cpp
src/manager/DirectoryManager.cpp
src/manager/GenreManager.cpp
src/manager/SongManager.cpp
src/manager/TokenManager.cpp
src/manager/UserManager.cpp
src/manager/YearManager.cpp
src/utility/ImageFile.cpp
src/utility/MetadataRetriever.cpp
src/utility/PasswordEncryption.cpp
src/verify/Initialization.cpp
)
set(HEADERS
include/callback/StreamCallback.h
include/component/AppComponent.hpp
include/controller/AlbumController.hpp
include/controller/ArtistController.hpp
include/controller/CoverArtController.hpp
include/controller/GenreController.hpp
include/controller/LoginController.hpp
include/controller/RegisterController.hpp
include/controller/SongController.hpp
include/controller/YearController.hpp
include/database/AlbumRepository.h
include/database/ArtistRepository.h
include/database/BaseRepository.h
include/database/CoverArtRepository.h
include/database/GenreRepository.h
include/database/SongRepository.h
include/database/UserRepository.h
include/database/YearRepository.h
include/dto/AlbumDto.hpp
include/dto/ArtistDto.hpp
include/dto/CoverArtDto.hpp
include/dto/GenreDto.hpp
include/dto/LoginResultDto.hpp
include/dto/SongDto.hpp
include/dto/YearDto.hpp
include/dto/conversion/DtoConversions.h
include/manager/AlbumManager.h
include/manager/ArtistManager.h
include/manager/CoverArtManager.h
include/manager/DirectoryManager.h
include/manager/GenreManager.h
include/manager/SongManager.h
include/manager/TokenManager.h
include/manager/UserManager.h
include/manager/YearManager.h
include/model/Models.h
include/utility/ImageFile.h
include/utility/MetadataRetriever.h
include/utility/PasswordEncryption.h
include/type/AlbumFilter.h
include/type/ArtistFilter.h
include/type/CoverFilter.h
include/type/GenreFilter.h
include/type/PathType.h
include/type/SaltFilter.h
include/type/Scopes.h
include/type/SongChanged.h
include/type/SongFilter.h
include/type/UserFilter.h
include/type/YearFilter.h
include/verify/Initialization.h
)
set (TAGLIB
${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/taglib/3rdparty
)
set (BCRYPTLIB
${CMAKE_SOURCE_DIR}/3rdparty/libbcrypt
)
set(TAGLIB_HEADERS
"${CMAKE_SOURCE_DIR}/build/3rdparty/taglib"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/ape"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/asf"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/dsdiff"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/dsf"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/flac"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/it"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/mod"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/mp4"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/mpc"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/mpeg"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/mpeg/id3v2"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/mpeg/id3v2/frames"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/ogg"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/riff"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/s3m"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/toolkit"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/trueaudio"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/wavpack"
"${CMAKE_SOURCE_DIR}/3rdparty/taglib/taglib/xm"
)
set(JWT_CPP_INCLUDE
${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/jwt-cpp/include
)
set (ORM_DIR
${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/ormpp
)
include(${CMAKE_BINARY_DIR}/conanbuildinfo.cmake)
conan_basic_setup()
find_library(BCRYPT bcrypt ${BCRYPTLIB})
include_directories(include ${CPR_INCLUDE_DIRS} ${TAGLIB} ${TAGLIB_HEADERS} ${BCRYPTLIB}/)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/cpr)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/taglib)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/oatpp)
#add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/3rdparty/libbcrypt)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/appsettings.json ${CMAKE_BINARY_DIR}/bin/appsettings.json COPYONLY)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/authcredentials.json ${CMAKE_BINARY_DIR}/bin/authcredentials.json COPYONLY)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/database.json ${CMAKE_BINARY_DIR}/bin/database.json COPYONLY)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/paths.json ${CMAKE_BINARY_DIR}/bin/paths.json COPYONLY)
configure_file(${CMAKE_CURRENT_SOURCE_DIR}/Images/Stock/CoverArt.png ${CMAKE_BINARY_DIR}/bin/CoverArt.png COPYONLY)
add_executable(icarus ${SOURCES} ${HEADERS})
target_include_directories(icarus PUBLIC ${JWT_CPP_INCLUDE})
target_link_libraries(icarus "-lstdc++fs" tag oatpp mysqlclient ${CONAN_LIBS} ${CPR_LIBRARIES} ${BCRYPT})
-28
View File
@@ -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
}
}
-28
View File
@@ -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
}
}
-13
View File
@@ -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
}
}
-205
View File
@@ -1,205 +0,0 @@
using System;
using System.IO;
using System.Linq;
using Microsoft.Extensions.Configuration;
using Icarus.Models;
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();
}
#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 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()
{
_rootSongDirectory = _config.GetValue<string>("RootMusicPath");
}
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
}
}
-28
View File
@@ -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
}
}
File diff suppressed because it is too large Load Diff
-141
View File
@@ -1,141 +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);
Console.WriteLine(tokenObject);
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");
Console.WriteLine(response.Content);
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
}
}
-28
View File
@@ -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
}
}
-292
View File
@@ -1,292 +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 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";
}
}
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,93 +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
}
}
-129
View File
@@ -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
}
}
-85
View File
@@ -1,85 +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
}
}
-85
View File
@@ -1,85 +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
}
}
-84
View File
@@ -1,84 +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
}
}
-89
View File
@@ -1,89 +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
}
}
View File
-71
View File
@@ -1,71 +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,65 +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
}
}
-133
View File
@@ -1,133 +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);
}
}
}
-149
View File
@@ -1,149 +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.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/data")]
[ApiController]
public class SongDataController : ControllerBase
{
#region Fields
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
[HttpGet("{id}")]
[Route("private-scoped")]
[Authorize("download:songs")]
public async Task<IActionResult> Get(int id)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
var songMetaData = context.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
{
SongRepository songRepository = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
AlbumRepository albumStoreContext = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
ArtistRepository artistStoreContext = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
GenreRepository genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
YearRepository yearStore = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
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,
albumStoreContext, artistStoreContext,
genreStore, yearStore);
}
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.LogError(msg, "An error occurred");
}
}
[HttpDelete("{id}")]
[Authorize("delete:songs")]
public IActionResult Delete(int id)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
AlbumRepository albumStore = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
ArtistRepository artistStore = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
GenreRepository genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
YearRepository yearStore = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
var songMetaData = new Song{ Id = id };
Console.WriteLine($"Id {songMetaData.Id}");
songMetaData = context.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, context, albumStore,
artistStore, genreStore, yearStore);
return Ok();
}
}
}
}
-67
View File
@@ -1,67 +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
}
}
-84
View File
@@ -1,84 +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
}
}
-27
View File
@@ -1,27 +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");
}
}
}
-27
View File
@@ -1,27 +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");
}
}
}
-27
View File
@@ -1,27 +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");
}
}
}
-68
View File
@@ -1,68 +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>()
.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);
}
}
}
-32
View File
@@ -1,32 +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);
}
}
}
-27
View File
@@ -1,27 +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");
}
}
}
-411
View File
@@ -1,411 +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
}
}
-370
View File
@@ -1,370 +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
}
}
-23
View File
@@ -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
}
}
-469
View File
@@ -1,469 +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
}
}
-326
View File
@@ -1,326 +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) VALUES(@Title, @AlbumTitle, " +
"@Artist, @Year, @Genre, @Duration, @Filename, @SongPath, " +
"@AlbumId, @ArtistId, @GenreId, @YearId)";
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.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())
});
}
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());
}
return song;
}
#endregion
}
}
-231
View File
@@ -1,231 +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
}
}
-381
View File
@@ -1,381 +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
}
}
-35
View File
@@ -1,35 +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" />
</ItemGroup>
</Project>
-9
View File
@@ -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>
-34
View File
@@ -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
-313
View File
@@ -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
Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File
-24
View File
@@ -1,24 +0,0 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class 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; }
}
}
-22
View File
@@ -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; }
}
}
-12
View File
@@ -1,12 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class BaseResult
{
[JsonProperty("message")]
public string Message { get; set; }
}
}
-22
View File
@@ -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; }
}
}
-20
View File
@@ -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; }
}
}
-14
View File
@@ -1,14 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class RegisterResult : BaseResult
{
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("successfully_registered")]
public bool SuccessfullyRegistered { get; set; }
}
}
-49
View File
@@ -1,49 +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; }
}
}
-12
View File
@@ -1,12 +0,0 @@
using System;
using System.Text;
namespace Icarus.Models
{
public class SongData
{
public int Id { get; set; }
public byte[] Data { get; set; }
public int SongId { get; set; }
}
}
-14
View File
@@ -1,14 +0,0 @@
using System;
using Newtonsoft.Json;
namespace Icarus.Models
{
public class SongResult
{
[JsonProperty("message")]
public string Message { get; set; }
[JsonProperty("song_title")]
public string SongTitle { get; set; }
}
}
-32
View File
@@ -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; }
}
}
-22
View File
@@ -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; }
}
}
-48
View File
@@ -1,48 +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() ;
}
}
-30
View File
@@ -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"
}
}
}
}
+66 -53
View File
@@ -1,6 +1,6 @@
# Icarus
Icarus is a music streaming API Server that interacts with [Mear](https://github.com/amazing-username/mear).
Icarus is a music streaming API Server, allowing access to stream your personal music collection
### Interfacing With Icarus
@@ -8,18 +8,21 @@ 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)
* Create your own client to interact with the API
## Built With
* 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)
* C++ >= C++17
* GCC >= 8.0
* [json](https://www.github.com/nlohmann/json)
* [cpr](https://www.github.com/whoshuu/cpr)
* [TagLib](https://github.com/taglib/taglib)
* [jwt-cpp](https://github.com/Thalhammer/jwt-cpp)
* [libbcrypt](https://github.com/rg3/libbcrypt)
* [oatpp](https://github.com/oatpp/oatpp)
![image](https://user-images.githubusercontent.com/14333136/56252069-28532d00-6084-11e9-896d-1a3c378014ef.png)
@@ -44,10 +47,10 @@ Create the API and enter an approrpiate name and identified. For the identified,
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"
},
"domain": "[domain].auth0.com",
"api_identifier": "https://[identifier]/api",
"client_id": "iamunique",
"client_secret": "Icankeepasecret"
```
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.
@@ -74,90 +77,100 @@ From the Application page, copy the client id and client secret. These values wi
<h1 align="center">
<img src="Images/Configuration/api_cred.png" width=100%>
</h1>
Enter the information in the corresponding appsettings json file
Enter the information in the corresponding ``authcredentials.json`` file
```Json
"Auth0": {
"ClientId":"",
"ClientSecret":""
},
{
"domain": "somedomain.auth0.com",
"api_identifier": "https://squawk/api"
"client_id": "clientidhere",
"client_secret": "illkeepyoumydirtylittlesecret"
}
```
### 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:
For the purposes of properly uploading, downloading, updating, deleting, and streaming songs the API filesystem paths must be configured. For that purpose you have to open the ``paths.json`` file. What is meant by this is that the `root_music_path` directory where all music will be stored must exist. The `cover_root_path`, `archive_root_path`, and `temp_root_path` paths must exist and be accessible. An example on a Linux system:
```Json
{
"RootMusicPath": "/home/dev/null/music/",
"TemporaryMusicPath": "/home/dev/null/music/temp/",
"ArchivePath": "/home/dev/null/music/archive/"
"root_music_path": "/dev/null/music/",
"temp_root_path": "/dev/null/music/temp/",
"cover_root_path": "/dev/null/music/coverArt/",
"archive_root_path": "/dev/null/music/archive/"
}
```
* 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
* `root_music_path` - Where music will be stored in the following convention: *`Artist/Album/Songs`*
* `temp_music_path` - 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 `root_music_path`
* `cover_root_path` - Where cover art of music will be saved to.
* `archive_root_path` - 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.
**Note**: The `temp_root_path`, `cover_root_path`, or `archive_root_path` does not have to be located in the same parent directory as `root_music_path`. 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:
In order for Database functionality to be operable, there must be a valid connection string and MySQL credentials with appropriate permissions. **At the moment there is only support for MySQL**. Edit the database.json file accordingly. An example of the fields to change are below:
```Json
{
"ConnectionStrings": {
"DefaultConnection": "Server=localhost;Database=my_db;Uid=admin;Pwd=toughpassword;"
}
"server": "localhost",
"database": "my_db",
"username": "admin",
"password": "toughpassword"
}
```
* Server - The address or domain name of the MySQL server
* Database - The database name
* Uid - Username
* Password - Self-explanatory
* server - The address or domain name of the MySQL server
* database - The database name
* username - 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
### Database
Prior to starting the API, the Migrations must be applied. There are 6 tables with migrations being applied and thy are:
* Users
Prior to starting the API, the database must be created. The following tables are required:
* User
* Salt
* Song
* Album
* Artist
* Year
* Genre
* CoverArt
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:
There is a MySQL script to create these tables, it can be found in the [Scripts/MySQL/](https://github.com/amazing-username/Icarus/blob/master/Scripts/MySQL/create_database.sql) directory. Just merely execute:
```shell
scripts/Migrations/Linux/AddUpdate.sh
mysql -u dblikedecibel -p < Scripts/MySQL/create_database.sql
```
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.
From this point the database has been successfully created. Metadata and song filesystem locations can be saved.
## Building and Running
```
git clone --recursive https://github.com/kdeng00/icarus
cd 3rdparty/libbcrypt/
make
cp bcrypt.a libbcrypt.a
cp bcrypt.o libbcrypt.o
cd ../..
mkdir build
cd build
conan install ..
cmake .. -DCMAKE_BUILD_TYPE=RELEASE -DUSE_SYSTEM_CURL=ON -DBUILD_CPR_TESTS=OFF -DOATPP_BUILD_TESTS=OFF
make
bin/icarus
```
Runs the server on localhost port 5002
## 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
Currently under development. No version has been released
## 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
+3
View File
@@ -11,6 +11,8 @@ 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"
@@ -20,4 +22,5 @@ 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
+86
View File
@@ -0,0 +1,86 @@
CREATE DATABASE Icarus;
USE Icarus;
CREATE TABLE CoverArt (
CoverArtId INT NOT NULL AUTO_INCREMENT,
SongTitle TEXT NOT NULL,
ImagePath TEXT NOT NULL,
PRIMARY KEY (CoverArtId)
);
CREATE TABLE Album (
AlbumId INT NOT NULL AUTO_INCREMENT,
Title TEXT NOT NULL,
Year INT NOT NULL,
PRIMARY KEY (AlbumId)
);
CREATE TABLE Artist (
ArtistId INT NOT NULL AUTO_INCREMENT,
Artist TEXT NOT NULL,
PRIMARY KEY (ArtistId)
);
CREATE TABLE Genre (
GenreId INT NOT NULL AUTO_INCREMENT,
Category TEXT NOT NULL,
PRIMARY KEY (GenreId)
);
CREATE TABLE Year (
YearId INT NOT NULL AUTO_INCREMENT,
Year INT NOT NULL,
PRIMARY KEY (YearId)
);
CREATE TABLE Song (
SongId INT NOT NULL AUTO_INCREMENT,
Title TEXT NOT NULL,
Artist TEXT NOT NULL,
Album TEXT NOT NULL,
Genre TEXT NOT NULL,
Year INT NOT NULL,
Duration INT NOT NULL,
Track INT NOT NULL,
Disc INT NOT NULL,
SongPath TEXT NOT NULL,
CoverArtId INT NOT NULL,
ArtistId INT NOT NULL,
AlbumId INT NOT NULL,
GenreId INT NOT NULL,
YearId INT NOT NULL,
PRIMARY KEY (SongId),
CONSTRAINT FK_CoverArtId FOREIGN KEY (CoverArtId) REFERENCES CoverArt (CoverArtId),
CONSTRAINT FK_ArtistId FOREIGN KEY (ArtistId) REFERENCES Artist (ArtistId),
CONSTRAINT FK_AlbumId FOREIGN KEY (AlbumId) REFERENCES Album (AlbumId),
CONSTRAINT FK_GenreId FOREIGN KEY (GenreId) REFERENCES Genre (GenreId),
CONSTRAINT FK_YearId FOREIGN KEY (YearId) REFERENCES Year (YearId)
);
CREATE TABLE User (
UserId INT NOT NULL AUTO_INCREMENT,
Firstname TEXT NOT NULL,
Lastname TEXT NOT NULL,
Email TEXT NOT NULL,
Phone TEXT NOT NULL,
Username TEXT NOT NULL,
Password TEXT NOT NULL,
PRIMARY KEY (UserId)
);
CREATE TABLE Salt (
SaltId INT NOT NULL AUTO_INCREMENT,
Salt TEXT NOT NULL,
UserId INT NOT NULL,
PRIMARY KEY (SaltId),
CONSTRAINT FK_UserId FOREIGN KEY (UserId) REFERENCES User (UserId)
);
+6 -3
View File
@@ -1,3 +1,6 @@
delete from Song where Id>0;
delete from Album where AlbumId>0;
delete from Artist where ArtistId>0;
delete from Song;
delete from Album;
delete from Artist;
delete from Genre;
delete from Year;
delete from CoverArt;
-168
View File
@@ -1,168 +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("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(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));
}
// This method gets 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, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
-21
View File
@@ -1,21 +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/"
}
+4 -3
View File
@@ -9,13 +9,14 @@
"Auth0": {
"Domain": "[domain].auth0.com",
"ApiIdentifier": "https://[identifier]/api",
"ClientId":"",
"ClientSecret":""
"ClientId": "",
"ClientSecret": ""
},
"ConnectionStrings": {
"DefaultConnection": "Server=;Database=;Uid=;Pwd=;"
},
"RootMusicPath": "/music/path/",
"TemporaryMusicPath": "/music/temp/path/",
"ArchivePath": "/archive/path/"
"ArchivePath": "/archive/path/",
"CoverArtPath": "/cover/art/path/"
}
+6
View File
@@ -0,0 +1,6 @@
{
"domain": "[domain].auth0.com",
"api_identifier": "https://[identifier]/api",
"client_id": "dfdfdfdf",
"client_secret": "dfdfdfdf"
}
+5
View File
@@ -0,0 +1,5 @@
[requires]
jsonformoderncpp/3.7.0@vthiery/stable
[generators]
cmake
+7
View File
@@ -0,0 +1,7 @@
{
"server": "localhost",
"database": "Icarus",
"username": "icarus-admin",
"password": "dreamofpeace"
}
+26
View File
@@ -0,0 +1,26 @@
#ifndef STREAMCALLBACK_H_
#define STREAMCALLBACK_H_
#include <string>
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/web/protocol/http/outgoing/ChunkedBody.hpp"
namespace callback {
class StreamCallback : public oatpp::data::stream::ReadCallback
{
public:
StreamCallback();
StreamCallback(const std::string&);
oatpp::data::v_io_size read(void*, oatpp::data::v_io_size);
private:
std::string m_songPath;
long m_bytesRead;
long m_counter;
long m_fileSize;
};
}
#endif
+37
View File
@@ -0,0 +1,37 @@
#ifndef APPCOMPONENT_H_
#define APPCOMPONENT_H_
#include <memory>
#include "oatpp/core/macro/component.hpp"
#include "oatpp/network/server/SimpleTCPConnectionProvider.hpp"
#include "oatpp/parser/json/mapping/ObjectMapper.hpp"
#include "oatpp/web/server/HttpConnectionHandler.hpp"
namespace component {
class AppComponent
{
public:
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([] {
return oatpp::network::server::SimpleTCPConnectionProvider::createShared(5002);
}());
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] {
return oatpp::web::server::HttpRouter::createShared();
}());
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::server::ConnectionHandler>, serverConnectionHandler)([] {
OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router);
return oatpp::web::server::HttpConnectionHandler::createShared(router);
}());
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, apiObjectMapper)([] {
return oatpp::parser::json::mapping::ObjectMapper::createShared();
}());
private:
};
}
#endif
+102
View File
@@ -0,0 +1,102 @@
#ifndef ALBUMCONTROLLER_H_
#define ALBUMCONTROLLER_H_
#include <filesystem>
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <memory>
#include <vector>
#include "oatpp/core/data/stream/ChunkedBuffer.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/mime/multipart/InMemoryPartReader.hpp"
#include "oatpp/web/mime/multipart/Reader.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "database/AlbumRepository.h"
#include "dto/AlbumDto.hpp"
#include "manager/AlbumManager.h"
#include "manager/TokenManager.h"
#include "model/Models.h"
#include "type/Scopes.h"
#include "type/AlbumFilter.h"
namespace fs = std::filesystem;
namespace controller {
class AlbumController : public oatpp::web::server::api::ApiController
{
public:
AlbumController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
AlbumController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all album records in json format
ENDPOINT("GET", "/api/v1/album", albumRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveAlbum), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving album" << std::endl;
database::AlbumRepository albRepo(m_bConf);
auto albsDb = albRepo.retrieveRecords();
auto albums = oatpp::data::mapping::type::List<dto::AlbumDto::ObjectWrapper>::createShared();
for (auto& albDb : albsDb) {
auto alb = dto::AlbumDto::createShared();
alb->id = albDb.id;
alb->title = albDb.title.c_str();
alb->year = albDb.year;
albums->pushBack(alb);
}
return createDtoResponse(Status::CODE_200, albums);
}
// endpoint for retrieving single album record by the album id in json format
ENDPOINT("GET", "/api/v1/album/{id}", albumRecord,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveAlbum), Status::CODE_403, "Not allowed");
database::AlbumRepository albRepo(m_bConf);
model::Album albDb(id);
OATPP_ASSERT_HTTP(albRepo.doesAlbumExists(albDb, type::AlbumFilter::id) , Status::CODE_403, "album does not exist");
std::cout << "album exists" << std::endl;
albDb = albRepo.retrieveRecord(albDb, type::AlbumFilter::id);
auto album = dto::AlbumDto::createShared();
album->id = albDb.id;
album->title = albDb.title.c_str();
album->year = albDb.year;
return createDtoResponse(Status::CODE_200, album);
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::string m_exe_path;
model::BinaryPath m_bConf;
};
}
#endif
+100
View File
@@ -0,0 +1,100 @@
#ifndef ARTISTCONTROLLER_H_
#define ARTISTCONTROLLER_H_
#include <filesystem>
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <memory>
#include <vector>
#include "oatpp/core/data/stream/ChunkedBuffer.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/mime/multipart/InMemoryPartReader.hpp"
#include "oatpp/web/mime/multipart/Reader.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "database/ArtistRepository.h"
#include "dto/ArtistDto.hpp"
#include "manager/ArtistManager.h"
#include "manager/TokenManager.h"
#include "model/Models.h"
#include "type/Scopes.h"
#include "type/ArtistFilter.h"
namespace fs = std::filesystem;
namespace controller {
class ArtistController : public oatpp::web::server::api::ApiController
{
public:
ArtistController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
ArtistController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all artist records in json format
ENDPOINT("GET", "/api/v1/artist", artistRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveArtist), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving artist" << std::endl;
database::ArtistRepository artRepo(m_bConf);
auto artsDb = artRepo.retrieveRecords();
auto artists = oatpp::data::mapping::type::List<dto::ArtistDto::ObjectWrapper>::createShared();
for (auto& artDb : artsDb) {
auto art = dto::ArtistDto::createShared();
art->id = artDb.id;
art->artist = artDb.artist.c_str();
artists->pushBack(art);
}
return createDtoResponse(Status::CODE_200, artists);
}
// endpoint for retrieving single artist record by the artist id in json format
ENDPOINT("GET", "/api/v1/artist/{id}", artistRecord,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveArtist), Status::CODE_403, "Not allowed");
database::ArtistRepository artRepo(m_bConf);
model::Artist artDb(id);
OATPP_ASSERT_HTTP(artRepo.doesArtistExist(artDb, type::ArtistFilter::id) , Status::CODE_403, "artist does not exist");
std::cout << "artist exist" << std::endl;
artDb = artRepo.retrieveRecord(artDb, type::ArtistFilter::id);
auto artist = dto::ArtistDto::createShared();
artist->id = artDb.id;
artist->artist = artDb.artist.c_str();
return createDtoResponse(Status::CODE_200, artist);
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::string m_exe_path;
model::BinaryPath m_bConf;
};
}
#endif
+121
View File
@@ -0,0 +1,121 @@
#ifndef COVERARTCONTROLLER_H_
#define COVERARTCONTROLLER_H_
#include <filesystem>
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <memory>
#include <vector>
#include "oatpp/core/data/stream/ChunkedBuffer.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/mime/multipart/InMemoryPartReader.hpp"
#include "oatpp/web/mime/multipart/Reader.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "database/CoverArtRepository.h"
#include "dto/CoverArtDto.hpp"
#include "manager/CoverArtManager.h"
#include "model/Models.h"
#include "type/Scopes.h"
#include "type/CoverFilter.h"
namespace fs = std::filesystem;
namespace controller {
class CoverArtController : public oatpp::web::server::api::ApiController
{
public:
CoverArtController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
CoverArtController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all cover art records in json format
ENDPOINT("GET", "/api/v1/coverart", coverArtRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving cover art" << std::endl;
database::CoverArtRepository covRepo(m_bConf);
auto covsDb = covRepo.retrieveRecords();
auto coverArts = oatpp::data::mapping::type::List<dto::CoverArtDto::ObjectWrapper>::createShared();
for (auto& covDb : covsDb) {
auto cov = dto::CoverArtDto::createShared();
cov->id = covDb.id;
cov->songTitle = covDb.songTitle.c_str();
coverArts->pushBack(cov);
}
return createDtoResponse(Status::CODE_200, coverArts);
}
// endpoint for retrieving single cover art record by the cover art id in json format
ENDPOINT("GET", "/api/v1/coverart/{id}", coverArtRecord,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed");
database::CoverArtRepository covRepo(m_bConf);
model::Cover covDb;
covDb.id = id;
OATPP_ASSERT_HTTP(covRepo.doesCoverArtExist(covDb, type::CoverFilter::id) , Status::CODE_403, "song does not exist");
std::cout << "cover art exists" << std::endl;
covDb = covRepo.retrieveRecord(covDb, type::CoverFilter::id);
auto coverArt = dto::CoverArtDto::createShared();
coverArt->id = covDb.id;
coverArt->songTitle = covDb.songTitle.c_str();
return createDtoResponse(Status::CODE_200, coverArt);
}
ENDPOINT("GET", "/api/v1/coverart/download/{id}", downloadCoverArt,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed");
database::CoverArtRepository covRepo(m_bConf);
model::Cover covDb;
covDb.id = id;
covDb = covRepo.retrieveRecord(covDb, type::CoverFilter::id);
auto rawCover = oatpp::base::StrBuffer::loadFromFile(covDb.imagePath.c_str());
auto response = createResponse(Status::CODE_200, rawCover);
response->putHeader(Header::CONTENT_TYPE, "image/*");
return response;
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::string m_exe_path;
model::BinaryPath m_bConf;
};
}
#endif
+100
View File
@@ -0,0 +1,100 @@
#ifndef GENRECONTROLLER_H_
#define GENRECONTROLLER_H_
#include <filesystem>
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <memory>
#include <vector>
#include "oatpp/core/data/stream/ChunkedBuffer.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/mime/multipart/InMemoryPartReader.hpp"
#include "oatpp/web/mime/multipart/Reader.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "database/GenreRepository.h"
#include "dto/GenreDto.hpp"
#include "manager/GenreManager.h"
#include "manager/YearManager.h"
#include "model/Models.h"
#include "type/Scopes.h"
#include "type/GenreFilter.h"
namespace fs = std::filesystem;
namespace controller {
class GenreController : public oatpp::web::server::api::ApiController
{
public:
GenreController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
GenreController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all genre records in json format
ENDPOINT("GET", "/api/v1/genre", genreRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveGenre), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving genre" << std::endl;
database::GenreRepository gnrRepo(m_bConf);
auto gnrsDb = gnrRepo.retrieveRecords();
auto genres = oatpp::data::mapping::type::List<dto::GenreDto::ObjectWrapper>::createShared();
for (auto& gnrDb : gnrsDb) {
auto gnr = dto::GenreDto::createShared();
gnr->id = gnrDb.id;
gnr->category = gnrDb.category.c_str();
genres->pushBack(gnr);
}
return createDtoResponse(Status::CODE_200, genres);
}
// endpoint for retrieving single genre record by the genre id in json format
ENDPOINT("GET", "/api/v1/genre/{id}", genreRecord,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveGenre), Status::CODE_403, "Not allowed");
database::GenreRepository gnrRepo(m_bConf);
model::Genre gnrDb(id);
OATPP_ASSERT_HTTP(gnrRepo.doesGenreExist(gnrDb, type::GenreFilter::id) , Status::CODE_403, "genre does not exist");
std::cout << "genre exist" << std::endl;
gnrDb = gnrRepo.retrieveRecord(gnrDb, type::GenreFilter::id);
auto genre = dto::GenreDto::createShared();
genre->id = gnrDb.id;
genre->category= gnrDb.category.c_str();
return createDtoResponse(Status::CODE_200, genre);
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::string m_exe_path;
model::BinaryPath m_bConf;
};
}
#endif
+61
View File
@@ -0,0 +1,61 @@
#ifndef LOGINCONTROLLER_H_
#define LOGINCONTROLLER_H_
#include <iostream>
#include <string>
#include <memory>
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "dto/LoginResultDto.hpp"
#include "dto/conversion/DtoConversions.h"
#include "manager/TokenManager.h"
#include "manager/UserManager.h"
#include "model/Models.h"
namespace controller {
class LoginController : public oatpp::web::server::api::ApiController {
public:
LoginController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), exe_path(p)
{ }
LoginController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
:oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
ENDPOINT("POST", "/api/v1/login", data, BODY_DTO(dto::UserDto::ObjectWrapper, usr)) {
OATPP_LOGI("icarus", "logging in");
manager::UserManager usrMgr(m_bConf);
auto user = dto::conversion::DtoConversions::toUser(usr);
if (!usrMgr.doesUserExist(user) || !usrMgr.validatePassword(user)) {
auto logRes = dto::LoginResultDto::createShared();
logRes->message = "invalid credentials";
std::cout << "user does not exist" << std::endl;
return createDtoResponse(Status::CODE_401, logRes);
}
std::cout << "user exists" << std::endl;
manager::TokenManager tok;
auto token = tok.retrieveToken(m_bConf);
auto logRes = dto::conversion::DtoConversions::toLoginResultDto(user, token);
logRes->message = "Successful";
return createDtoResponse(Status::CODE_200, logRes);
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::string exe_path;
model::BinaryPath m_bConf;
};
}
#endif
+41
View File
@@ -0,0 +1,41 @@
#ifndef REGISTERCONTROLLER_H_
#define REGISTERCONTROLLER_H_
#include <iostream>
#include <memory>
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "dto/LoginResultDto.hpp"
#include "dto/conversion/DtoConversions.h"
#include "manager/UserManager.h"
#include "model/Models.h"
namespace controller {
class RegisterController : public oatpp::web::server::api::ApiController {
public:
RegisterController(const model::BinaryPath& bConf,
OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) :
oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
#include OATPP_CODEGEN_BEGIN(ApiController)
ENDPOINT("POST", "api/v1/register", registerUser,
BODY_DTO(dto::UserDto::ObjectWrapper, usr)) {
manager::UserManager usrMgr(m_bConf);
auto user = dto::conversion::DtoConversions::toUser(usr);
auto res = usrMgr.registerUser(user);
auto registerResult = dto::conversion::DtoConversions::toRegisterResultDto(res);
return createDtoResponse(Status::CODE_200, registerResult);
}
#include OATPP_CODEGEN_END(ApiController)
private:
model::BinaryPath m_bConf;
};
}
#endif
+240
View File
@@ -0,0 +1,240 @@
#ifndef SONGCONTROLLER_H_
#define SONGCONTROLLER_H_
#include <filesystem>
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <memory>
#include <vector>
#include "oatpp/core/data/stream/ChunkedBuffer.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/mime/multipart/InMemoryPartReader.hpp"
#include "oatpp/web/mime/multipart/Reader.hpp"
#include "oatpp/web/protocol/http/outgoing/ChunkedBody.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "callback/StreamCallback.h"
#include "database/SongRepository.h"
#include "dto/SongDto.hpp"
#include "dto/conversion/DtoConversions.h"
#include "manager/SongManager.h"
#include "manager/TokenManager.h"
#include "model/Models.h"
#include "type/Scopes.h"
#include "type/SongFilter.h"
namespace fs = std::filesystem;
namespace controller {
class SongController : public oatpp::web::server::api::ApiController {
public:
SongController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
SongController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for uploading a song
ENDPOINT("POST", "/api/v1/song/data", songUpload,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::upload), Status::CODE_403, "Not allowed");
auto mp = std::make_shared<oatpp::web::mime::multipart::Multipart>(request->getHeaders());
oatpp::web::mime::multipart::Reader mp_reader(mp.get());
mp_reader.setPartReader("file", oatpp::web::mime::multipart::createInMemoryPartReader(m_dataSize));
request->transferBody(&mp_reader);
auto file = mp->getNamedPart("file");
OATPP_ASSERT_HTTP(file, Status::CODE_400, "file is null");
auto buff = std::unique_ptr<char>(new char[file->getKnownSize()]);
auto buffSize = file->getInputStream()->read(buff.get(), file->getKnownSize());
std::vector<unsigned char> data(buff.get(), buff.get() + buffSize);
model::Song sng;
sng.data = std::move(data);
manager::SongManager songMgr(m_bConf);
songMgr.saveSong(sng);
auto songDto = dto::conversion::DtoConversions::toSongDto(sng);
return createDtoResponse(Status::CODE_200, songDto);
}
// endpoint for retrieving all song records in json format
ENDPOINT("GET", "/api/v1/song", songRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveSong), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving songs" << std::endl;
database::SongRepository songRepo(m_bConf);
auto songsDb = songRepo.retrieveRecords();
auto songs = oatpp::data::mapping::type::List<dto::SongDto::ObjectWrapper>::createShared();
std::cout << "creating object to send" << std::endl;
for (auto& songDb : songsDb) {
auto song = dto::conversion::DtoConversions::toSongDto(songDb);
songs->pushBack(song);
}
return createDtoResponse(Status::CODE_200, songs);
}
// endpoint for retrieving song record by the song id in json format
ENDPOINT("GET", "/api/v1/song/{id}", songRecord,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveSong), Status::CODE_403, "Not allowed");
database::SongRepository songRepo(m_bConf);
model::Song songDb(id);
if (!songRepo.doesSongExist(songDb, type::SongFilter::id)) {
return songDoesNotExist();
}
std::cout << "song exists" << std::endl;
songDb = songRepo.retrieveRecord(songDb, type::SongFilter::id);
auto song = dto::conversion::DtoConversions::toSongDto(songDb);
return createDtoResponse(Status::CODE_200, song);
}
ENDPOINT("GET", "/api/v1/song/data/{id}", downloadSong,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::download), Status::CODE_403, "Not allowed");
database::SongRepository songRepo(m_bConf);
model::Song songDb(id);
if (!songRepo.doesSongExist(songDb, type::SongFilter::id)) {
return songDoesNotExist();
}
songDb = songRepo.retrieveRecord(songDb, type::SongFilter::id);
auto rawSong = oatpp::base::StrBuffer::loadFromFile(songDb.songPath.c_str());
auto response = createResponse(Status::CODE_200, rawSong);
response->putHeader(Header::CONTENT_TYPE, "audio/mpeg");
return response;
}
ENDPOINT("UPDATE", "/api/v1/song/{id}", songUpdate,
REQUEST(std::shared_ptr<IncomingRequest>, request),
BODY_DTO(dto::SongDto::ObjectWrapper, songDto), PATH(Int32, id)) {
songDto->id = id;
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::updateSong), Status::CODE_403, "Not allowed");
auto updatedSong = dto::conversion::DtoConversions::toSong(songDto);
manager::SongManager songMgr(m_bConf);
auto result = songMgr.updateSong(updatedSong);
if (!result) {
return songDoesNotExist();
}
return createResponse(Status::CODE_200, "OK");
}
// endpoint to delete a song
ENDPOINT("DELETE", "api/v1/song/data/{id}", songDelete,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::deleteSong), Status::CODE_403, "Not allowed");
model::Song song(id);
manager::SongManager sngMgr(m_bConf);
auto result = sngMgr.deleteSong(song);
if (!result) {
return songDoesNotExist();
}
return createResponse(Status::CODE_200, "OK");
}
// endpoint for streaming a song
ENDPOINT("GET", "/api/v1/song/stream/{id}", streamSong,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::stream), Status::CODE_403, "Not allowed");
database::SongRepository songRepo(m_bConf);
model::Song songDb(id);
if (!songRepo.doesSongExist(songDb, type::SongFilter::id)) {
return songDoesNotExist();
}
songDb = songRepo.retrieveRecord(songDb, type::SongFilter::id);
oatpp::data::v_io_size dSize = 1024;
auto db = std::make_shared<oatpp::web::protocol::http::outgoing::ChunkedBody>(
std::make_shared<callback::StreamCallback>(songDb.songPath), nullptr, dSize);
auto response = OutgoingResponse::createShared(Status::CODE_200, db);
response->putHeader(Header::CONNECTION, Header::Value::CONNECTION_KEEP_ALIVE);
response->putHeader(Header::CONTENT_TYPE, "audio/mpeg");
return response;
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>
songDoesNotExist() {
return createResponse(Status::CODE_404, "Song not found");
}
std::string m_exe_path;
model::BinaryPath m_bConf;
const long m_dataSize = std::numeric_limits<long long int>::max();
};
}
#endif
+99
View File
@@ -0,0 +1,99 @@
#ifndef YEARCONTROLLER_H_
#define YEARCONTROLLER_H_
#include <filesystem>
#include <iostream>
#include <fstream>
#include <limits>
#include <string>
#include <memory>
#include <vector>
#include "oatpp/core/data/stream/ChunkedBuffer.hpp"
#include "oatpp/core/data/stream/FileStream.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "oatpp/core/macro/component.hpp"
#include "oatpp/web/mime/multipart/InMemoryPartReader.hpp"
#include "oatpp/web/mime/multipart/Reader.hpp"
#include "oatpp/web/server/api/ApiController.hpp"
#include "database/YearRepository.h"
#include "dto/YearDto.hpp"
#include "manager/YearManager.h"
#include "model/Models.h"
#include "type/Scopes.h"
#include "type/YearFilter.h"
namespace fs = std::filesystem;
namespace controller {
class YearController : public oatpp::web::server::api::ApiController
{
public:
YearController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
YearController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all year records in json format
ENDPOINT("GET", "/api/v1/year", yearRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request))
{
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveYear), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving year" << std::endl;
database::YearRepository yrRepo(m_bConf);
auto yrsDb = yrRepo.retrieveRecords();
auto yearRecs = oatpp::data::mapping::type::List<dto::YearDto::ObjectWrapper>::createShared();
for (auto& yrDb : yrsDb) {
auto yr = dto::YearDto::createShared();
yr->id = yrDb.id;
yr->year = yrDb.year;
yearRecs->pushBack(yr);
}
return createDtoResponse(Status::CODE_200, yearRecs);
}
// endpoint for retrieving single year record by the year id in json format
ENDPOINT("GET", "/api/v1/year/{id}", yearRecord,
REQUEST(std::shared_ptr<IncomingRequest>, request), PATH(Int32, id)) {
auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str();
manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveYear), Status::CODE_403, "Not allowed");
database::YearRepository yrRepo(m_bConf);
model::Year yrDb(id);
OATPP_ASSERT_HTTP(yrRepo.doesYearExist(yrDb, type::YearFilter::id) , Status::CODE_403, "year does not exist");
std::cout << "year exist" << std::endl;
yrDb = yrRepo.retrieveRecord(yrDb, type::YearFilter::id);
auto year = dto::YearDto::createShared();
year->id = yrDb.id;
year->year= yrDb.year;
return createDtoResponse(Status::CODE_200, year);
}
#include OATPP_CODEGEN_END(ApiController)
private:
std::string m_exe_path;
model::BinaryPath m_bConf;
};
}
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef ALBUMREPOSITORY_H_
#define ALBUMREPOSITORY_H_
#include <utility>
#include <vector>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/AlbumFilter.h"
namespace database
{
class AlbumRepository : public BaseRepository
{
public:
AlbumRepository(const model::BinaryPath&);
std::vector<model::Album> retrieveRecords();
std::pair<model::Album, int> retrieveRecordWithSongCount(model::Album&, type::AlbumFilter);
model::Album retrieveRecord(model::Album&, type::AlbumFilter);
bool doesAlbumExists(const model::Album&, type::AlbumFilter);
void saveAlbum(const model::Album&);
void deleteAlbum(const model::Album&, type::AlbumFilter);
private:
std::vector<model::Album> parseRecords(MYSQL_STMT*);
std::pair<model::Album, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: after parseRecord(MYSQL_STMT*) is implemented remove
// parseRecord(MYSQL_RES*)
model::Album parseRecord(MYSQL_RES*);
model::Album parseRecord(MYSQL_STMT*);
};
}
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef ARTISTREPOSITORY_H_
#define ARTISTREPOSITORY_H_
#include <utility>
#include <vector>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/ArtistFilter.h"
namespace database
{
class ArtistRepository : public BaseRepository
{
public:
ArtistRepository(const model::BinaryPath&);
std::vector<model::Artist> retrieveRecords();
std::pair<model::Artist, int> retrieveRecordWithSongCount(model::Artist&, type::ArtistFilter);
model::Artist retrieveRecord(model::Artist&, type::ArtistFilter);
bool doesArtistExist(const model::Artist&, type::ArtistFilter);
void saveRecord(const model::Artist&);
void deleteArtist(const model::Artist&, type::ArtistFilter);
private:
std::vector<model::Artist> parseRecords(MYSQL_STMT*);
std::pair<model::Artist, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented
// remove parseRecord(MYSQL_RES*)
model::Artist parseRecord(MYSQL_RES*);
model::Artist parseRecord(MYSQL_STMT*);
};
}
#endif
+36
View File
@@ -0,0 +1,36 @@
#ifndef BASE_REPOSITORY_H_
#define BASE_REPOSITORY_H_
#include <string>
#include <mysql/mysql.h>
#include "model/Models.h"
namespace database
{
class BaseRepository
{
public:
BaseRepository();
BaseRepository(const std::string&);
BaseRepository(const model::BinaryPath&);
bool testConnection();
protected:
MYSQL* setupMysqlConnection();
MYSQL* setupMysqlConnection(model::DatabaseConnection);
MYSQL_RES* performMysqlQuery(MYSQL*, const std::string&);
model::DatabaseConnection details;
private:
void intitalizeDetails();
void initializeDetails(const model::BinaryPath&);
std::string path;
model::BinaryPath m_binConf;
};
}
#endif
+39
View File
@@ -0,0 +1,39 @@
#ifndef COVERARTREPOSITORY_H_
#define COVERARTREPOSITORY_H_
#include <vector>
#include <mysql/mysql.h>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/CoverFilter.h"
namespace database
{
class CoverArtRepository : public BaseRepository
{
public:
CoverArtRepository(const std::string&);
CoverArtRepository(const model::BinaryPath&);
std::vector<model::Cover> retrieveRecords();
model::Cover retrieveRecord(model::Cover&, type::CoverFilter);
bool doesCoverArtExist(const model::Cover&, type::CoverFilter);
void deleteRecord(const model::Cover&);
void saveRecord(const model::Cover&);
void updateRecord(const model::Cover&);
private:
std::vector<model::Cover> parseRecords(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented
// remove parseRecord(MYSQL_RES*)
model::Cover parseRecord(MYSQL_RES*);
model::Cover parseRecord(MYSQL_STMT*);
};
}
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef GENREREPOSITORY_H_
#define GENREREPOSITORY_H_
#include <utility>
#include <vector>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/GenreFilter.h"
namespace database
{
class GenreRepository : public BaseRepository
{
public:
GenreRepository(const model::BinaryPath&);
std::vector<model::Genre> retrieveRecords();
std::pair<model::Genre, int> retrieveRecordWithSongCount(model::Genre&, type::GenreFilter);
model::Genre retrieveRecord(model::Genre&, type::GenreFilter);
bool doesGenreExist(const model::Genre&, type::GenreFilter);
void saveRecord(const model::Genre&);
void deleteRecord(const model::Genre&, type::GenreFilter);
private:
std::vector<model::Genre> parseRecords(MYSQL_STMT*);
std::pair<model::Genre, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented
// remove parseRecord(MYSQL_RES*)
model::Genre parseRecord(MYSQL_RES*);
model::Genre parseRecord(MYSQL_STMT*);
};
}
#endif
+39
View File
@@ -0,0 +1,39 @@
#ifndef SONGREPOSITORY_H_
#define SONGREPOSITORY_H_
#include <memory>
#include <vector>
#include <mysql/mysql.h>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/SongFilter.h"
namespace database
{
class SongRepository : public BaseRepository
{
public:
SongRepository(const std::string&);
SongRepository(const model::BinaryPath&);
std::vector<model::Song> retrieveRecords();
model::Song retrieveRecord(model::Song&, type::SongFilter);
bool doesSongExist(const model::Song&, type::SongFilter);
bool deleteRecord(const model::Song&);
void saveRecord(const model::Song&);
void updateRecord(const model::Song&);
private:
std::vector<model::Song> parseRecords(MYSQL_RES*); // TODO: to be removed
std::vector<model::Song> parseRecords(MYSQL_STMT*);
model::Song parseRecord(MYSQL_RES*); // TODO: to be removed
model::Song parseRecord(MYSQL_STMT*);
};
}
#endif
+58
View File
@@ -0,0 +1,58 @@
#ifndef USERREPOSITORY_H_
#define USERREPOSITORY_H_
#include <iostream>
#include <memory>
#include <tuple>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/SaltFilter.h"
#include "type/UserFilter.h"
namespace database {
class UserRepository : BaseRepository {
public:
UserRepository(const model::BinaryPath&);
model::User retrieveUserRecord(model::User&, type::UserFilter);
model::PassSec retrieverUserSaltRecord(model::PassSec&, type::SaltFilter);
bool doesUserRecordExist(const model::User&, type::UserFilter);
void saveUserRecord(const model::User&);
void saveUserSalt(const model::PassSec&);
private:
struct UserLengths;
struct SaltLengths;
struct UserLengths
{
unsigned long firstnameLength;
unsigned long lastnameLength;
unsigned long phoneLength;
unsigned long emailLength;
unsigned long usernameLength;
unsigned long passwordLength;
};
struct SaltLengths
{
unsigned long saltLength;
};
std::shared_ptr<MYSQL_BIND> insertUserValues(const model::User&, std::shared_ptr<UserLengths>);
std::shared_ptr<MYSQL_BIND> insertSaltValues(const model::PassSec&, std::shared_ptr<SaltLengths>);
std::shared_ptr<MYSQL_BIND> valueBind(model::User&, std::tuple<char*, char*, char*, char*, char*, char*>&);
std::shared_ptr<MYSQL_BIND> saltValueBind(model::PassSec&, char*);
std::shared_ptr<UserLengths> fetchUserLengths(const model::User&);
std::shared_ptr<SaltLengths> fetchSaltLengths(const model::PassSec&);
std::tuple<char*, char*, char*, char*, char*, char*> fetchUV();
model::User parseRecord(MYSQL_STMT*);
model::PassSec parseSaltRecord(MYSQL_STMT*);
};
}
#endif
+40
View File
@@ -0,0 +1,40 @@
#ifndef YEARREPOSITORY_H_
#define YEARREPOSITORY_H_
#include <utility>
#include <vector>
#include "database/BaseRepository.h"
#include "model/Models.h"
#include "type/YearFilter.h"
namespace database
{
class YearRepository : public BaseRepository
{
public:
YearRepository(const model::BinaryPath&);
std::vector<model::Year> retrieveRecords();
std::pair<model::Year, int> retrieveRecordWithSongCount(model::Year&, type::YearFilter);
model::Year retrieveRecord(model::Year&, type::YearFilter);
bool doesYearExist(const model::Year&, type::YearFilter);
void saveRecord(const model::Year&);
void deleteYear(const model::Year&, type::YearFilter);
private:
std::vector<model::Year> parseRecords(MYSQL_STMT*);
std::pair<model::Year, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented
// remove parseRecord(MYSQL_RES*)
model::Year parseRecord(MYSQL_RES*);
model::Year parseRecord(MYSQL_STMT*);
};
}
#endif
+23
View File
@@ -0,0 +1,23 @@
#ifndef ALBUMDTO_H_
#define ALBUMDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
namespace dto
{
#include OATPP_CODEGEN_BEGIN(DTO)
class AlbumDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(AlbumDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(String, title);
DTO_FIELD(Int32, year);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+22
View File
@@ -0,0 +1,22 @@
#ifndef ARTISTDTO_H_
#define ARTISTDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
namespace dto
{
#include OATPP_CODEGEN_BEGIN(DTO)
class ArtistDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(ArtistDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(String, artist);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+22
View File
@@ -0,0 +1,22 @@
#ifndef COVERARTDTO_H_
#define COVERARTDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
namespace dto
{
#include OATPP_CODEGEN_BEGIN(DTO)
class CoverArtDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(CoverArtDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(String, songTitle);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+22
View File
@@ -0,0 +1,22 @@
#ifndef GENREDTO_H_
#define GENREDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
namespace dto
{
#include OATPP_CODEGEN_BEGIN(DTO)
class GenreDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(GenreDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(String, category);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+47
View File
@@ -0,0 +1,47 @@
#ifndef LOGINRESULTDTO_H_
#define LOGINRESULTDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "model/Models.h"
namespace dto {
#include OATPP_CODEGEN_BEGIN(DTO)
class LoginResultDto : public oatpp::data::mapping::type::Object {
DTO_INIT(LoginResultDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(String, username);
DTO_FIELD(String, token);
DTO_FIELD(String, token_type);
DTO_FIELD(Int32, expiration);
DTO_FIELD(String, message);
};
class RegisterResultDto : public oatpp::data::mapping::type::Object {
DTO_INIT(RegisterResultDto, Object)
DTO_FIELD(String, username);
DTO_FIELD(Boolean, registered);
DTO_FIELD(String, message);
};
class UserDto : public oatpp::data::mapping::type::Object {
DTO_INIT(UserDto, Object)
DTO_FIELD(Int32, userId);
DTO_FIELD(String, firstname);
DTO_FIELD(String, lastname);
DTO_FIELD(String, phone);
DTO_FIELD(String, email);
DTO_FIELD(String, username);
DTO_FIELD(String, password);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+34
View File
@@ -0,0 +1,34 @@
#ifndef SONGDTO_H_
#define SONGDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
#include "model/Models.h"
namespace dto
{
#include OATPP_CODEGEN_BEGIN(DTO)
class SongDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(SongDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(String, title);
DTO_FIELD(String, artist);
DTO_FIELD(String, album);
DTO_FIELD(String, genre);
DTO_FIELD(Int32, track);
DTO_FIELD(Int32, disc);
DTO_FIELD(Int32, year);
DTO_FIELD(Int32, duration);
DTO_FIELD(Int32, coverart_id);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+22
View File
@@ -0,0 +1,22 @@
#ifndef YEARDTO_H_
#define YEARDTO_H_
#include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp"
namespace dto
{
#include OATPP_CODEGEN_BEGIN(DTO)
class YearDto : public oatpp::data::mapping::type::Object
{
DTO_INIT(YearDto, Object)
DTO_FIELD(Int32, id);
DTO_FIELD(Int32, year);
};
#include OATPP_CODEGEN_END(DTO)
}
#endif
+24
View File
@@ -0,0 +1,24 @@
#ifndef DTOCONVERSIONS_H_
#define DTOCONVERSIONS_H_
#include "dto/LoginResultDto.hpp"
#include "dto/SongDto.hpp"
#include "model/Models.h"
namespace dto { namespace conversion {
class DtoConversions {
public:
static dto::LoginResultDto::ObjectWrapper toLoginResultDto(const model::User&, const model::Token&);
static dto::RegisterResultDto::ObjectWrapper toRegisterResultDto(
const model::RegisterResult&);
static dto::SongDto::ObjectWrapper toSongDto(const model::Song&);
static model::Song toSong(dto::SongDto::ObjectWrapper&);
static model::User toUser(dto::UserDto::ObjectWrapper&);
};
}}
#endif
+25
View File
@@ -0,0 +1,25 @@
#ifndef ALBUMMANAGER_H_
#define ALBUMMANAGER_H_
#include "model/Models.h"
namespace manager
{
class AlbumManager
{
public:
AlbumManager(const model::BinaryPath&);
model::Album retrieveAlbum(model::Album&);
model::Album saveAlbum(const model::Song&);
void deleteAlbum(const model::Song&);
void updateAlbum(model::Song&, const model::Song&);
static void printAlbum(const model::Album&);
private:
model::BinaryPath m_bConf;
};
}
#endif

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