From c9b1abdbdbe72269bb24a6bcc98301a1e54bdcc0 Mon Sep 17 00:00:00 2001 From: amazing-username Date: Sun, 14 Apr 2019 18:53:04 +0000 Subject: [PATCH] Refactoring and cleanup --- Controllers/Managers/SongManager.cs | 573 +++++++++---------- Controllers/SongCompressedDataControllers.cs | 47 +- Controllers/SongController.cs | 39 +- Controllers/SongDataController.cs | 71 +-- Controllers/Utilities/SongCompression.cs | 124 ++-- Models/MusicStoreContext.cs | 141 +++++ Models/Song.cs | 3 + Startup.cs | 5 + appsettings.Development.json | 8 +- appsettings.json | 8 +- 10 files changed, 596 insertions(+), 423 deletions(-) create mode 100644 Models/MusicStoreContext.cs diff --git a/Controllers/Managers/SongManager.cs b/Controllers/Managers/SongManager.cs index a9c5a98..bfc6b66 100644 --- a/Controllers/Managers/SongManager.cs +++ b/Controllers/Managers/SongManager.cs @@ -19,193 +19,192 @@ using Icarus.Controllers.Utilities; namespace Icarus.Controllers.Managers { - public class SongManager - { - #region Fields + public class SongManager + { + #region Fields private MySqlConnection _conn; private MySqlCommand _cmd; private MySqlDataAdapter _dataDump; private DataTable _results; - private List _songs; - private Song _song; - private IConfiguration _config; - private string _connectionString; - private string _tempDirectoryRoot; - private string _archiveDirectoryRoot; - private string _compressedSongFilename; - #endregion + private List _songs; + private Song _song; + private IConfiguration _config; + private string _connectionString; + private string _tempDirectoryRoot; + private string _archiveDirectoryRoot; + private string _compressedSongFilename; + #endregion - #region Properties - public Song SongDetails - { - get => _song; - set => _song = value; - } + #region Properties + public Song SongDetails + { + get => _song; + set => _song = value; + } - public string ArchiveDirectoryRoot - { - get => _archiveDirectoryRoot; - set => _archiveDirectoryRoot = value; - } - public string CompressedSongFilename - { - get => _compressedSongFilename; - set => _compressedSongFilename = value; - } - #endregion + public string ArchiveDirectoryRoot + { + get => _archiveDirectoryRoot; + set => _archiveDirectoryRoot = value; + } + public string CompressedSongFilename + { + get => _compressedSongFilename; + set => _compressedSongFilename = value; + } + #endregion - #region Constructors - public SongManager() - { - Initialize(); + #region Constructors + public SongManager() + { + Initialize(); InitializeConnection(); - } + } - public SongManager(Song song) - { - Initialize(); + public SongManager(Song song) + { + Initialize(); InitializeConnection(); _song = song; - } - public SongManager(IConfiguration config) - { - _config = config; - Initialize(); + } + public SongManager(IConfiguration config) + { + _config = config; + Initialize(); InitializeConnection(); - } - public SongManager(IConfiguration config, string tempDirectoryRoot) - { - _config = config; - _tempDirectoryRoot = tempDirectoryRoot; - Initialize(); + } + public SongManager(IConfiguration config, string tempDirectoryRoot) + { + _config = config; + _tempDirectoryRoot = tempDirectoryRoot; + Initialize(); InitializeConnection(); - } - #endregion + } + #endregion - #region Methods - public void SaveSongDetails() + #region Methods + public void SaveSongDetails() + { + try + { + using (MySqlConnection conn = new MySqlConnection(_connectionString)) { - try - { - using (MySqlConnection conn = new MySqlConnection(_connectionString)) - { - conn.Open(); - string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + - "Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + - "@Duration, @Filename, @SongPath)"; - using (MySqlCommand cmd = new MySqlCommand(query, conn)) - { - cmd.Parameters.AddWithValue("@Title", _song.Title); - cmd.Parameters.AddWithValue("@Album", _song.Album); - 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); + conn.Open(); + string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + + "Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + + "@Duration, @Filename, @SongPath)"; + using (MySqlCommand cmd = new MySqlCommand(query, conn)) + { + cmd.Parameters.AddWithValue("@Title", _song.Title); + cmd.Parameters.AddWithValue("@Album", _song.Album); + 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}"); - } + cmd.ExecuteNonQuery(); + } } - public void SaveSongDetails(Song song) + } + 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)) { - try - { - using (MySqlConnection conn = new MySqlConnection(_connectionString)) - { - conn.Open(); - string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + - ", Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + - "@Duration, @Filename, @SongPath)"; - using (MySqlCommand cmd = new MySqlCommand(query, conn)) - { - cmd.Parameters.AddWithValue("@Title", song.Title); - cmd.Parameters.AddWithValue("@Album", song.Album); - 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); + conn.Open(); + string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + + ", Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + + "@Duration, @Filename, @SongPath)"; + using (MySqlCommand cmd = new MySqlCommand(query, conn)) + { + cmd.Parameters.AddWithValue("@Title", song.Title); + cmd.Parameters.AddWithValue("@Album", song.Album); + 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}"); - } + cmd.ExecuteNonQuery(); + } } - public async Task SaveSong(SongData songData) + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An Error Occurred: {exMsg}"); + } + } + + public async Task SaveSong(SongData songData) + { + try + { + using (MySqlConnection conn = new MySqlConnection(_connectionString)) { - 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); + 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}"); - } + cmd.ExecuteNonQuery(); + } } - public async Task SaveSongToFileSystem(IFormFile song) + } + catch(Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error occurred: {exMsg}"); + } + } + public async Task SaveSongToFileSystem(IFormFile song) + { + try + { + var filePath = Path.Combine(_tempDirectoryRoot, song.FileName); + 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)) { - try - { - var filePath = Path.Combine(_tempDirectoryRoot, song.FileName); - await SaveSongToFileSystemTemp(song, filePath); - System.IO.File.Delete(filePath); + await song.CopyToAsync(fileStream); + _song.SongPath = 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; - SaveSongDetails(); - - - Console.WriteLine($"Writing song to the directory: {filePath}"); - Console.WriteLine("Song successfully saved"); - } - } - catch (Exception ex) - { - var exMsg = ex.Message; - Console.WriteLine($"An error occurred: {exMsg}"); - } + Console.WriteLine($"Writing song to the directory: {filePath}"); + Console.WriteLine("Song successfully saved"); } + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error occurred: {exMsg}"); + } + } public async Task> RetrieveAllSongDetails() { @@ -237,160 +236,150 @@ namespace Icarus.Controllers.Managers return _songs; } - public async Task RetrieveSongDetails(int id) + public async Task RetrieveSongDetails(int id) + { + DataTable results = new DataTable(); + + try + { + using (MySqlConnection conn = new MySqlConnection(_connectionString)) { - DataTable results = new DataTable(); + conn.Open(); + string query = "SELECT * FROM Songs WHERE Id=@Id"; + using (MySqlCommand cmd = new MySqlCommand(query, conn)) + { + cmd.Parameters.AddWithValue("@Id", id); + + cmd.ExecuteNonQuery(); - try + using (MySqlDataAdapter dataDump = new MySqlDataAdapter(cmd)) { - 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); - } - } - } + 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 RetrieveSong(int id) - { - SongData song = new SongData(); - try - { - _song = await RetrieveSongDetails(id); - song = RetrieveSongFromFileSystem(_song); - } - catch (Exception ex) - { - var exMsg = ex.Message; - Console.WriteLine($"An error occurred: {exMsg}"); - } + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error occurred"); + } + + DataRow row = results.Rows[0]; - return song; - } - public async Task RetrieveCompressedSong(int id) - { - SongData song = new SongData(); - try - { - _song = await RetrieveSongDetails(id); - Console.WriteLine("Retrieved details of song"); + return new Song + { + Id = Int32.Parse(row["Id"].ToString()), + Filename = row["Filename"].ToString(), + SongPath = row["SongPath"].ToString() + }; + } + public async Task RetrieveSong(int id) + { + SongData song = new SongData(); + try + { + _song = await RetrieveSongDetails(id); + song = await RetrieveSongFromFileSystem(_song); + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error occurred: {exMsg}"); + } - song = RetrieveSongFromFileSystem(_song); - Console.WriteLine("Retrieved song from filesystem"); + return song; + } + public async Task RetrieveSong(Song songMetaData) + { + SongData song = new SongData(); + try + { + Console.WriteLine("Fetching song from filesystem"); + song = await RetrieveSongFromFileSystem(songMetaData); + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error occurred: {exMsg}"); + } - SongCompression compressed = new SongCompression(_archiveDirectoryRoot); - Console.WriteLine("SongCompression Initialized"); - - var compressedPath = compressed.RetrieveCompressesSongPath(_song); - Console.WriteLine($"Path of compressed song: {compressedPath}"); - - song.Data = System.IO.File.ReadAllBytes(compressedPath); - - _compressedSongFilename = compressed.CompressedSongFilename; - } - catch (Exception ex) - { - var exMsg = ex.Message; - Console.WriteLine($"An error occurred: {exMsg}"); - } - return song; - } + return song; + } - Song RetrieveMetaData(string filePath) - { - string title, artist, album, genre; - int year, duration; + Song RetrieveMetaData(string filePath) + { + string title, artist, album, genre; + int year, duration; - TagLib.File tfile = TagLib.File.Create(filePath); - duration = (int)tfile.Properties.Duration.TotalSeconds; + TagLib.File tfile = TagLib.File.Create(filePath); + duration = (int)tfile.Properties.Duration.TotalSeconds; - using (var mp3 = new Mp3(filePath)) - { - Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); - title = tag.Title; - artist = tag.Artists; - album = tag.Album; - genre = "Not Implemented"; - year = (int)tag.Year; - Console.WriteLine("Title: {0}", title); - Console.WriteLine("Artist: {0}", artist); - Console.WriteLine("Album: {0}", album); - Console.WriteLine("Genre: {0}", genre); - Console.WriteLine("Year: {0}", year); - Console.WriteLine("Duration: {0}", duration); - } + using (var mp3 = new Mp3(filePath)) + { + Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); + title = tag.Title; + artist = tag.Artists; + album = tag.Album; + genre = "Not Implemented"; + year = (int)tag.Year; + Console.WriteLine("Title: {0}", title); + Console.WriteLine("Artist: {0}", artist); + Console.WriteLine("Album: {0}", album); + Console.WriteLine("Genre: {0}", genre); + Console.WriteLine("Year: {0}", year); + Console.WriteLine("Duration: {0}", duration); + } - _song = new Song - { - Title = title, - Artist = artist, - Album = album, - Year = year, - Genre = genre, - Duration = duration, - SongPath = filePath - }; + _song = new Song + { + Title = title, + Artist = artist, + Album = album, + Year = year, + Genre = genre, + Duration = duration, + SongPath = filePath + }; - return _song; - } + return _song; + } - SongData RetrieveSongFromFileSystem(Song details) - { + async Task RetrieveSongFromFileSystem(Song details) + { byte[] uncompressedSong = System.IO.File.ReadAllBytes(details.SongPath); - return new SongData - { - Data = uncompressedSong - }; - } + return new SongData + { + Data = uncompressedSong + }; + } - async Task SaveSongToFileSystemTemp(IFormFile song, string filePath) - { - using (var fileStream = new FileStream(filePath, FileMode.Create)) - { - await song.CopyToAsync(fileStream); - _song = RetrieveMetaData(filePath); - _song.Filename = song.FileName; - } - } + async Task SaveSongToFileSystemTemp(IFormFile song, string filePath) + { + using (var fileStream = new FileStream(filePath, FileMode.Create)) + { + await song.CopyToAsync(fileStream); + _song = RetrieveMetaData(filePath); + _song.Filename = song.FileName; + } + } - void Initialize() - { - try - { - _connectionString = _config.GetConnectionString("IcarusDev"); - } - catch (Exception ex) - { - Console.WriteLine($"Error Occurred: {ex.Message}"); - } + void Initialize() + { + try + { + _connectionString = _config.GetConnectionString("IcarusDev"); + } + catch (Exception ex) + { + Console.WriteLine($"Error Occurred: {ex.Message}"); + } - } + } void InitializeConnection() { _conn = new MySqlConnection(_connectionString); @@ -441,6 +430,6 @@ namespace Icarus.Controllers.Managers _songs.Add(song); } } - #endregion - } + #endregion + } } diff --git a/Controllers/SongCompressedDataControllers.cs b/Controllers/SongCompressedDataControllers.cs index 49847fd..f50a554 100644 --- a/Controllers/SongCompressedDataControllers.cs +++ b/Controllers/SongCompressedDataControllers.cs @@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Icarus.Controllers.Managers; +using Icarus.Controllers.Utilities; using Icarus.Models; namespace Icarus.Controllers @@ -20,41 +21,41 @@ namespace Icarus.Controllers { #region Fields private IConfiguration _config; - private SongManager _songMgr; - private string _songTempDir; - private string _archiveDir; - #endregion + private SongManager _songMgr; + private string _songTempDir; + private string _archiveDir; + #endregion - #region Properties - #endregion + #region Properties + #endregion - #region Constructor - public SongCompressedDataController(IConfiguration config) - { - _config = config; - _songTempDir = _config.GetValue("TemporaryMusicPath"); - _archiveDir = _config.GetValue("ArchivePath"); - _songMgr = new SongManager(config, _songTempDir); - _songMgr.ArchiveDirectoryRoot = _archiveDir; - } - #endregion + #region Constructor + public SongCompressedDataController(IConfiguration config) + { + _config = config; + _songTempDir = _config.GetValue("TemporaryMusicPath"); + _archiveDir = _config.GetValue("ArchivePath"); + } + #endregion - #region API Routes + #region API Routes [HttpGet("{id}")] public async Task Get(int id) { - SongData song = new SongData(); + MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext; - Console.WriteLine($"Archive directory root: {_archiveDir}"); + SongCompression cmp = new SongCompression(_archiveDir); + + Console.WriteLine($"Archive directory root: {_archiveDir}"); - Console.WriteLine("Starting process of retrieving comrpessed song"); - song = await _songMgr.RetrieveCompressedSong(id); + Console.WriteLine("Starting process of retrieving comrpessed song"); + SongData song = await cmp.RetrieveCompressedSong(context.GetSong(id)); - return File(song.Data, "application/x-msdownload", _songMgr.CompressedSongFilename); + return File(song.Data, "application/x-msdownload", cmp.CompressedSongFilename); } - #endregion + #endregion } } diff --git a/Controllers/SongController.cs b/Controllers/SongController.cs index 8418e34..3cf130a 100644 --- a/Controllers/SongController.cs +++ b/Controllers/SongController.cs @@ -16,30 +16,35 @@ namespace Icarus.Controllers [ApiController] public class SongController : ControllerBase { - #region Fields - private IConfiguration _config; - private SongManager _songMgr; - #endregion + #region Fields + private IConfiguration _config; + private SongManager _songMgr; + #endregion - #region Properties - #endregion + #region Properties + #endregion - #region Constructor - public SongController(IConfiguration config) - { - _config = config; - _songMgr = new SongManager(config); - } - #endregion + #region Constructor + public SongController(IConfiguration config) + { + _config = config; + _songMgr = new SongManager(config); + } + #endregion [HttpGet] public ActionResult> Get() { - List songs = new List(); + List songs = new List(); songs = _songMgr.RetrieveAllSongDetails().Result; + Console.WriteLine("Attemtping to retrieve songs"); + + MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext; + + songs = context.GetAllSongs(); return songs; @@ -48,7 +53,8 @@ namespace Icarus.Controllers [HttpGet("{id}")] public ActionResult Get(int id) { - Song song = _songMgr.RetrieveSongDetails(id).Result; + MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext; + Song song = context.GetSong(id); return song; } @@ -56,7 +62,8 @@ namespace Icarus.Controllers [HttpPost] public void Post([FromBody] Song song) { - _songMgr.SaveSongDetails(song); + // TODO: Replace this call with the one in the MusicContext class + _songMgr.SaveSongDetails(song); } [HttpPut("{id}")] diff --git a/Controllers/SongDataController.cs b/Controllers/SongDataController.cs index 03099e4..4b2a604 100644 --- a/Controllers/SongDataController.cs +++ b/Controllers/SongDataController.cs @@ -20,29 +20,29 @@ namespace Icarus.Controllers { #region Fields private IConfiguration _config; - private SongManager _songMgr; - private string _songTempDir; - #endregion + private SongManager _songMgr; + private string _songTempDir; + #endregion - #region Properties - #endregion + #region Properties + #endregion - #region Constructor - public SongDataController(IConfiguration config) - { - _config = config; - _songTempDir = _config.GetValue("TemporaryMusicPath"); - _songMgr = new SongManager(config, _songTempDir); - } - #endregion + #region Constructor + public SongDataController(IConfiguration config) + { + _config = config; + _songTempDir = _config.GetValue("TemporaryMusicPath"); + _songMgr = new SongManager(config, _songTempDir); + } + #endregion [HttpGet] public ActionResult> Get() { - List songs = new List(); + List songs = new List(); return songs; @@ -51,33 +51,38 @@ namespace Icarus.Controllers [HttpGet("{id}")] public async Task Get(int id) { - SongData song = new SongData(); + MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext; + var songMetaData = context.GetSong(id); - song = await _songMgr.RetrieveSong(id); + SongData song = await _songMgr.RetrieveSong(songMetaData); - return File(song.Data, "application/x-msdownload", _songMgr.SongDetails.Filename); + return File(song.Data, "application/x-msdownload", songMetaData.Filename); } [HttpPost] public async Task Post([FromForm(Name = "file")] List songData) { - try - { - Console.WriteLine("Uploading song..."); + try + { + MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext; + Console.WriteLine("Uploading song..."); - var uploads = _songTempDir; - Console.WriteLine($"Song Root Path {uploads}"); - foreach (var sng in songData) - { - if (sng.Length > 0) { - await _songMgr.SaveSongToFileSystem(sng); - } - } - } - catch (Exception ex) - { - Console.WriteLine($"An error occurred: {ex.Message}"); - } + var uploads = _songTempDir; + Console.WriteLine($"Song Root Path {uploads}"); + foreach (var sng in songData) + { + if (sng.Length > 0) { + await _songMgr.SaveSongToFileSystem(sng); + var song = _songMgr.SongDetails; + context.SaveSong(song); + Console.WriteLine("Song successfully saved"); + } + } + } + catch (Exception ex) + { + Console.WriteLine($"An error occurred: {ex.Message}"); + } } [HttpPut("{id}")] diff --git a/Controllers/Utilities/SongCompression.cs b/Controllers/Utilities/SongCompression.cs index bcf7ccb..25f73e6 100644 --- a/Controllers/Utilities/SongCompression.cs +++ b/Controllers/Utilities/SongCompression.cs @@ -2,6 +2,8 @@ using System; using System.IO; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; + using Ionic.Zip; using Icarus.Models; @@ -11,18 +13,19 @@ namespace Icarus.Controllers.Utilities public class SongCompression { #region Fields - string _compressedSongFilename; - string _tempDirectory; + string _archiveDirectory; + 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 @@ -30,10 +33,10 @@ namespace Icarus.Controllers.Utilities public SongCompression() { } - public SongCompression(string tempDirectory) - { - _tempDirectory = tempDirectory; - } + public SongCompression(string tempDirectory) + { + _tempDirectory = tempDirectory; + } public SongCompression(byte[] uncompressedSong) { _uncompressedSong = uncompressedSong; @@ -42,41 +45,60 @@ namespace Icarus.Controllers.Utilities #region Methods - public string RetrieveCompressesSongPath(Song songDetails) + public async Task 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()) { - 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; + 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); + } - // Method not being used + if (songDetails.Filename.Contains(".mp3")) + { + _compressedSongFilename = StripMP3Extension(songDetails.Filename); + } + + return tmpZipFilePath; + } + + // Method not being used public byte[] CompressedSong(byte[] uncompressedSong) { byte[] compressedSong = null; try { - Console.WriteLine("Song has been successfully compressed"); + Console.WriteLine("Song has been successfully compressed"); } catch (Exception ex) { @@ -89,20 +111,20 @@ namespace Icarus.Controllers.Utilities } - 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 } } diff --git a/Models/MusicStoreContext.cs b/Models/MusicStoreContext.cs new file mode 100644 index 0000000..14ec5b7 --- /dev/null +++ b/Models/MusicStoreContext.cs @@ -0,0 +1,141 @@ +using MySql.Data.MySqlClient; +using System; +using System.Collections.Generic; + +namespace Icarus.Models +{ + public class MusicStoreContext + { + public string ConnectionString { get; set; } + + public MusicStoreContext(string connectionString) + { + this.ConnectionString = connectionString; + } + + public void InsertSongDetails() + { + } + + + public void SaveSong(Song song) + { + try + { + using (MySqlConnection conn = GetConnection()) + { + conn.Open(); + string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + + "Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + + "@Duration, @Filename, @SongPath)"; + using (MySqlCommand cmd = new MySqlCommand(query, conn)) + { + cmd.Parameters.AddWithValue("@Title", song.Title); + cmd.Parameters.AddWithValue("@Album", song.Album); + 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:\n{exMsg}"); + } + } + + public List GetAllSongs() + { + List songs = new List(); + try + { + using (MySqlConnection conn = GetConnection()) + { + conn.Open(); + var query = "SELECT * FROM Songs"; + MySqlCommand cmd = new MySqlCommand(query, conn); + using (var reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + songs.Add(new Song + { + Id = Convert.ToInt32(reader["Id"]), + Title = reader["Title"].ToString(), + Album = reader["Album"].ToString(), + Artist = reader["Artist"].ToString(), + Year = Convert.ToInt32(reader["Year"]), + Genre = reader["Genre"].ToString(), + Duration = Convert.ToInt32(reader["Duration"]), + Filename = reader["Filename"].ToString(), + SongPath = reader["SongPath"].ToString() + }); + } + } + } + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error ocurred:\n{exMsg}"); + songs.Clear(); + } + + return songs; + } + + public Song GetSong(int id) + { + Song song = new Song(); + + try + { + using (MySqlConnection conn = GetConnection()) + { + conn.Open(); + var query = "SELECT * FROM Songs WHERE Id=@Id"; + + MySqlCommand cmd = new MySqlCommand(query, conn); + cmd.Parameters.AddWithValue("@Id", id); + + using (var reader = cmd.ExecuteReader()) + { + while (reader.Read()) + { + song = new Song + { + Id = Convert.ToInt32(reader["Id"]), + Title = reader["Title"].ToString(), + Album = reader["Album"].ToString(), + Artist = reader["Artist"].ToString(), + Year = Convert.ToInt32(reader["Year"]), + Genre = reader["Genre"].ToString(), + Duration = Convert.ToInt32(reader["Duration"]), + Filename = reader["Filename"].ToString(), + SongPath = reader["SongPath"].ToString() + }; + } + } + } + } + catch(Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error ocurred: {exMsg}"); + } + + return song; + } + + private MySqlConnection GetConnection() + { + return new MySqlConnection(ConnectionString); + } + } +} diff --git a/Models/Song.cs b/Models/Song.cs index 4c25fcf..1906e76 100644 --- a/Models/Song.cs +++ b/Models/Song.cs @@ -6,6 +6,9 @@ namespace Icarus.Models { public class Song { + [JsonIgnore] + private MusicStoreContext _context; + [JsonProperty("id")] public int Id { get; set; } [JsonProperty("title")] diff --git a/Startup.cs b/Startup.cs index 2c4ba14..ae40ca3 100644 --- a/Startup.cs +++ b/Startup.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; + using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; @@ -11,6 +12,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; +using Icarus.Models; + namespace Icarus { public class Startup @@ -27,6 +30,8 @@ namespace Icarus { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddSingleton(Configuration); + + services.Add(new ServiceDescriptor(typeof(MusicStoreContext), new MusicStoreContext(Configuration.GetConnectionString("DefaultConnection")))); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/appsettings.Development.json b/appsettings.Development.json index c1e040a..f5baa39 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -7,9 +7,9 @@ } }, "ConnectionStrings": { - "IcarusDev":"Server=; User=; Password=; Database=; Port=" + "DefaultConnection":"Server=;Database=;Uid=;Pwd=;" }, - "RootMusicPath":"/root/of/music/path/", - "TemporaryMusicPath":"/root/temp/music/path/", - "ArchivePath":"/root/of/archive/path/" + "RootMusicPath":"/music/path/", + "TemporaryMusicPath":"/music/temp/path/", + "ArchivePath":"/archive/path/" } diff --git a/appsettings.json b/appsettings.json index dbd1be1..63e4404 100644 --- a/appsettings.json +++ b/appsettings.json @@ -6,9 +6,9 @@ }, "AllowedHosts": "*", "ConnectionStrings": { - "IcarusProd":"Server=; User=; Password=; Database=; Port=" + "DefaultConnection":"Server=;Database=;Uid=;Pwd=;" }, - "RootMusicPath":"/root/of/music/path/", - "TemporaryMusicPath":"/root/temp/music/path/", - "ArchivePath":"/root/of/archive/path/" + "RootMusicPath":"/music/path/", + "TemporaryMusicPath":"/music/temp/path/", + "ArchivePath":"/archive/path/" }