Refactoring and cleanup

This commit is contained in:
amazing-username
2019-04-14 18:53:04 +00:00
parent ed6ae7e3dd
commit c9b1abdbdb
10 changed files with 596 additions and 423 deletions
+281 -292
View File
@@ -19,193 +19,192 @@ using Icarus.Controllers.Utilities;
namespace Icarus.Controllers.Managers namespace Icarus.Controllers.Managers
{ {
public class SongManager public class SongManager
{ {
#region Fields #region Fields
private MySqlConnection _conn; private MySqlConnection _conn;
private MySqlCommand _cmd; private MySqlCommand _cmd;
private MySqlDataAdapter _dataDump; private MySqlDataAdapter _dataDump;
private DataTable _results; private DataTable _results;
private List<Song> _songs; private List<Song> _songs;
private Song _song; private Song _song;
private IConfiguration _config; private IConfiguration _config;
private string _connectionString; private string _connectionString;
private string _tempDirectoryRoot; private string _tempDirectoryRoot;
private string _archiveDirectoryRoot; private string _archiveDirectoryRoot;
private string _compressedSongFilename; private string _compressedSongFilename;
#endregion #endregion
#region Properties #region Properties
public Song SongDetails public Song SongDetails
{ {
get => _song; get => _song;
set => _song = value; set => _song = value;
} }
public string ArchiveDirectoryRoot public string ArchiveDirectoryRoot
{ {
get => _archiveDirectoryRoot; get => _archiveDirectoryRoot;
set => _archiveDirectoryRoot = value; set => _archiveDirectoryRoot = value;
} }
public string CompressedSongFilename public string CompressedSongFilename
{ {
get => _compressedSongFilename; get => _compressedSongFilename;
set => _compressedSongFilename = value; set => _compressedSongFilename = value;
} }
#endregion #endregion
#region Constructors #region Constructors
public SongManager() public SongManager()
{ {
Initialize(); Initialize();
InitializeConnection(); InitializeConnection();
} }
public SongManager(Song song) public SongManager(Song song)
{ {
Initialize(); Initialize();
InitializeConnection(); InitializeConnection();
_song = song; _song = song;
} }
public SongManager(IConfiguration config) public SongManager(IConfiguration config)
{ {
_config = config; _config = config;
Initialize(); Initialize();
InitializeConnection(); InitializeConnection();
} }
public SongManager(IConfiguration config, string tempDirectoryRoot) public SongManager(IConfiguration config, string tempDirectoryRoot)
{ {
_config = config; _config = config;
_tempDirectoryRoot = tempDirectoryRoot; _tempDirectoryRoot = tempDirectoryRoot;
Initialize(); Initialize();
InitializeConnection(); InitializeConnection();
} }
#endregion #endregion
#region Methods #region Methods
public void SaveSongDetails() public void SaveSongDetails()
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{ {
try conn.Open();
{ string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " +
using (MySqlConnection conn = new MySqlConnection(_connectionString)) "Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " +
{ "@Duration, @Filename, @SongPath)";
conn.Open(); using (MySqlCommand cmd = new MySqlCommand(query, conn))
string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + {
"Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + cmd.Parameters.AddWithValue("@Title", _song.Title);
"@Duration, @Filename, @SongPath)"; cmd.Parameters.AddWithValue("@Album", _song.Album);
using (MySqlCommand cmd = new MySqlCommand(query, conn)) cmd.Parameters.AddWithValue("@Artist", _song.Artist);
{ cmd.Parameters.AddWithValue("@Year", _song.Year);
cmd.Parameters.AddWithValue("@Title", _song.Title); cmd.Parameters.AddWithValue("@Genre", _song.Genre);
cmd.Parameters.AddWithValue("@Album", _song.Album); cmd.Parameters.AddWithValue("@Duration", _song.Duration);
cmd.Parameters.AddWithValue("@Artist", _song.Artist); cmd.Parameters.AddWithValue("@Filename", _song.Filename);
cmd.Parameters.AddWithValue("@Year", _song.Year); cmd.Parameters.AddWithValue("@SongPath", _song.SongPath);
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(); cmd.ExecuteNonQuery();
} }
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An Error Occurred: {exMsg}");
}
} }
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 conn.Open();
{ string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " +
using (MySqlConnection conn = new MySqlConnection(_connectionString)) ", Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " +
{ "@Duration, @Filename, @SongPath)";
conn.Open(); using (MySqlCommand cmd = new MySqlCommand(query, conn))
string query = "INSERT INTO Songs(Title, Album, Artist, Year, Genre, Duration, " + {
", Filename, SongPath) VALUES(@Title, @Album, @Artist, @Year, @Genre, " + cmd.Parameters.AddWithValue("@Title", song.Title);
"@Duration, @Filename, @SongPath)"; cmd.Parameters.AddWithValue("@Album", song.Album);
using (MySqlCommand cmd = new MySqlCommand(query, conn)) cmd.Parameters.AddWithValue("@Artist", song.Artist);
{ cmd.Parameters.AddWithValue("@Year", song.Year);
cmd.Parameters.AddWithValue("@Title", song.Title); cmd.Parameters.AddWithValue("@Genre", song.Genre);
cmd.Parameters.AddWithValue("@Album", song.Album); cmd.Parameters.AddWithValue("@Duration", song.Duration);
cmd.Parameters.AddWithValue("@Artist", song.Artist); cmd.Parameters.AddWithValue("@Filename", song.Filename);
cmd.Parameters.AddWithValue("@Year", song.Year); cmd.Parameters.AddWithValue("@SongPath", song.SongPath);
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(); cmd.ExecuteNonQuery();
} }
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An Error Occurred: {exMsg}");
}
} }
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 conn.Open();
{ string query = "INSERT INTO SongData(Data) VALUES(@Data)";
using (MySqlConnection conn = new MySqlConnection(_connectionString)) using (MySqlCommand cmd = new MySqlCommand(query, conn))
{ {
conn.Open(); cmd.Parameters.AddWithValue("@Data", songData.Data);
string query = "INSERT INTO SongData(Data) VALUES(@Data)";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Data", songData.Data);
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
}
}
catch(Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
} }
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 await song.CopyToAsync(fileStream);
{ _song.SongPath = filePath;
var filePath = Path.Combine(_tempDirectoryRoot, song.FileName);
await SaveSongToFileSystemTemp(song, filePath);
System.IO.File.Delete(filePath);
Console.WriteLine($"Writing song to the directory: {filePath}");
DirectoryManager dirMgr = new DirectoryManager(_config, _song); Console.WriteLine("Song successfully saved");
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}");
}
} }
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
}
public async Task<List<Song>> RetrieveAllSongDetails() public async Task<List<Song>> RetrieveAllSongDetails()
{ {
@@ -237,160 +236,150 @@ namespace Icarus.Controllers.Managers
return _songs; return _songs;
} }
public async Task<Song> RetrieveSongDetails(int id) public async Task<Song> 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)) dataDump.Fill(results);
{
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) }
{ catch (Exception ex)
SongData song = new SongData(); {
try var exMsg = ex.Message;
{ Console.WriteLine($"An error occurred");
_song = await RetrieveSongDetails(id); }
song = RetrieveSongFromFileSystem(_song);
} DataRow row = results.Rows[0];
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
return song; return new Song
} {
public async Task<SongData> RetrieveCompressedSong(int id) Id = Int32.Parse(row["Id"].ToString()),
{ Filename = row["Filename"].ToString(),
SongData song = new SongData(); SongPath = row["SongPath"].ToString()
try };
{ }
_song = await RetrieveSongDetails(id); public async Task<SongData> RetrieveSong(int id)
Console.WriteLine("Retrieved details of song"); {
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); return song;
Console.WriteLine("Retrieved song from filesystem"); }
public async Task<SongData> 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); return song;
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;
}
Song RetrieveMetaData(string filePath) Song RetrieveMetaData(string filePath)
{ {
string title, artist, album, genre; string title, artist, album, genre;
int year, duration; int year, duration;
TagLib.File tfile = TagLib.File.Create(filePath); TagLib.File tfile = TagLib.File.Create(filePath);
duration = (int)tfile.Properties.Duration.TotalSeconds; duration = (int)tfile.Properties.Duration.TotalSeconds;
using (var mp3 = new Mp3(filePath)) using (var mp3 = new Mp3(filePath))
{ {
Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X); Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
title = tag.Title; title = tag.Title;
artist = tag.Artists; artist = tag.Artists;
album = tag.Album; album = tag.Album;
genre = "Not Implemented"; genre = "Not Implemented";
year = (int)tag.Year; year = (int)tag.Year;
Console.WriteLine("Title: {0}", title); Console.WriteLine("Title: {0}", title);
Console.WriteLine("Artist: {0}", artist); Console.WriteLine("Artist: {0}", artist);
Console.WriteLine("Album: {0}", album); Console.WriteLine("Album: {0}", album);
Console.WriteLine("Genre: {0}", genre); Console.WriteLine("Genre: {0}", genre);
Console.WriteLine("Year: {0}", year); Console.WriteLine("Year: {0}", year);
Console.WriteLine("Duration: {0}", duration); Console.WriteLine("Duration: {0}", duration);
} }
_song = new Song _song = new Song
{ {
Title = title, Title = title,
Artist = artist, Artist = artist,
Album = album, Album = album,
Year = year, Year = year,
Genre = genre, Genre = genre,
Duration = duration, Duration = duration,
SongPath = filePath SongPath = filePath
}; };
return _song; return _song;
} }
SongData RetrieveSongFromFileSystem(Song details) async Task<SongData> RetrieveSongFromFileSystem(Song details)
{ {
byte[] uncompressedSong = System.IO.File.ReadAllBytes(details.SongPath); byte[] uncompressedSong = System.IO.File.ReadAllBytes(details.SongPath);
return new SongData return new SongData
{ {
Data = uncompressedSong Data = uncompressedSong
}; };
} }
async Task SaveSongToFileSystemTemp(IFormFile song, string filePath) async Task SaveSongToFileSystemTemp(IFormFile song, string filePath)
{ {
using (var fileStream = new FileStream(filePath, FileMode.Create)) using (var fileStream = new FileStream(filePath, FileMode.Create))
{ {
await song.CopyToAsync(fileStream); await song.CopyToAsync(fileStream);
_song = RetrieveMetaData(filePath); _song = RetrieveMetaData(filePath);
_song.Filename = song.FileName; _song.Filename = song.FileName;
} }
} }
void Initialize() void Initialize()
{ {
try try
{ {
_connectionString = _config.GetConnectionString("IcarusDev"); _connectionString = _config.GetConnectionString("IcarusDev");
} }
catch (Exception ex) catch (Exception ex)
{ {
Console.WriteLine($"Error Occurred: {ex.Message}"); Console.WriteLine($"Error Occurred: {ex.Message}");
} }
} }
void InitializeConnection() void InitializeConnection()
{ {
_conn = new MySqlConnection(_connectionString); _conn = new MySqlConnection(_connectionString);
@@ -441,6 +430,6 @@ namespace Icarus.Controllers.Managers
_songs.Add(song); _songs.Add(song);
} }
} }
#endregion #endregion
} }
} }
+24 -23
View File
@@ -10,6 +10,7 @@ using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Icarus.Controllers.Managers; using Icarus.Controllers.Managers;
using Icarus.Controllers.Utilities;
using Icarus.Models; using Icarus.Models;
namespace Icarus.Controllers namespace Icarus.Controllers
@@ -20,41 +21,41 @@ namespace Icarus.Controllers
{ {
#region Fields #region Fields
private IConfiguration _config; private IConfiguration _config;
private SongManager _songMgr; private SongManager _songMgr;
private string _songTempDir; private string _songTempDir;
private string _archiveDir; private string _archiveDir;
#endregion #endregion
#region Properties #region Properties
#endregion #endregion
#region Constructor #region Constructor
public SongCompressedDataController(IConfiguration config) public SongCompressedDataController(IConfiguration config)
{ {
_config = config; _config = config;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath"); _songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_archiveDir = _config.GetValue<string>("ArchivePath"); _archiveDir = _config.GetValue<string>("ArchivePath");
_songMgr = new SongManager(config, _songTempDir); }
_songMgr.ArchiveDirectoryRoot = _archiveDir; #endregion
}
#endregion
#region API Routes #region API Routes
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> Get(int id) public async Task<IActionResult> 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"); Console.WriteLine("Starting process of retrieving comrpessed song");
song = await _songMgr.RetrieveCompressedSong(id); 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
} }
} }
+23 -16
View File
@@ -16,30 +16,35 @@ namespace Icarus.Controllers
[ApiController] [ApiController]
public class SongController : ControllerBase public class SongController : ControllerBase
{ {
#region Fields #region Fields
private IConfiguration _config; private IConfiguration _config;
private SongManager _songMgr; private SongManager _songMgr;
#endregion #endregion
#region Properties #region Properties
#endregion #endregion
#region Constructor #region Constructor
public SongController(IConfiguration config) public SongController(IConfiguration config)
{ {
_config = config; _config = config;
_songMgr = new SongManager(config); _songMgr = new SongManager(config);
} }
#endregion #endregion
[HttpGet] [HttpGet]
public ActionResult<IEnumerable<Song>> Get() public ActionResult<IEnumerable<Song>> Get()
{ {
List<Song> songs = new List<Song>(); List<Song> songs = new List<Song>();
songs = _songMgr.RetrieveAllSongDetails().Result; songs = _songMgr.RetrieveAllSongDetails().Result;
Console.WriteLine("Attemtping to retrieve songs");
MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext;
songs = context.GetAllSongs();
return songs; return songs;
@@ -48,7 +53,8 @@ namespace Icarus.Controllers
[HttpGet("{id}")] [HttpGet("{id}")]
public ActionResult<Song> Get(int id) public ActionResult<Song> 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; return song;
} }
@@ -56,7 +62,8 @@ namespace Icarus.Controllers
[HttpPost] [HttpPost]
public void Post([FromBody] Song song) 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}")] [HttpPut("{id}")]
+38 -33
View File
@@ -20,29 +20,29 @@ namespace Icarus.Controllers
{ {
#region Fields #region Fields
private IConfiguration _config; private IConfiguration _config;
private SongManager _songMgr; private SongManager _songMgr;
private string _songTempDir; private string _songTempDir;
#endregion #endregion
#region Properties #region Properties
#endregion #endregion
#region Constructor #region Constructor
public SongDataController(IConfiguration config) public SongDataController(IConfiguration config)
{ {
_config = config; _config = config;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath"); _songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_songMgr = new SongManager(config, _songTempDir); _songMgr = new SongManager(config, _songTempDir);
} }
#endregion #endregion
[HttpGet] [HttpGet]
public ActionResult<IEnumerable<SongData>> Get() public ActionResult<IEnumerable<SongData>> Get()
{ {
List<SongData> songs = new List<SongData>(); List<SongData> songs = new List<SongData>();
return songs; return songs;
@@ -51,33 +51,38 @@ namespace Icarus.Controllers
[HttpGet("{id}")] [HttpGet("{id}")]
public async Task<IActionResult> Get(int id) public async Task<IActionResult> 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] [HttpPost]
public async Task Post([FromForm(Name = "file")] List<IFormFile> songData) public async Task Post([FromForm(Name = "file")] List<IFormFile> songData)
{ {
try try
{ {
Console.WriteLine("Uploading song..."); MusicStoreContext context = HttpContext.RequestServices.GetService(typeof(MusicStoreContext)) as MusicStoreContext;
Console.WriteLine("Uploading song...");
var uploads = _songTempDir; var uploads = _songTempDir;
Console.WriteLine($"Song Root Path {uploads}"); Console.WriteLine($"Song Root Path {uploads}");
foreach (var sng in songData) foreach (var sng in songData)
{ {
if (sng.Length > 0) { if (sng.Length > 0) {
await _songMgr.SaveSongToFileSystem(sng); 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}"); }
} catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
} }
[HttpPut("{id}")] [HttpPut("{id}")]
+73 -51
View File
@@ -2,6 +2,8 @@ using System;
using System.IO; using System.IO;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Ionic.Zip; using Ionic.Zip;
using Icarus.Models; using Icarus.Models;
@@ -11,18 +13,19 @@ namespace Icarus.Controllers.Utilities
public class SongCompression public class SongCompression
{ {
#region Fields #region Fields
string _compressedSongFilename; string _archiveDirectory;
string _tempDirectory; string _compressedSongFilename;
string _tempDirectory;
byte[] _uncompressedSong; byte[] _uncompressedSong;
#endregion #endregion
#region Propterties #region Propterties
public string CompressedSongFilename public string CompressedSongFilename
{ {
get => _compressedSongFilename; get => _compressedSongFilename;
set => _compressedSongFilename = value; set => _compressedSongFilename = value;
} }
#endregion #endregion
@@ -30,10 +33,10 @@ namespace Icarus.Controllers.Utilities
public SongCompression() public SongCompression()
{ {
} }
public SongCompression(string tempDirectory) public SongCompression(string tempDirectory)
{ {
_tempDirectory = tempDirectory; _tempDirectory = tempDirectory;
} }
public SongCompression(byte[] uncompressedSong) public SongCompression(byte[] uncompressedSong)
{ {
_uncompressedSong = uncompressedSong; _uncompressedSong = uncompressedSong;
@@ -42,41 +45,60 @@ namespace Icarus.Controllers.Utilities
#region Methods #region Methods
public string RetrieveCompressesSongPath(Song songDetails) 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())
{ {
string tmpZipFilePath = _tempDirectory + songDetails.Filename; zip.AddFile(songDetails.SongPath);
zip.Save(tmpZipFilePath);
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;
} }
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) public byte[] CompressedSong(byte[] uncompressedSong)
{ {
byte[] compressedSong = null; byte[] compressedSong = null;
try try
{ {
Console.WriteLine("Song has been successfully compressed"); Console.WriteLine("Song has been successfully compressed");
} }
catch (Exception ex) catch (Exception ex)
{ {
@@ -89,20 +111,20 @@ namespace Icarus.Controllers.Utilities
} }
string StripMP3Extension(string filename) string StripMP3Extension(string filename)
{ {
Console.WriteLine($"Before: {filename}"); Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length; int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}"); Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1; var endIndex = filenameLength - 1;
var startIndex = endIndex - 3; var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}"); Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4); var stripped = filename.Remove(startIndex, 4);
stripped += ".zip"; stripped += ".zip";
Console.WriteLine($"After {stripped}"); Console.WriteLine($"After {stripped}");
return stripped; return stripped;
} }
#endregion #endregion
} }
} }
+141
View File
@@ -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<Song> GetAllSongs()
{
List<Song> songs = new List<Song>();
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);
}
}
}
+3
View File
@@ -6,6 +6,9 @@ namespace Icarus.Models
{ {
public class Song public class Song
{ {
[JsonIgnore]
private MusicStoreContext _context;
[JsonProperty("id")] [JsonProperty("id")]
public int Id { get; set; } public int Id { get; set; }
[JsonProperty("title")] [JsonProperty("title")]
+5
View File
@@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.AspNetCore.HttpsPolicy;
@@ -11,6 +12,8 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; using Microsoft.Extensions.Options;
using Icarus.Models;
namespace Icarus namespace Icarus
{ {
public class Startup public class Startup
@@ -27,6 +30,8 @@ namespace Icarus
{ {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSingleton<IConfiguration>(Configuration); services.AddSingleton<IConfiguration>(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. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
+4 -4
View File
@@ -7,9 +7,9 @@
} }
}, },
"ConnectionStrings": { "ConnectionStrings": {
"IcarusDev":"Server=; User=; Password=; Database=; Port=" "DefaultConnection":"Server=;Database=;Uid=;Pwd=;"
}, },
"RootMusicPath":"/root/of/music/path/", "RootMusicPath":"/music/path/",
"TemporaryMusicPath":"/root/temp/music/path/", "TemporaryMusicPath":"/music/temp/path/",
"ArchivePath":"/root/of/archive/path/" "ArchivePath":"/archive/path/"
} }
+4 -4
View File
@@ -6,9 +6,9 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"ConnectionStrings": { "ConnectionStrings": {
"IcarusProd":"Server=; User=; Password=; Database=; Port=" "DefaultConnection":"Server=;Database=;Uid=;Pwd=;"
}, },
"RootMusicPath":"/root/of/music/path/", "RootMusicPath":"/music/path/",
"TemporaryMusicPath":"/root/temp/music/path/", "TemporaryMusicPath":"/music/temp/path/",
"ArchivePath":"/root/of/archive/path/" "ArchivePath":"/archive/path/"
} }