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
-1
View File
@@ -4,7 +4,6 @@ using System.IO;
using Icarus.Constants;
using Icarus.Controllers.Utilities;
using Icarus.Database.Repositories;
using Icarus.Models;
using Icarus.Types;
+44 -523
View File
@@ -8,29 +8,17 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Id3;
using Id3.Frames;
using MySql.Data;
using MySql.Data.MySqlClient;
using NLog;
using TagLib;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
using Icarus.Database.Repositories;
namespace Icarus.Controllers.Managers
{
public class SongManager : BaseManager
{
#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 string _connectionString;
private string _tempDirectoryRoot;
@@ -41,12 +29,6 @@ namespace Icarus.Controllers.Managers
#region Properties
public Song SongDetails
{
get => _song;
set => _song = value;
}
public string ArchiveDirectoryRoot
{
get => _archiveDirectoryRoot;
@@ -66,37 +48,31 @@ namespace Icarus.Controllers.Managers
#region Constructors
/**
public SongManager()
{
Initialize();
InitializeConnection();
}
*/
public SongManager(Song song)
{
Initialize();
InitializeConnection();
_song = song;
}
public SongManager(IConfiguration config)
{
_config = config;
Initialize();
InitializeConnection();
}
public SongManager(IConfiguration config, string tempDirectoryRoot)
{
_config = config;
_tempDirectoryRoot = tempDirectoryRoot;
Initialize();
InitializeConnection();
}
#endregion
#region Methods
public SongResult UpdateSong(Song song, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)
public SongResult UpdateSong(Song song)/**, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)*/
{
var result = new SongResult();
@@ -110,21 +86,18 @@ namespace Icarus.Controllers.Managers
var updatedSong = updateMetadata.UpdatedSongRecord;
var updatedAlbum = UpdateAlbumInDatabase(oldSongRecord, updatedSong, albumStore);
var updatedAlbum = UpdateAlbumInDatabase(oldSongRecord, updatedSong)
oldSongRecord.AlbumId = updatedAlbum.AlbumId;
var updatedArtist = UpdateArtistInDatabase(oldSongRecord, updatedSong, artistStore);
var updatedArtist = UpdateArtistInDatabase(oldSongRecord, updatedSong);
oldSongRecord.ArtistId = updatedArtist.ArtistId;
var updatedGenre = UpdateGenreInDatabase(oldSongRecord, updatedSong, genreStore);
var updatedGenre = UpdateGenreInDatabase(oldSongRecord, updatedSong);
Console.WriteLine($"Old Genre Id {oldSongRecord.GenreId}");
oldSongRecord.GenreId = updatedGenre.GenreId;
Console.WriteLine($"Updated Genre Id {updatedGenre.GenreId}");
var updatedYear = UpdateYearInDatabase(oldSongRecord, updatedSong, yearStore);
oldSongRecord.YearId = updatedYear.YearId;
UpdateSongInDatabase(ref oldSongRecord, ref updatedSong, songStore, ref result);
UpdateSongInDatabase(ref oldSongRecord, ref updatedSong, ref result);
DeleteEmptyDirectories(ref oldSongRecord, ref updatedSong);
}
@@ -160,10 +133,10 @@ namespace Icarus.Controllers.Managers
return successful;
}
public void DeleteSong(Song song, SongRepository songStore,
public void DeleteSong(Song song)/**, SongRepository songStore,
AlbumRepository albumStore, ArtistRepository artistStore,
GenreRepository genreStore, YearRepository yearStore,
CoverArtRepository coverStore)
CoverArtRepository coverStore)*/
{
try
{
@@ -180,9 +153,9 @@ namespace Icarus.Controllers.Managers
var coverArt = coverStore.GetCoverArt(song);
coverMgr.DeleteCoverArt(coverArt);
coverMgr.DeleteCoverArtFromDatabase(coverArt, coverStore);
DeleteSongFromDatabase(song, songStore, albumStore, artistStore,
genreStore, yearStore);
coverMgr.DeleteCoverArtFromDatabase(coverArt);
DeleteSongFromDatabase(song/**, songStore, albumStore, artistStore,
genreStore, yearStore*/);
}
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();
}
}
}
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,
public async Task SaveSongToFileSystem(IFormFile songFile/**, SongRepository songStore,
AlbumRepository albumStore, ArtistRepository artistStore,
GenreRepository genreStore, YearRepository yearStore,
CoverArtRepository coverArtStore)
CoverArtRepository coverArtStore*/)
{
try
{
@@ -388,10 +208,9 @@ namespace Icarus.Controllers.Managers
var coverMgr = new CoverArtManager(_config.GetValue<string>("CoverArtPath"));
var coverArt = coverMgr.SaveCoverArt(song);
coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt,
coverArtStore);
SaveSongToDatabase(song, songStore, albumStore, artistStore, genreStore,
yearStore);
coverMgr.SaveCoverArtToDatabase(ref song, ref coverArt);//,
SaveSongToDatabase(song);/**, songStore, albumStore, artistStore, genreStore,
yearStore);*/
}
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)
{
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)
{
@@ -587,23 +269,6 @@ namespace Icarus.Controllers.Managers
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)
{
@@ -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");
SaveAlbumToDatabase(ref song, albumStore);
SaveArtistToDatabase(ref song, artistStore);
SaveGenreToDatabase(ref song, genreStore);
SaveYearToDatabase(ref song, yearStore);
SaveAlbumToDatabase(ref song);//, albumStore);
SaveArtistToDatabase(ref song);//, artistStore);
SaveGenreToDatabase(ref song);//, genreStore);
var info = "Saving Song to DB";
Console.WriteLine(info);
_logger.Info(info);
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");
@@ -707,7 +350,7 @@ namespace Icarus.Controllers.Managers
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");
@@ -733,7 +376,7 @@ namespace Icarus.Controllers.Managers
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");
@@ -764,32 +407,7 @@ namespace Icarus.Controllers.Managers
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)
{
@@ -826,7 +444,7 @@ namespace Icarus.Controllers.Managers
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 oldAlbumTitle = oldSongRecord.AlbumTitle;
@@ -877,7 +495,7 @@ namespace Icarus.Controllers.Managers
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 oldArtistName = oldArtistRecord.Name;
@@ -922,7 +540,7 @@ namespace Icarus.Controllers.Managers
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 oldGenreName = oldGenreRecord.GenreName;
@@ -966,57 +584,13 @@ namespace Icarus.Controllers.Managers
return genreStore.GetGenre(existingGenreRecord);
}
}
private Year UpdateYearInDatabase(Song oldSongRecord, Song newSongRecord, YearRepository yearStore)
{
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,
private void UpdateSongInDatabase(ref Song oldSongRecord, ref Song newSongRecord, /**SongRepository songStore,*/
ref SongResult result)
{
var updatedSongRecord = new Song
{
Id = oldSongRecord.Id,
SongID = oldSongRecord.SongID,
Title = oldSongRecord.Title,
Artist = oldSongRecord.Artist,
AlbumTitle = oldSongRecord.AlbumTitle,
@@ -1111,19 +685,20 @@ namespace Icarus.Controllers.Managers
result.SongTitle = updatedSongRecord.Title;
}
private void DeleteSongFromDatabase(Song song, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)
private void DeleteSongFromDatabase(Song song)/**, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore, GenreRepository genreStore, YearRepository yearStore)*/
{
_logger.Info("Starting process to delete records related to the song from the database");
DeleteAlbumFromDatabase(song, albumStore);
DeleteArtistFromDatabase(song, artistStore);
DeleteGenreFromDatabase(song, genreStore);
DeleteYearFromDatabase(song, yearStore);
DeleteAlbumFromDatabase(song);//, albumStore);
DeleteArtistFromDatabase(song);//, artistStore);
DeleteGenreFromDatabase(song);//, genreStore);
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))
{
@@ -1136,7 +711,7 @@ namespace Icarus.Controllers.Managers
if (album.SongCount <= 1)
albumStore.DeleteAlbum(album);
}
private void DeleteArtistFromDatabase(Song song, ArtistRepository artistStore)
private void DeleteArtistFromDatabase(Song song)//, ArtistRepository artistStore)
{
if (!artistStore.DoesArtistExist(song))
{
@@ -1149,7 +724,7 @@ namespace Icarus.Controllers.Managers
if (artist.SongCount <= 1)
artistStore.DeleteArtist(artist);
}
private void DeleteGenreFromDatabase(Song song, GenreRepository genreStore)
private void DeleteGenreFromDatabase(Song song)//, GenreRepository genreStore)
{
if (!genreStore.DoesGenreExist(song))
{
@@ -1162,62 +737,8 @@ namespace Icarus.Controllers.Managers
if (genre.SongCount <= 1)
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
}
}
-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
}
}
+2 -1
View File
@@ -8,7 +8,8 @@ using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Database.Repositories;
using Icarus.Database.Contexts;
// using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
+5 -5
View File
@@ -10,7 +10,7 @@ using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Repositories;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
@@ -41,12 +41,12 @@ namespace Icarus.Controllers.V1
user.Password = pe.HashPassword(user);
user.EmailVerified = false;
UserRepository context = HttpContext.RequestServices
.GetService(typeof(UserRepository)) as UserRepository;
var context = new UserContext(_config.GetConnectionString("DefaultConnection"));
try
{
context.SaveUser(user);
context.Add(user);
context.SaveChanges();
}
catch (Exception ex)
{
@@ -61,7 +61,7 @@ namespace Icarus.Controllers.V1
Username = user.Username
};
if (context.DoesUserExist(user))
if (context.Users.FirstOrDefault(sng => sng.Username.Equals(user.Username)) != null)
{
registerResult.Message = "Successful registration";
registerResult.SuccessfullyRegistered = true;
+2 -41
View File
@@ -14,7 +14,6 @@ using Microsoft.Extensions.Logging;
using Icarus.Controllers.Managers;
using Icarus.Models;
using Icarus.Database.Contexts;
using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
@@ -23,12 +22,6 @@ namespace Icarus.Controllers.V1
public class SongDataController : ControllerBase
{
#region Fields
private SongRepository _songRepository;
private AlbumRepository _albumRepository;
private ArtistRepository _artistRepository;
private GenreRepository _genreRepository;
private YearRepository _yearRepository;
private CoverArtRepository _coverArtRepository;
private IConfiguration _config;
private ILogger<SongDataController> _logger;
private SongManager _songMgr;
@@ -50,33 +43,6 @@ namespace Icarus.Controllers.V1
}
#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}")]
@@ -84,7 +50,6 @@ namespace Icarus.Controllers.V1
[Authorize("download:songs")]
public async Task<IActionResult> Get(int id)
{
Initialize();
var songMetaData = _songRepository.GetSong(id);
SongData song = await _songMgr.RetrieveSong(songMetaData);
@@ -98,8 +63,6 @@ namespace Icarus.Controllers.V1
{
try
{
Initialize();
Console.WriteLine("Uploading song...");
_logger.LogInformation("Uploading song...");
@@ -127,10 +90,8 @@ namespace Icarus.Controllers.V1
[Authorize("delete:songs")]
public IActionResult Delete(int id)
{
Initialize();
var songMetaData = new Song{ Id = id };
Console.WriteLine($"Id {songMetaData.Id}");
var songMetaData = new Song{ SongID = id };
Console.WriteLine($"Id {songMetaData.SongID}");
songMetaData = _songRepository.GetSong(songMetaData);
if (string.IsNullOrEmpty(songMetaData.Title))
+7 -5
View File
@@ -9,10 +9,11 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Icarus.Models;
using Icarus.Database.Repositories;
using Icarus.Database.Contexts;
namespace Icarus.Controllers.V1
{
@@ -22,6 +23,7 @@ namespace Icarus.Controllers.V1
{
#region Fields
private ILogger<SongStreamController> _logger;
private IConfiguration _config;
#endregion
@@ -30,9 +32,10 @@ namespace Icarus.Controllers.V1
#region Constructor
public SongStreamController(ILogger<SongStreamController> logger)
public SongStreamController(ILogger<SongStreamController> logger, IConfiguration config)
{
_logger = logger;
_config = config;
}
#endregion
@@ -42,10 +45,9 @@ namespace Icarus.Controllers.V1
[Authorize("stream:songs")]
public async Task<IActionResult> Get(int id)
{
var songStore= HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
var context = new SongContext(_config.GetConnectionString("DefaultConnection"));
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);
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
}
}
+10
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
@@ -15,11 +16,20 @@ namespace Icarus.Database.Contexts
public DbSet<Album> Albums { get; set; }
public AlbumContext(DbContextOptions<AlbumContext> options) : base(options) { }
public AlbumContext(string connString) : base(new DbContextOptionsBuilder<AlbumContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Album>()
.ToTable("Album");
}
public bool DoesRecordExist(Album album)
{
return Albums.FirstOrDefault(alb => alb.AlbumId == album.AlbumId) != null ? true : false;
}
}
}
+11
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
@@ -15,11 +16,21 @@ namespace Icarus.Database.Contexts
public DbSet<Artist> Artists { get; set; }
public ArtistContext(DbContextOptions<ArtistContext> options) : base (options) { }
public ArtistContext(string connString) : base(new DbContextOptionsBuilder<ArtistContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Artist>()
.ToTable("Artist");
}
public bool DoesRecordExist(Artist artist)
{
return Artists.FirstOrDefault(arst => arst.ArtistId == artist.ArtistId) != null ? true : false;
}
}
}
+11
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
@@ -15,11 +16,21 @@ namespace Icarus.Database.Contexts
public DbSet<CoverArt> CoverArtImages { get; set; }
public CoverArtContext(DbContextOptions<CoverArtContext> options) : base(options) { }
public CoverArtContext(string connString) : base(new DbContextOptionsBuilder<CoverArtContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<CoverArt>()
.ToTable("CoverArt");
}
public bool DoesRecordExist(CoverArt cover)
{
return CoverArtImages.FirstOrDefault(cov => cov.CoverArtId == cover.CoverArtId) != null ? true : false;
}
}
}
+11
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
@@ -14,11 +15,21 @@ namespace Icarus.Database.Contexts
{
public DbSet<Genre> Genres { get; set; }
public GenreContext(DbContextOptions<GenreContext> options) : base(options) { }
public GenreContext(string connString) : base(new DbContextOptionsBuilder<GenreContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Genre>()
.ToTable("Genre");
}
public bool DoesRecordExist(Genre genre)
{
return Genres.FirstOrDefault(gnr => gnr.GenreId == genre.GenreId) != null ? true : false;
}
}
}
+12
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
@@ -14,6 +15,11 @@ namespace Icarus.Database.Contexts
{
public DbSet<Song> Songs { get; set; }
public SongContext(string connString) : base(new DbContextOptionsBuilder<SongContext>()
.UseMySQL(connString).Options)
{
}
public SongContext(DbContextOptions<SongContext> options) : base(options) { }
@@ -71,5 +77,11 @@ namespace Icarus.Database.Contexts
.Property(s => s.CoverArtId)
.IsRequired(false);
}
public bool DoesRecordExist(Song song)
{
return Songs.FirstOrDefault(sng => sng.SongID == song.SongID) != null ? true : false;
}
}
}
+11
View File
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using MySql.Data;
@@ -16,6 +17,10 @@ namespace Icarus.Database.Contexts
public UserContext(DbContextOptions<UserContext> options) : base(options) { }
public UserContext(string connString) : base(new DbContextOptionsBuilder<UserContext>()
.UseMySQL(connString).Options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -26,5 +31,11 @@ namespace Icarus.Database.Contexts
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");
}
}
}
+2 -2
View File
@@ -7,8 +7,8 @@ namespace Icarus.Models
{
public class Song
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("song_id")]
public int SongID { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("album")]
+5 -6
View File
@@ -9,26 +9,25 @@ namespace Icarus.Models
[Table("User")]
public class User
{
[JsonProperty("id")]
[Column("UserId")]
[JsonProperty("user_id")]
[Column("UserID")]
[Key]
public int Id { get; set; }
public int UserID { 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")]
[Column("Phone")]
public string PhoneNumber { get; set; }
public string Phone { get; set; }
[JsonProperty("first_name")]
public string Firstname { get; set; }
[JsonProperty("last_name")]
public string Lastname { get; set; }
[JsonProperty("email_verified")]
[NotMapped]
public bool EmailVerified { get; set; }
[JsonProperty("date_created")]
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.Handlers;
using Icarus.Database.Contexts;
using Icarus.Database.Repositories;
// using Icarus.Database.Repositories;
namespace Icarus
{
@@ -107,6 +107,7 @@ namespace Icarus
var connString = Configuration.GetConnectionString("DefaultConnection");
/**
services.Add(new ServiceDescriptor(typeof(SongRepository),
new SongRepository(connString)));
@@ -127,6 +128,7 @@ namespace Icarus
services.Add(new ServiceDescriptor(typeof(UserRepository),
new UserRepository(connString)));
*/
services.AddDbContext<SongContext>(options => options.UseMySQL(connString));
services.AddDbContext<AlbumContext>(options => options.UseMySQL(connString));