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;
+51 -530
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)
{
_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)
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
}
}
+79 -79
View File
@@ -13,18 +13,18 @@ namespace Icarus.Controllers.Utilities
public class SongCompression
{
#region Fields
string _compressedSongFilename;
string _tempDirectory;
string _compressedSongFilename;
string _tempDirectory;
byte[] _uncompressedSong;
#endregion
#region Propterties
public string CompressedSongFilename
{
get => _compressedSongFilename;
set => _compressedSongFilename = value;
}
public string CompressedSongFilename
{
get => _compressedSongFilename;
set => _compressedSongFilename = value;
}
#endregion
@@ -44,86 +44,86 @@ namespace Icarus.Controllers.Utilities
#region Methods
public async Task<SongData> RetrieveCompressedSong(Song song)
{
SongData songData = new SongData();
try
{
var archivePath = RetrieveCompressesSongPath(song);
Console.WriteLine($"Compressed song saved to: {archivePath}");
songData.Data = System.IO.File.ReadAllBytes(archivePath);
}
catch(Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error ocurred: \n{exMsg}");
}
return songData;
}
public string RetrieveCompressesSongPath(Song songDetails)
{
string tmpZipFilePath = _tempDirectory + songDetails.Filename;
try
{
using (ZipFile zip = new ZipFile())
public async Task<SongData> RetrieveCompressedSong(Song song)
{
zip.AddFile(songDetails.SongPath);
zip.Save(tmpZipFilePath);
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;
}
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"))
{
_compressedSongFilename = StripMP3Extension(songDetails.Filename);
}
// 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 tmpZipFilePath;
}
// Method not being used
public byte[] CompressedSong(byte[] uncompressedSong)
{
byte[] compressedSong = null;
try
{
Console.WriteLine("Song has been successfully compressed");
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine("An error ocurred:");
Console.WriteLine(exMsg);
}
return compressedSong;
}
return compressedSong;
}
string StripMP3Extension(string filename)
{
Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1;
var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4);
stripped += ".zip";
Console.WriteLine($"After {stripped}");
string StripMP3Extension(string filename)
{
Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1;
var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4);
stripped += ".zip";
Console.WriteLine($"After {stripped}");
return stripped;
}
return stripped;
}
#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
}
}