This commit is contained in:
kdeng00
2021-12-22 21:33:12 -05:00
parent 922e527819
commit 8600d9b6bc
31 changed files with 495 additions and 1000 deletions
+13 -13
View File
@@ -11,21 +11,21 @@ namespace Icarus.Authorization.Handlers
public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement> public class HasScopeHandler : AuthorizationHandler<HasScopeRequirement>
{ {
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement) protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
{ {
if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer)) if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == requirement.Issuer))
{ {
return Task.CompletedTask; return Task.CompletedTask;
} }
var scopes = context.User.FindFirst(c => var scopes = context.User.FindFirst(c =>
c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' '); c.Type == "scope" && c.Issuer == requirement.Issuer).Value.Split(' ');
if (scopes.Any(s => s == requirement.Scope)) if (scopes.Any(s => s == requirement.Scope))
{ {
context.Succeed(requirement); context.Succeed(requirement);
} }
return Task.CompletedTask; return Task.CompletedTask;
} }
} }
} }
+6 -6
View File
@@ -7,13 +7,13 @@ namespace Icarus.Authorization
public class HasScopeRequirement : IAuthorizationRequirement public class HasScopeRequirement : IAuthorizationRequirement
{ {
public string Issuer { get; } public string Issuer { get; }
public string Scope { get; } public string Scope { get; }
public HasScopeRequirement(string scope, string issuer) public HasScopeRequirement(string scope, string issuer)
{ {
Scope = scope ?? throw new ArgumentNullException(nameof(scope)); Scope = scope ?? throw new ArgumentNullException(nameof(scope));
Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer)); Issuer = issuer ?? throw new ArgumentNullException(nameof(issuer));
} }
} }
} }
-1
View File
@@ -4,7 +4,6 @@ using System.IO;
using Icarus.Constants; using Icarus.Constants;
using Icarus.Controllers.Utilities; using Icarus.Controllers.Utilities;
using Icarus.Database.Repositories;
using Icarus.Models; using Icarus.Models;
using Icarus.Types; using Icarus.Types;
+51 -530
View File
@@ -8,29 +8,17 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Id3;
using Id3.Frames;
using MySql.Data;
using MySql.Data.MySqlClient;
using NLog; using NLog;
using TagLib;
using Icarus.Controllers.Utilities; using Icarus.Controllers.Utilities;
using Icarus.Models; using Icarus.Models;
using Icarus.Database.Contexts; using Icarus.Database.Contexts;
using Icarus.Database.Repositories;
namespace Icarus.Controllers.Managers namespace Icarus.Controllers.Managers
{ {
public class SongManager : BaseManager public class SongManager : BaseManager
{ {
#region Fields #region Fields
private MySqlConnection _conn;
private MySqlCommand _cmd;
private MySqlDataAdapter _dataDump;
private DataTable _results;
private List<Song> _songs;
private Song _song;
private IConfiguration _config; private IConfiguration _config;
private string _connectionString; private string _connectionString;
private string _tempDirectoryRoot; private string _tempDirectoryRoot;
@@ -41,12 +29,6 @@ namespace Icarus.Controllers.Managers
#region Properties #region Properties
public Song SongDetails
{
get => _song;
set => _song = value;
}
public string ArchiveDirectoryRoot public string ArchiveDirectoryRoot
{ {
get => _archiveDirectoryRoot; get => _archiveDirectoryRoot;
@@ -66,37 +48,31 @@ namespace Icarus.Controllers.Managers
#region Constructors #region Constructors
/**
public SongManager() public SongManager()
{ {
Initialize(); Initialize();
InitializeConnection(); InitializeConnection();
} }
*/
public SongManager(Song song)
{
Initialize();
InitializeConnection();
_song = song;
}
public SongManager(IConfiguration config) public SongManager(IConfiguration config)
{ {
_config = config; _config = config;
Initialize(); Initialize();
InitializeConnection();
} }
public SongManager(IConfiguration config, string tempDirectoryRoot) public SongManager(IConfiguration config, string tempDirectoryRoot)
{ {
_config = config; _config = config;
_tempDirectoryRoot = tempDirectoryRoot; _tempDirectoryRoot = tempDirectoryRoot;
Initialize(); Initialize();
InitializeConnection();
} }
#endregion #endregion
#region Methods #region Methods
public SongResult UpdateSong(Song song, SongRepository songStore, AlbumRepository albumStore, public SongResult UpdateSong(Song song)/**, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore) ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)*/
{ {
var result = new SongResult(); var result = new SongResult();
@@ -110,21 +86,18 @@ namespace Icarus.Controllers.Managers
var updatedSong = updateMetadata.UpdatedSongRecord; var updatedSong = updateMetadata.UpdatedSongRecord;
var updatedAlbum = UpdateAlbumInDatabase(oldSongRecord, updatedSong, albumStore); var updatedAlbum = UpdateAlbumInDatabase(oldSongRecord, updatedSong)
oldSongRecord.AlbumId = updatedAlbum.AlbumId; oldSongRecord.AlbumId = updatedAlbum.AlbumId;
var updatedArtist = UpdateArtistInDatabase(oldSongRecord, updatedSong, artistStore); var updatedArtist = UpdateArtistInDatabase(oldSongRecord, updatedSong);
oldSongRecord.ArtistId = updatedArtist.ArtistId; oldSongRecord.ArtistId = updatedArtist.ArtistId;
var updatedGenre = UpdateGenreInDatabase(oldSongRecord, updatedSong, genreStore); var updatedGenre = UpdateGenreInDatabase(oldSongRecord, updatedSong);
Console.WriteLine($"Old Genre Id {oldSongRecord.GenreId}"); Console.WriteLine($"Old Genre Id {oldSongRecord.GenreId}");
oldSongRecord.GenreId = updatedGenre.GenreId; oldSongRecord.GenreId = updatedGenre.GenreId;
Console.WriteLine($"Updated Genre Id {updatedGenre.GenreId}"); Console.WriteLine($"Updated Genre Id {updatedGenre.GenreId}");
var updatedYear = UpdateYearInDatabase(oldSongRecord, updatedSong, yearStore); UpdateSongInDatabase(ref oldSongRecord, ref updatedSong, ref result);
oldSongRecord.YearId = updatedYear.YearId;
UpdateSongInDatabase(ref oldSongRecord, ref updatedSong, songStore, ref result);
DeleteEmptyDirectories(ref oldSongRecord, ref updatedSong); DeleteEmptyDirectories(ref oldSongRecord, ref updatedSong);
} }
@@ -160,10 +133,10 @@ namespace Icarus.Controllers.Managers
return successful; return successful;
} }
public void DeleteSong(Song song, SongRepository songStore, public void DeleteSong(Song song)/**, SongRepository songStore,
AlbumRepository albumStore, ArtistRepository artistStore, AlbumRepository albumStore, ArtistRepository artistStore,
GenreRepository genreStore, YearRepository yearStore, GenreRepository genreStore, YearRepository yearStore,
CoverArtRepository coverStore) CoverArtRepository coverStore)*/
{ {
try try
{ {
@@ -180,9 +153,9 @@ namespace Icarus.Controllers.Managers
var coverArt = coverStore.GetCoverArt(song); var coverArt = coverStore.GetCoverArt(song);
coverMgr.DeleteCoverArt(coverArt); coverMgr.DeleteCoverArt(coverArt);
coverMgr.DeleteCoverArtFromDatabase(coverArt, coverStore); coverMgr.DeleteCoverArtFromDatabase(coverArt);
DeleteSongFromDatabase(song, songStore, albumStore, artistStore, DeleteSongFromDatabase(song/**, songStore, albumStore, artistStore,
genreStore, yearStore); genreStore, yearStore*/);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -191,167 +164,14 @@ namespace Icarus.Controllers.Managers
} }
} }
public void SaveSongDetails()
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "INSERT INTO Songs(Title, AlbumTitle, Artist, Year, Genre, Duration, " +
"Filename, SongPath) VALUES(@Title, @AlbumTitle, @Artist, @Year, @Genre, " +
"@Duration, @Filename, @SongPath)";
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.ExecuteNonQuery();
}
}
} public async Task SaveSongToFileSystem(IFormFile songFile/**, SongRepository songStore,
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An Error Occurred: {exMsg}");
}
}
public void SaveSongDetails(Song song)
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "INSERT INTO Songs(Title, AlbumTitle, Artist, Year, Genre, Duration, " +
", Filename, SongPath) VALUES(@Title, @AlbumTitle, @Artist, @Year, @Genre, " +
"@Duration, @Filename, @SongPath)";
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.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An Error Occurred: {exMsg}");
}
}
public void SaveSong(SongData songData)
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "INSERT INTO SongData(Data) VALUES(@Data)";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Data", songData.Data);
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
}
public async Task SaveSongToFileSystem(IFormFile song)
{
try
{
Console.WriteLine("Saving song to the filesystem");
var filePath = Path.Combine(_tempDirectoryRoot, song.FileName);
Console.WriteLine("Saving song to the filePath");
await SaveSongToFileSystemTemp(song, filePath);
System.IO.File.Delete(filePath);
DirectoryManager dirMgr = new DirectoryManager(_config, _song);
dirMgr.CreateDirectory();
filePath = dirMgr.SongDirectory;
if (!song.FileName.EndsWith(".mp3"))
filePath += $"{song.FileName}.mp3";
else
filePath += $"{song.FileName}";
Console.WriteLine($"Full path {filePath}");
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await song.CopyToAsync(fileStream);
_song.SongPath = filePath;
Console.WriteLine($"Writing song to the directory: {filePath}");
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
}
public async Task SaveSongToFileSystem(IFormFile songFile, SongRepository sStoreContext,
AlbumRepository alStoreContext, ArtistRepository arStoreContext)
{
try
{
_logger.Info("Starting process to save song to the filesystem");
var fileTempPath = Path.Combine(_tempDirectoryRoot, songFile.FileName);
var song = await SaveSongTemp(songFile, fileTempPath);
System.IO.File.Delete(fileTempPath);
DirectoryManager dirMgr = new DirectoryManager(_config, song);
dirMgr.CreateDirectory();
var filePath = dirMgr.SongDirectory;
if (!songFile.FileName.EndsWith(".mp3"))
filePath += $"{songFile.FileName}.mp3";
else
filePath += $"{songFile.FileName}";
_logger.Info($"Absolute song path: {filePath}");
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
await (songFile.CopyToAsync(fileStream));
song.SongPath = filePath;
_logger.Info("Song Successfully saved");
}
SaveSongToDatabase(song, sStoreContext, alStoreContext, arStoreContext);
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public async Task SaveSongToFileSystem(IFormFile songFile, SongRepository songStore,
AlbumRepository albumStore, ArtistRepository artistStore, AlbumRepository albumStore, ArtistRepository artistStore,
GenreRepository genreStore, YearRepository yearStore, GenreRepository genreStore, YearRepository yearStore,
CoverArtRepository coverArtStore) CoverArtRepository coverArtStore*/)
{ {
try try
{ {
@@ -388,10 +208,9 @@ namespace Icarus.Controllers.Managers
var coverMgr = new CoverArtManager(_config.GetValue<string>("CoverArtPath")); var coverMgr = new CoverArtManager(_config.GetValue<string>("CoverArtPath"));
var coverArt = coverMgr.SaveCoverArt(song); var coverArt = coverMgr.SaveCoverArt(song);
coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt, coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt);//,
coverArtStore); SaveSongToDatabase(song);/**, songStore, albumStore, artistStore, genreStore,
SaveSongToDatabase(song, songStore, albumStore, artistStore, genreStore, yearStore);*/
yearStore);
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -400,90 +219,8 @@ namespace Icarus.Controllers.Managers
} }
} }
public async Task<List<Song>> RetrieveAllSongDetails()
{
try
{
InitializeResults();
_songs = new List<Song>();
_conn.Open();
string query = "SELECT * FROM Songs";
_cmd = new MySqlCommand(query, _conn);
_cmd.ExecuteNonQuery();
_dataDump = new MySqlDataAdapter(_cmd);
_dataDump.Fill(_results);
_dataDump.Dispose();
await PopulateSongDetails();
_conn.Close();
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error ocurred: {exMsg}");
}
return _songs;
}
public Song RetrieveSongDetails(int id)
{
DataTable results = new DataTable();
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "SELECT * FROM Songs WHERE Id=@Id";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.ExecuteNonQuery();
using (MySqlDataAdapter dataDump = new MySqlDataAdapter(cmd))
{
dataDump.Fill(results);
}
}
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred");
}
DataRow row = results.Rows[0];
return new Song
{
Id = Int32.Parse(row["Id"].ToString()),
Filename = row["Filename"].ToString(),
SongPath = row["SongPath"].ToString()
};
}
public async Task<SongData> RetrieveSong(int id)
{
SongData song = new SongData();
try
{
_song = RetrieveSongDetails(id);
song = await RetrieveSongFromFileSystem(_song);
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
return song;
}
public async Task<SongData> RetrieveSong(Song songMetaData) public async Task<SongData> RetrieveSong(Song songMetaData)
{ {
SongData song = new SongData(); SongData song = new SongData();
@@ -502,61 +239,6 @@ namespace Icarus.Controllers.Managers
} }
private Song RetrieveMetaData(string filePath)
{
Song newSong = new Song
{
Title = "Untitled",
Artist = "Untitled",
AlbumTitle = "Untitled",
Year = 0,
Genre = "Untitled",
Duration = 0,
SongPath = ""
};
string title, artist, album, genre;
int year, duration;
Console.WriteLine("Stripping song metadata");
try
{
TagLib.File tfile = TagLib.File.Create(filePath);
using (var mp3 = new Mp3(filePath))
{
Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
title = tag.Title;
Console.WriteLine("Title: {0}", title);
newSong.Title = title;
artist = tag.Artists;
Console.WriteLine("Artist: {0}", artist);
newSong.Artist = artist;
album = tag.Album;
Console.WriteLine("Album: {0}", album);
newSong.AlbumTitle = album;
genre = "Not Implemented";
Console.WriteLine("Genre: {0}", genre);
newSong.Genre = genre;
year = (int)tag.Year;
Console.WriteLine("Year: {0}", year);
newSong.Year = year;
duration = (int)tfile.Properties.Duration.TotalSeconds;
Console.WriteLine("Duration: {0}", duration);
newSong.Duration = duration;
}
_song = newSong;
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred when stripping metadata\n{msg}");
_song = newSong;
}
return newSong;
}
private async Task<SongData> RetrieveSongFromFileSystem(Song details) private async Task<SongData> RetrieveSongFromFileSystem(Song details)
{ {
@@ -587,23 +269,6 @@ namespace Icarus.Controllers.Managers
return song; return song;
} }
private async Task SaveSongToFileSystemTemp(IFormFile song, string filePath)
{
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
Console.WriteLine("Retrieving song and storing it in memory");
_logger.Info("Retrieving song and storing it in memory");
await song.CopyToAsync(fileStream);
Console.WriteLine($"Retrieving metadata of song from filepath {filePath}");
_logger.Info($"Retrieving metadata of song from filepath {filePath}");
MetadataRetriever meta = new MetadataRetriever();
_song = meta.RetrieveMetaData(filePath);
Console.WriteLine("Assigning song filename");
_song.Filename = song.FileName;
Console.WriteLine($"Song filename retrieved: {song.FileName}");
}
}
private bool SongRecordChanged(Song currentSong, Song songUpdates) private bool SongRecordChanged(Song currentSong, Song songUpdates)
{ {
@@ -641,46 +306,24 @@ namespace Icarus.Controllers.Managers
} }
} }
private void InitializeConnection()
{
_conn = new MySqlConnection(_connectionString);
}
private void InitializeResults()
{
_results = new DataTable();
}
private void SaveSongToDatabase(Song song, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore) private void SaveSongToDatabase(Song song)/**, SongRepository songStore, AlbumRepository albumStore,
{ ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)*/
_logger.Info("Starting process to save the song to the database");
MetadataRetriever.PrintMetadata(song);
SaveAlbumToDatabase(ref song, albumStore);
MetadataRetriever.PrintMetadata(song);
SaveArtistToDatabase(ref song, artistStore);
MetadataRetriever.PrintMetadata(song);
_logger.Info($"Song;\nTitle {song.Title}\nAlbum {song.AlbumTitle}\nAlbum Id {song.AlbumId}\nArtist {song.ArtistId}");
songStore.SaveSong(song);
}
private void SaveSongToDatabase(Song song, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)
{ {
_logger.Info("Starting process to save the song to the database"); _logger.Info("Starting process to save the song to the database");
SaveAlbumToDatabase(ref song, albumStore); SaveAlbumToDatabase(ref song);//, albumStore);
SaveArtistToDatabase(ref song, artistStore); SaveArtistToDatabase(ref song);//, artistStore);
SaveGenreToDatabase(ref song, genreStore); SaveGenreToDatabase(ref song);//, genreStore);
SaveYearToDatabase(ref song, yearStore);
var info = "Saving Song to DB"; var info = "Saving Song to DB";
Console.WriteLine(info); Console.WriteLine(info);
_logger.Info(info); _logger.Info(info);
songStore.SaveSong(song); songStore.SaveSong(song);
} }
private void SaveAlbumToDatabase(ref Song song, AlbumRepository albumStore) private void SaveAlbumToDatabase(ref Song song)//, AlbumRepository albumStore)
{ {
_logger.Info("Starting process to save the album record of the song to the database"); _logger.Info("Starting process to save the album record of the song to the database");
@@ -707,7 +350,7 @@ namespace Icarus.Controllers.Managers
song.AlbumId = album.AlbumId; song.AlbumId = album.AlbumId;
} }
private void SaveArtistToDatabase(ref Song song, ArtistRepository artistStore) private void SaveArtistToDatabase(ref Song song)//, ArtistRepository artistStore)
{ {
_logger.Info("Starting process to save the artist record of the song to the database"); _logger.Info("Starting process to save the artist record of the song to the database");
@@ -733,7 +376,7 @@ namespace Icarus.Controllers.Managers
song.ArtistId = artist.ArtistId; song.ArtistId = artist.ArtistId;
} }
private void SaveGenreToDatabase(ref Song song, GenreRepository genreStore) private void SaveGenreToDatabase(ref Song song)//, GenreRepository genreStore)
{ {
_logger.Info("Starting process to save the genre record of the song to the database"); _logger.Info("Starting process to save the genre record of the song to the database");
@@ -764,32 +407,7 @@ namespace Icarus.Controllers.Managers
song.GenreId = genre.GenreId; song.GenreId = genre.GenreId;
} }
private void SaveYearToDatabase(ref Song song, YearRepository yearStore)
{
_logger.Info("Starting process to save the year record of the song to the database");
var year = new Year
{
YearValue = song.Year.Value,
SongCount = 1
};
if (!yearStore.DoesYearExist(song))
{
yearStore.SaveYear(year);
year = yearStore.GetSongYear(song);
}
else
{
var yearRetrieved = yearStore.GetSongYear(song);
year.YearId = yearRetrieved.YearId;
year.SongCount = yearRetrieved.SongCount + 1;
yearStore.UpdateYear(year);
}
song.YearId = year.YearId;
}
private bool DeleteSongFromFilesystem(Song song) private bool DeleteSongFromFilesystem(Song song)
{ {
@@ -826,7 +444,7 @@ namespace Icarus.Controllers.Managers
return true; return true;
} }
private Album UpdateAlbumInDatabase(Song oldSongRecord, Song newSongRecord, AlbumRepository albumStore) private Album UpdateAlbumInDatabase(Song oldSongRecord, Song newSongRecord)//, AlbumRepository albumStore)
{ {
var albumRecord = albumStore.GetAlbum(oldSongRecord, true); var albumRecord = albumStore.GetAlbum(oldSongRecord, true);
var oldAlbumTitle = oldSongRecord.AlbumTitle; var oldAlbumTitle = oldSongRecord.AlbumTitle;
@@ -877,7 +495,7 @@ namespace Icarus.Controllers.Managers
return existingAlbumRecord; return existingAlbumRecord;
} }
} }
private Artist UpdateArtistInDatabase(Song oldSongRecord, Song newSongRecord, ArtistRepository artistStore) private Artist UpdateArtistInDatabase(Song oldSongRecord, Song newSongRecord)//, ArtistRepository artistStore)
{ {
var oldArtistRecord = artistStore.GetArtist(oldSongRecord, true); var oldArtistRecord = artistStore.GetArtist(oldSongRecord, true);
var oldArtistName = oldArtistRecord.Name; var oldArtistName = oldArtistRecord.Name;
@@ -922,7 +540,7 @@ namespace Icarus.Controllers.Managers
return existingArtistRecord; return existingArtistRecord;
} }
} }
private Genre UpdateGenreInDatabase(Song oldSongRecord, Song newSongRecord, GenreRepository genreStore) private Genre UpdateGenreInDatabase(Song oldSongRecord, Song newSongRecord)//, GenreRepository genreStore)
{ {
var oldGenreRecord = genreStore.GetGenre(oldSongRecord, true); var oldGenreRecord = genreStore.GetGenre(oldSongRecord, true);
var oldGenreName = oldGenreRecord.GenreName; var oldGenreName = oldGenreRecord.GenreName;
@@ -966,57 +584,13 @@ namespace Icarus.Controllers.Managers
return genreStore.GetGenre(existingGenreRecord); return genreStore.GetGenre(existingGenreRecord);
} }
} }
private Year UpdateYearInDatabase(Song oldSongRecord, Song newSongRecord, YearRepository yearStore)
{ private void UpdateSongInDatabase(ref Song oldSongRecord, ref Song newSongRecord, /**SongRepository songStore,*/
var oldYearRecord = yearStore.GetSongYear(oldSongRecord, true);
var oldYearValue = oldYearRecord.YearValue;
var newYearValue = newSongRecord.Year;
if (oldYearValue == newYearValue || newYearValue == 0 || newYearValue == null)
{
_logger.Info("No change to the song's Year");
return oldYearRecord;
}
_logger.Info("Change to the song's year found");
if (oldYearRecord.SongCount <= 1)
{
_logger.Info("Deleting year record");
yearStore.DeleteYear(oldYearRecord);
}
if(!yearStore.DoesYearExist(newSongRecord))
{
_logger.Info("Creating new year record");
var newYearRecord = new Year
{
YearValue = newYearValue.Value
};
yearStore.SaveYear(newYearRecord);
return yearStore.GetSongYear(newSongRecord, true);
}
else
{
_logger.Info("Updating existing year record");
var existingYearRecord = yearStore.GetSongYear(newSongRecord);
yearStore.UpdateYear(existingYearRecord);
return existingYearRecord;
}
}
private void UpdateSongInDatabase(ref Song oldSongRecord, ref Song newSongRecord, SongRepository songStore,
ref SongResult result) ref SongResult result)
{ {
var updatedSongRecord = new Song var updatedSongRecord = new Song
{ {
Id = oldSongRecord.Id, SongID = oldSongRecord.SongID,
Title = oldSongRecord.Title, Title = oldSongRecord.Title,
Artist = oldSongRecord.Artist, Artist = oldSongRecord.Artist,
AlbumTitle = oldSongRecord.AlbumTitle, AlbumTitle = oldSongRecord.AlbumTitle,
@@ -1111,19 +685,20 @@ namespace Icarus.Controllers.Managers
result.SongTitle = updatedSongRecord.Title; result.SongTitle = updatedSongRecord.Title;
} }
private void DeleteSongFromDatabase(Song song, SongRepository songStore, AlbumRepository albumStore, private void DeleteSongFromDatabase(Song song)/**, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore) ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)*/
{ {
_logger.Info("Starting process to delete records related to the song from the database"); _logger.Info("Starting process to delete records related to the song from the database");
DeleteAlbumFromDatabase(song, albumStore); DeleteAlbumFromDatabase(song);//, albumStore);
DeleteArtistFromDatabase(song, artistStore); DeleteArtistFromDatabase(song);//, artistStore);
DeleteGenreFromDatabase(song, genreStore); DeleteGenreFromDatabase(song);//, genreStore);
DeleteYearFromDatabase(song, yearStore);
songStore.DeleteSong(song); var sngContext = new SongContext(_connectionString);
sngContext.Songs.Remove(song);
sngContext.SaveChanges();
} }
private void DeleteAlbumFromDatabase(Song song, AlbumRepository albumStore) private void DeleteAlbumFromDatabase(Song song)// AlbumRepository albumStore)
{ {
if (!albumStore.DoesAlbumExist(song)) if (!albumStore.DoesAlbumExist(song))
{ {
@@ -1136,7 +711,7 @@ namespace Icarus.Controllers.Managers
if (album.SongCount <= 1) if (album.SongCount <= 1)
albumStore.DeleteAlbum(album); albumStore.DeleteAlbum(album);
} }
private void DeleteArtistFromDatabase(Song song, ArtistRepository artistStore) private void DeleteArtistFromDatabase(Song song)//, ArtistRepository artistStore)
{ {
if (!artistStore.DoesArtistExist(song)) if (!artistStore.DoesArtistExist(song))
{ {
@@ -1149,7 +724,7 @@ namespace Icarus.Controllers.Managers
if (artist.SongCount <= 1) if (artist.SongCount <= 1)
artistStore.DeleteArtist(artist); artistStore.DeleteArtist(artist);
} }
private void DeleteGenreFromDatabase(Song song, GenreRepository genreStore) private void DeleteGenreFromDatabase(Song song)//, GenreRepository genreStore)
{ {
if (!genreStore.DoesGenreExist(song)) if (!genreStore.DoesGenreExist(song))
{ {
@@ -1162,62 +737,8 @@ namespace Icarus.Controllers.Managers
if (genre.SongCount <= 1) if (genre.SongCount <= 1)
genreStore.DeleteGenre(genre); genreStore.DeleteGenre(genre);
} }
private void DeleteYearFromDatabase(Song song, YearRepository yearStore)
{
if (!yearStore.DoesYearExist(song))
{
_logger.Info("Cannot delete the year record because it does not exist");
return;
}
var year = yearStore.GetSongYear(song, true);
if (year.SongCount <= 1)
yearStore.DeleteYear(year);
}
private async Task PopulateSongDetails()
{
foreach (DataRow row in _results.Rows)
{
Song song = new Song();
foreach (DataColumn col in _results.Columns)
{
string colStr = col.ToString().ToUpper();
switch (colStr)
{
case "ID":
song.Id = Int32.Parse(row[col].ToString());
break;
case "TITLE":
song.Title = row[col].ToString();
break;
case "ALBUM":
song.AlbumTitle = row[col].ToString();
break;
case "ARTIST":
song.Artist = row[col].ToString();
break;
case "YEAR":
song.Year = Int32.Parse(row[col].ToString());
break;
case "GENRE":
song.Genre = row[col].ToString();
break;
case "DURATION":
song.Duration = Int32.Parse(row[col].ToString());
break;
case "FILENAME":
song.Filename = row[col].ToString();
break;
case "SONGPATH":
song.SongPath = row[col].ToString();
break;
}
}
_songs.Add(song);
}
}
#endregion #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
}
}
+79 -79
View File
@@ -13,18 +13,18 @@ namespace Icarus.Controllers.Utilities
public class SongCompression public class SongCompression
{ {
#region Fields #region Fields
string _compressedSongFilename; string _compressedSongFilename;
string _tempDirectory; string _tempDirectory;
byte[] _uncompressedSong; byte[] _uncompressedSong;
#endregion #endregion
#region Propterties #region Propterties
public string CompressedSongFilename public string CompressedSongFilename
{ {
get => _compressedSongFilename; get => _compressedSongFilename;
set => _compressedSongFilename = value; set => _compressedSongFilename = value;
} }
#endregion #endregion
@@ -44,86 +44,86 @@ namespace Icarus.Controllers.Utilities
#region Methods #region Methods
public async Task<SongData> RetrieveCompressedSong(Song song) 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); SongData songData = new SongData();
zip.Save(tmpZipFilePath); 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;
} }
Console.WriteLine("Successfully compressed");
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;
} }
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine("An error ocurred");
Console.WriteLine(exMsg);
}
if (songDetails.Filename.Contains(".mp3")) // Method not being used
{ public byte[] CompressedSong(byte[] uncompressedSong)
_compressedSongFilename = StripMP3Extension(songDetails.Filename); {
} 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 tmpZipFilePath; return compressedSong;
} }
// 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) string StripMP3Extension(string filename)
{ {
Console.WriteLine($"Before: {filename}"); Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length; int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}"); Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1; var endIndex = filenameLength - 1;
var startIndex = endIndex - 3; var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}"); Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4); var stripped = filename.Remove(startIndex, 4);
stripped += ".zip"; stripped += ".zip";
Console.WriteLine($"After {stripped}"); Console.WriteLine($"After {stripped}");
return stripped; return stripped;
} }
#endregion #endregion
} }
} }
+2 -1
View File
@@ -8,7 +8,8 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Icarus.Models; using Icarus.Models;
using Icarus.Database.Repositories; using Icarus.Database.Contexts;
// using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1 namespace Icarus.Controllers.V1
{ {
+5 -5
View File
@@ -10,7 +10,7 @@ using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Managers; using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities; using Icarus.Controllers.Utilities;
using Icarus.Models; using Icarus.Models;
using Icarus.Database.Repositories; using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1 namespace Icarus.Controllers.V1
{ {
@@ -41,12 +41,12 @@ namespace Icarus.Controllers.V1
user.Password = pe.HashPassword(user); user.Password = pe.HashPassword(user);
user.EmailVerified = false; user.EmailVerified = false;
UserRepository context = HttpContext.RequestServices var context = new UserContext(_config.GetConnectionString("DefaultConnection"));
.GetService(typeof(UserRepository)) as UserRepository;
try try
{ {
context.SaveUser(user); context.Add(user);
context.SaveChanges();
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -61,7 +61,7 @@ namespace Icarus.Controllers.V1
Username = user.Username Username = user.Username
}; };
if (context.DoesUserExist(user)) if (context.Users.FirstOrDefault(sng => sng.Username.Equals(user.Username)) != null)
{ {
registerResult.Message = "Successful registration"; registerResult.Message = "Successful registration";
registerResult.SuccessfullyRegistered = true; registerResult.SuccessfullyRegistered = true;
+2 -41
View File
@@ -14,7 +14,6 @@ using Microsoft.Extensions.Logging;
using Icarus.Controllers.Managers; using Icarus.Controllers.Managers;
using Icarus.Models; using Icarus.Models;
using Icarus.Database.Contexts; using Icarus.Database.Contexts;
using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1 namespace Icarus.Controllers.V1
{ {
@@ -23,12 +22,6 @@ namespace Icarus.Controllers.V1
public class SongDataController : ControllerBase public class SongDataController : ControllerBase
{ {
#region Fields #region Fields
private SongRepository _songRepository;
private AlbumRepository _albumRepository;
private ArtistRepository _artistRepository;
private GenreRepository _genreRepository;
private YearRepository _yearRepository;
private CoverArtRepository _coverArtRepository;
private IConfiguration _config; private IConfiguration _config;
private ILogger<SongDataController> _logger; private ILogger<SongDataController> _logger;
private SongManager _songMgr; private SongManager _songMgr;
@@ -50,33 +43,6 @@ namespace Icarus.Controllers.V1
} }
#endregion #endregion
private void Initialize()
{
_songRepository = HttpContext
.RequestServices
.GetService
(typeof(SongRepository)) as SongRepository;
_albumRepository = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
_artistRepository = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
_genreRepository = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
_yearRepository = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
_coverArtRepository = HttpContext
.RequestServices
.GetService(typeof(CoverArtRepository)) as CoverArtRepository;
}
[HttpGet("{id}")] [HttpGet("{id}")]
@@ -84,7 +50,6 @@ namespace Icarus.Controllers.V1
[Authorize("download:songs")] [Authorize("download:songs")]
public async Task<IActionResult> Get(int id) public async Task<IActionResult> Get(int id)
{ {
Initialize();
var songMetaData = _songRepository.GetSong(id); var songMetaData = _songRepository.GetSong(id);
SongData song = await _songMgr.RetrieveSong(songMetaData); SongData song = await _songMgr.RetrieveSong(songMetaData);
@@ -98,8 +63,6 @@ namespace Icarus.Controllers.V1
{ {
try try
{ {
Initialize();
Console.WriteLine("Uploading song..."); Console.WriteLine("Uploading song...");
_logger.LogInformation("Uploading song..."); _logger.LogInformation("Uploading song...");
@@ -127,10 +90,8 @@ namespace Icarus.Controllers.V1
[Authorize("delete:songs")] [Authorize("delete:songs")]
public IActionResult Delete(int id) public IActionResult Delete(int id)
{ {
Initialize(); var songMetaData = new Song{ SongID = id };
Console.WriteLine($"Id {songMetaData.SongID}");
var songMetaData = new Song{ Id = id };
Console.WriteLine($"Id {songMetaData.Id}");
songMetaData = _songRepository.GetSong(songMetaData); songMetaData = _songRepository.GetSong(songMetaData);
if (string.IsNullOrEmpty(songMetaData.Title)) if (string.IsNullOrEmpty(songMetaData.Title))
+7 -5
View File
@@ -9,10 +9,11 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Icarus.Models; using Icarus.Models;
using Icarus.Database.Repositories; using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1 namespace Icarus.Controllers.V1
{ {
@@ -22,6 +23,7 @@ namespace Icarus.Controllers.V1
{ {
#region Fields #region Fields
private ILogger<SongStreamController> _logger; private ILogger<SongStreamController> _logger;
private IConfiguration _config;
#endregion #endregion
@@ -30,9 +32,10 @@ namespace Icarus.Controllers.V1
#region Constructor #region Constructor
public SongStreamController(ILogger<SongStreamController> logger) public SongStreamController(ILogger<SongStreamController> logger, IConfiguration config)
{ {
_logger = logger; _logger = logger;
_config = config;
} }
#endregion #endregion
@@ -42,10 +45,9 @@ namespace Icarus.Controllers.V1
[Authorize("stream:songs")] [Authorize("stream:songs")]
public async Task<IActionResult> Get(int id) public async Task<IActionResult> Get(int id)
{ {
var songStore= HttpContext.RequestServices var context = new SongContext(_config.GetConnectionString("DefaultConnection"));
.GetService(typeof(SongRepository)) as SongRepository;
var song = songStore.GetSong(new Song { Id = id }); var song = context.Songs.FirstOrDefault(sng => sng.SongID == id);
var stream = new FileStream(song.SongPath, FileMode.Open, FileAccess.Read); var stream = new FileStream(song.SongPath, FileMode.Open, FileAccess.Read);
stream.Position = 0; stream.Position = 0;
-76
View File
@@ -1,76 +0,0 @@
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Database.Repositories;
namespace Icarus.Controller.V1
{
[Route("api/v1/year")]
[ApiController]
public class YearController : ControllerBase
{
#region Fields
private readonly ILogger<YearController> _logger;
#endregion
#region Properties
#endregion
#region Constructors
public YearController(ILogger<YearController> logger)
{
_logger = logger;
}
#endregion
#region HTTP Routes
[HttpGet]
[Authorize("read:year")]
public IActionResult Get()
{
var yearValues = new List<Year>();
var yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
yearValues = yearStore.GetSongYears();
if (yearValues.Count > 0)
return Ok(yearValues);
else
return NotFound(new List<Year>());
}
[HttpGet("{id}")]
[Authorize("read:year")]
public IActionResult Get(int id)
{
var year = new Year
{
YearId = id
};
var yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
if (yearStore.DoesYearExist(year))
{
year = yearStore.GetSongYear(year);
return Ok(year);
}
else
return NotFound(new Year());
}
#endregion
}
}
+16 -6
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
@@ -14,12 +15,21 @@ namespace Icarus.Database.Contexts
{ {
public DbSet<Album> Albums { get; set; } public DbSet<Album> Albums { get; set; }
public AlbumContext(DbContextOptions<AlbumContext> options) : base(options) { } public AlbumContext(DbContextOptions<AlbumContext> options) : base(options) { }
public AlbumContext(string connString) : base(new DbContextOptionsBuilder<AlbumContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<Album>() modelBuilder.Entity<Album>()
.ToTable("Album"); .ToTable("Album");
} }
public bool DoesRecordExist(Album album)
{
return Albums.FirstOrDefault(alb => alb.AlbumId == album.AlbumId) != null ? true : false;
}
} }
} }
+17 -6
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
@@ -14,12 +15,22 @@ namespace Icarus.Database.Contexts
{ {
public DbSet<Artist> Artists { get; set; } public DbSet<Artist> Artists { get; set; }
public ArtistContext(DbContextOptions<ArtistContext> options) : base (options) { } public ArtistContext(DbContextOptions<ArtistContext> options) : base (options) { }
public ArtistContext(string connString) : base(new DbContextOptionsBuilder<ArtistContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<Artist>() modelBuilder.Entity<Artist>()
.ToTable("Artist"); .ToTable("Artist");
} }
public bool DoesRecordExist(Artist artist)
{
return Artists.FirstOrDefault(arst => arst.ArtistId == artist.ArtistId) != null ? true : false;
}
} }
} }
+18 -7
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
@@ -14,12 +15,22 @@ namespace Icarus.Database.Contexts
{ {
public DbSet<CoverArt> CoverArtImages { get; set; } public DbSet<CoverArt> CoverArtImages { get; set; }
public CoverArtContext(DbContextOptions<CoverArtContext> options) : base(options) { } public CoverArtContext(DbContextOptions<CoverArtContext> options) : base(options) { }
public CoverArtContext(string connString) : base(new DbContextOptionsBuilder<CoverArtContext>()
protected override void OnModelCreating(ModelBuilder modelBuilder) .UseMySQL(connString).Options)
{ {
modelBuilder.Entity<CoverArt>() }
.ToTable("CoverArt");
} protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CoverArt>()
.ToTable("CoverArt");
}
public bool DoesRecordExist(CoverArt cover)
{
return CoverArtImages.FirstOrDefault(cov => cov.CoverArtId == cover.CoverArtId) != null ? true : false;
}
} }
} }
+16 -5
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
@@ -14,11 +15,21 @@ namespace Icarus.Database.Contexts
{ {
public DbSet<Genre> Genres { get; set; } public DbSet<Genre> Genres { get; set; }
public GenreContext(DbContextOptions<GenreContext> options) : base(options) { } public GenreContext(DbContextOptions<GenreContext> options) : base(options) { }
public GenreContext(string connString) : base(new DbContextOptionsBuilder<GenreContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<Genre>() modelBuilder.Entity<Genre>()
.ToTable("Genre"); .ToTable("Genre");
} }
public bool DoesRecordExist(Genre genre)
{
return Genres.FirstOrDefault(gnr => gnr.GenreId == genre.GenreId) != null ? true : false;
}
} }
} }
+61 -49
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
@@ -14,62 +15,73 @@ namespace Icarus.Database.Contexts
{ {
public DbSet<Song> Songs { get; set; } public DbSet<Song> Songs { get; set; }
public SongContext(string connString) : base(new DbContextOptionsBuilder<SongContext>()
.UseMySQL(connString).Options)
{
}
public SongContext(DbContextOptions<SongContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder) public SongContext(DbContextOptions<SongContext> options) : base(options) { }
{
modelBuilder.Entity<Song>()
.ToTable("Song");
modelBuilder.Entity<Song>() protected override void OnModelCreating(ModelBuilder modelBuilder)
.HasOne(s => s.Album) {
.WithMany(al => al.Songs) modelBuilder.Entity<Song>()
.HasForeignKey(s => s.AlbumId) .ToTable("Song");
.OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.HasOne(sa => sa.SongArtist) .HasOne(s => s.Album)
.WithMany(ar => ar.Songs) .WithMany(al => al.Songs)
.HasForeignKey(s => s.ArtistId) .HasForeignKey(s => s.AlbumId)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.HasOne(s => s.SongGenre) .HasOne(sa => sa.SongArtist)
.WithMany(gnr => gnr.Songs) .WithMany(ar => ar.Songs)
.HasForeignKey(s => s.GenreId) .HasForeignKey(s => s.ArtistId)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.HasOne(s => s.SongYear) .HasOne(s => s.SongGenre)
.WithMany(yr => yr.Songs) .WithMany(gnr => gnr.Songs)
.HasForeignKey(s => s.YearId) .HasForeignKey(s => s.GenreId)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.HasOne(s => s.SongCoverArt) .HasOne(s => s.SongYear)
.WithMany(ca => ca.Songs) .WithMany(yr => yr.Songs)
.HasForeignKey(s => s.CoverArtId) .HasForeignKey(s => s.YearId)
.OnDelete(DeleteBehavior.SetNull); .OnDelete(DeleteBehavior.SetNull);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.Property(s => s.Year) .HasOne(s => s.SongCoverArt)
.IsRequired(false); .WithMany(ca => ca.Songs)
modelBuilder.Entity<Song>() .HasForeignKey(s => s.CoverArtId)
.Property(s => s.YearId) .OnDelete(DeleteBehavior.SetNull);
.IsRequired(false);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.Property(s => s.GenreId) .Property(s => s.Year)
.IsRequired(false); .IsRequired(false);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.Property(s => s.ArtistId) .Property(s => s.YearId)
.IsRequired(false); .IsRequired(false);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.Property(s => s.AlbumId) .Property(s => s.GenreId)
.IsRequired(false); .IsRequired(false);
modelBuilder.Entity<Song>() modelBuilder.Entity<Song>()
.Property(s => s.CoverArtId) .Property(s => s.ArtistId)
.IsRequired(false); .IsRequired(false);
} modelBuilder.Entity<Song>()
.Property(s => s.AlbumId)
.IsRequired(false);
modelBuilder.Entity<Song>()
.Property(s => s.CoverArtId)
.IsRequired(false);
}
public bool DoesRecordExist(Song song)
{
return Songs.FirstOrDefault(sng => sng.SongID == song.SongID) != null ? true : false;
}
} }
} }
+17 -6
View File
@@ -1,5 +1,6 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using MySql.Data; using MySql.Data;
@@ -15,16 +16,26 @@ namespace Icarus.Database.Contexts
public DbSet<User> Users { get; set; } public DbSet<User> Users { get; set; }
public UserContext(DbContextOptions<UserContext> options) : base(options) { } public UserContext(DbContextOptions<UserContext> options) : base(options) { }
public UserContext(string connString) : base(new DbContextOptionsBuilder<UserContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder) protected override void OnModelCreating(ModelBuilder modelBuilder)
{ {
modelBuilder.Entity<User>()
.ToTable("User");
modelBuilder.Entity<User>() modelBuilder.Entity<User>()
.Property(u => u.LastLogin).IsRequired(false); .ToTable("User");
modelBuilder.Entity<User>() modelBuilder.Entity<User>()
.Property(u => u.DateCreated).HasDefaultValue(DateTime.Now); .Property(u => u.LastLogin).IsRequired(false);
modelBuilder.Entity<User>()
.Property(u => u.DateCreated).HasDefaultValue(DateTime.Now);
}
public bool DoesRecordExist(User user)
{
return Users.FirstOrDefault(usr => usr.UserID == user.UserID) != null ? true : false;
} }
} }
} }
-25
View File
@@ -1,25 +0,0 @@
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
using MySql.Data.EntityFrameworkCore.Extensions;
using MySql.Data.MySqlClient;
using Icarus.Models;
namespace Icarus.Database.Contexts
{
public class YearContext : DbContext
{
public DbSet<Year> YearValues { get; set; }
public YearContext(DbContextOptions<YearContext> options) : base(options) { }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Year>()
.ToTable("Year");
}
}
}
+10 -10
View File
@@ -9,16 +9,16 @@ namespace Icarus.Models
public class Album public class Album
{ {
[JsonProperty("id")] [JsonProperty("id")]
public int AlbumId { get; set; } public int AlbumId { get; set; }
[JsonProperty("title")] [JsonProperty("title")]
public string Title { get; set; } public string Title { get; set; }
[JsonProperty("album_artist")] [JsonProperty("album_artist")]
public string AlbumArtist { get; set; } public string AlbumArtist { get; set; }
[JsonProperty("song_count")] [JsonProperty("song_count")]
[NotMapped] [NotMapped]
public int SongCount { get; set; } public int SongCount { get; set; }
[JsonIgnore] [JsonIgnore]
public List<Song> Songs { get; set; } public List<Song> Songs { get; set; }
} }
} }
+8 -8
View File
@@ -9,14 +9,14 @@ namespace Icarus.Models
public class Artist public class Artist
{ {
[JsonProperty("id")] [JsonProperty("id")]
public int ArtistId { get; set; } public int ArtistId { get; set; }
[JsonProperty("name")] [JsonProperty("name")]
public string Name { get; set; } public string Name { get; set; }
[JsonProperty("song_count")] [JsonProperty("song_count")]
[NotMapped] [NotMapped]
public int SongCount { get; set; } public int SongCount { get; set; }
[JsonIgnore] [JsonIgnore]
public List<Song> Songs { get; set; } public List<Song> Songs { get; set; }
} }
} }
+1 -1
View File
@@ -7,6 +7,6 @@ namespace Icarus.Models
public class BaseResult public class BaseResult
{ {
[JsonProperty("message")] [JsonProperty("message")]
public string Message { get; set; } public string Message { get; set; }
} }
} }
+8 -8
View File
@@ -9,14 +9,14 @@ namespace Icarus.Models
public class Genre public class Genre
{ {
[JsonProperty("id")] [JsonProperty("id")]
public int GenreId { get; set; } public int GenreId { get; set; }
[JsonProperty("genre")] [JsonProperty("genre")]
public string GenreName { get; set; } public string GenreName { get; set; }
[JsonProperty("song_count")] [JsonProperty("song_count")]
[NotMapped] [NotMapped]
public int SongCount { get; set; } public int SongCount { get; set; }
[JsonIgnore] [JsonIgnore]
public List<Song> Songs { get; set; } public List<Song> Songs { get; set; }
} }
} }
+9 -9
View File
@@ -7,14 +7,14 @@ namespace Icarus.Models
public class LoginResult : BaseResult public class LoginResult : BaseResult
{ {
[JsonProperty("id")] [JsonProperty("id")]
public int UserId { get; set; } public int UserId { get; set; }
[JsonProperty("username")] [JsonProperty("username")]
public string Username { get; set; } public string Username { get; set; }
[JsonProperty("token")] [JsonProperty("token")]
public string Token { get; set; } public string Token { get; set; }
[JsonProperty("token_type")] [JsonProperty("token_type")]
public string TokenType { get; set; } public string TokenType { get; set; }
[JsonProperty("expiration")] [JsonProperty("expiration")]
public int Expiration { get; set; } public int Expiration { get; set; }
} }
} }
+3 -3
View File
@@ -7,8 +7,8 @@ namespace Icarus.Models
public class RegisterResult : BaseResult public class RegisterResult : BaseResult
{ {
[JsonProperty("username")] [JsonProperty("username")]
public string Username { get; set; } public string Username { get; set; }
[JsonProperty("successfully_registered")] [JsonProperty("successfully_registered")]
public bool SuccessfullyRegistered { get; set; } public bool SuccessfullyRegistered { get; set; }
} }
} }
+38 -38
View File
@@ -7,48 +7,48 @@ namespace Icarus.Models
{ {
public class Song public class Song
{ {
[JsonProperty("id")] [JsonProperty("song_id")]
public int Id { get; set; } public int SongID { get; set; }
[JsonProperty("title")] [JsonProperty("title")]
public string Title { get; set; } public string Title { get; set; }
[JsonProperty("album")] [JsonProperty("album")]
public string AlbumTitle { get; set; } public string AlbumTitle { get; set; }
[JsonProperty("artist")] [JsonProperty("artist")]
public string Artist { get; set; } public string Artist { get; set; }
[JsonProperty("year")] [JsonProperty("year")]
public int? Year { get; set; } public int? Year { get; set; }
[JsonProperty("genre")] [JsonProperty("genre")]
public string Genre { get; set; } public string Genre { get; set; }
[JsonProperty("duration")] [JsonProperty("duration")]
public int Duration { get; set; } public int Duration { get; set; }
[JsonProperty("filename")] [JsonProperty("filename")]
public string Filename { get; set; } public string Filename { get; set; }
[JsonProperty("song_path")] [JsonProperty("song_path")]
public string SongPath { get; set; } public string SongPath { get; set; }
[JsonIgnore] [JsonIgnore]
public Album Album { get; set; } public Album Album { get; set; }
[JsonIgnore] [JsonIgnore]
public int? AlbumId { get; set; } public int? AlbumId { get; set; }
[JsonIgnore] [JsonIgnore]
public Artist SongArtist { get; set; } public Artist SongArtist { get; set; }
[JsonIgnore] [JsonIgnore]
public int? ArtistId { get; set; } public int? ArtistId { get; set; }
[JsonIgnore] [JsonIgnore]
public Genre SongGenre { get; set; } public Genre SongGenre { get; set; }
[JsonIgnore] [JsonIgnore]
public int? GenreId { get; set; } public int? GenreId { get; set; }
[JsonIgnore] [JsonIgnore]
public Year SongYear { get; set; } public Year SongYear { get; set; }
[JsonIgnore] [JsonIgnore]
public int? YearId { get; set; } public int? YearId { get; set; }
[JsonIgnore] [JsonIgnore]
public CoverArt SongCoverArt { get; set; } public CoverArt SongCoverArt { get; set; }
[JsonIgnore] [JsonIgnore]
public int? CoverArtId { get; set; } public int? CoverArtId { get; set; }
} }
} }
+2 -2
View File
@@ -6,7 +6,7 @@ namespace Icarus.Models
public class SongData public class SongData
{ {
public int Id { get; set; } public int Id { get; set; }
public byte[] Data { get; set; } public byte[] Data { get; set; }
public int SongId { get; set; } public int SongId { get; set; }
} }
} }
+3 -3
View File
@@ -7,8 +7,8 @@ namespace Icarus.Models
public class SongResult public class SongResult
{ {
[JsonProperty("message")] [JsonProperty("message")]
public string Message { get; set; } public string Message { get; set; }
[JsonProperty("song_title")] [JsonProperty("song_title")]
public string SongTitle { get; set; } public string SongTitle { get; set; }
} }
} }
+5 -6
View File
@@ -9,26 +9,25 @@ namespace Icarus.Models
[Table("User")] [Table("User")]
public class User public class User
{ {
[JsonProperty("id")] [JsonProperty("user_id")]
[Column("UserId")] [Column("UserID")]
[Key] [Key]
public int Id { get; set; } public int UserID { get; set; }
[JsonProperty("username")] [JsonProperty("username")]
public string Username { get; set; } public string Username { get; set; }
[JsonProperty("nickname")]
public string Nickname { get; set; }
[JsonProperty("password")] [JsonProperty("password")]
public string Password { get; set; } public string Password { get; set; }
[JsonProperty("email")] [JsonProperty("email")]
public string Email { get; set; } public string Email { get; set; }
[JsonProperty("phone")] [JsonProperty("phone")]
[Column("Phone")] [Column("Phone")]
public string PhoneNumber { get; set; } public string Phone { get; set; }
[JsonProperty("first_name")] [JsonProperty("first_name")]
public string Firstname { get; set; } public string Firstname { get; set; }
[JsonProperty("last_name")] [JsonProperty("last_name")]
public string Lastname { get; set; } public string Lastname { get; set; }
[JsonProperty("email_verified")] [JsonProperty("email_verified")]
[NotMapped]
public bool EmailVerified { get; set; } public bool EmailVerified { get; set; }
[JsonProperty("date_created")] [JsonProperty("date_created")]
public DateTime DateCreated { get; set; } public DateTime DateCreated { 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; }
}
}
+95
View File
@@ -0,0 +1,95 @@
CREATE DATABASE Icarus;
USE Icarus;
CREATE TABLE CoverArt (
CoverArtID INT NOT NULL AUTO_INCREMENT,
SongTitle TEXT NOT NULL,
ImagePath TEXT NOT NULL,
PRIMARY KEY (CoverArtID)
);
CREATE TABLE Album (
AlbumID INT NOT NULL AUTO_INCREMENT,
Title TEXT NOT NULL,
Artist TEXT NOT NULL,
Year INT NOT NULL,
PRIMARY KEY (AlbumID)
);
CREATE TABLE Artist (
ArtistID INT NOT NULL AUTO_INCREMENT,
Artist TEXT NOT NULL,
PRIMARY KEY (ArtistID)
);
CREATE TABLE Genre (
GenreID INT NOT NULL AUTO_INCREMENT,
Category TEXT NOT NULL,
PRIMARY KEY (GenreID)
);
CREATE TABLE Song (
SongID INT NOT NULL AUTO_INCREMENT,
Title TEXT NOT NULL,
Artist TEXT NOT NULL,
Album TEXT NOT NULL,
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,
DateCreated DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (SongID),
CONSTRAINT FK_Song_CoverArtID FOREIGN KEY (CoverArtID) REFERENCES CoverArt (CoverArtID),
CONSTRAINT FK_Song_ArtistID FOREIGN KEY (ArtistID) REFERENCES Artist (ArtistID),
CONSTRAINT FK_Song_AlbumID FOREIGN KEY (AlbumID) REFERENCES Album (AlbumID),
CONSTRAINT FK_Song_GenreID FOREIGN KEY (GenreID) REFERENCES Genre (GenreID)
);
CREATE TABLE User (
UserID INT NOT NULL AUTO_INCREMENT,
Firstname TEXT NOT NULL,
Lastname TEXT NOT NULL,
Email TEXT NOT NULL,
Phone TEXT NOT NULL,
Username TEXT NOT NULL,
Password TEXT NOT NULL,
DateCreated DATETIME DEFAULT CURRENT_TIMESTAMP,
Status TEXT DEFAULT 'Active',
LastLogin DATETIME NULL,
PRIMARY KEY (UserID)
);
CREATE TABLE Salt (
SaltID INT NOT NULL AUTO_INCREMENT,
Salt TEXT NOT NULL,
UserID INT NOT NULL,
PRIMARY KEY (SaltID),
CONSTRAINT FK_Salt_UserID FOREIGN KEY (UserID) REFERENCES User (UserID)
);
CREATE TABLE Token (
TokenID INT NOT NULL AUTO_INCREMENT,
AccessToken TEXT NOT NULL,
TokenType TEXT NOT NULL,
Expires DATETIME DEFAULT CURRENT_TIMESTAMP,
Issued DATETIME DEFAULT CURRENT_TIMESTAMP,
UserID INT NOT NULL,
PRIMARY KEY (TokenID),
CONSTRAINT FK_Token_UserID FOREIGN KEY (UserID) REFERENCES User (UserID)
);
+3 -1
View File
@@ -25,7 +25,7 @@ using NLog.Web.AspNetCore;
using Icarus.Authorization; using Icarus.Authorization;
using Icarus.Authorization.Handlers; using Icarus.Authorization.Handlers;
using Icarus.Database.Contexts; using Icarus.Database.Contexts;
using Icarus.Database.Repositories; // using Icarus.Database.Repositories;
namespace Icarus namespace Icarus
{ {
@@ -107,6 +107,7 @@ namespace Icarus
var connString = Configuration.GetConnectionString("DefaultConnection"); var connString = Configuration.GetConnectionString("DefaultConnection");
/**
services.Add(new ServiceDescriptor(typeof(SongRepository), services.Add(new ServiceDescriptor(typeof(SongRepository),
new SongRepository(connString))); new SongRepository(connString)));
@@ -127,6 +128,7 @@ namespace Icarus
services.Add(new ServiceDescriptor(typeof(UserRepository), services.Add(new ServiceDescriptor(typeof(UserRepository),
new UserRepository(connString))); new UserRepository(connString)));
*/
services.AddDbContext<SongContext>(options => options.UseMySQL(connString)); services.AddDbContext<SongContext>(options => options.UseMySQL(connString));
services.AddDbContext<AlbumContext>(options => options.UseMySQL(connString)); services.AddDbContext<AlbumContext>(options => options.UseMySQL(connString));