Code cleanup and conforming to a coding covention

This commit is contained in:
amazing-username
2019-07-04 17:19:40 -04:00
parent ada8fa79d3
commit 56fe805f80
28 changed files with 4274 additions and 4465 deletions
+11 -11
View File
@@ -8,21 +8,21 @@ using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class AlbumManager : BaseManager
{
#region Fields
#endregion
public class AlbumManager : BaseManager
{
#region Fields
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
#endregion
#region Constructors
#endregion
#region Methods
#endregion
}
#region Methods
#endregion
}
}
+11 -11
View File
@@ -8,21 +8,21 @@ using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class ArtistManager : BaseManager
{
#region Fields
#endregion
public class ArtistManager : BaseManager
{
#region Fields
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
#endregion
#region Constructors
#endregion
#region Methods
#endregion
}
#region Methods
#endregion
}
}
+6 -6
View File
@@ -4,10 +4,10 @@ using NLog;
namespace Icarus.Controllers.Managers
{
public class BaseManager
{
#region Fields
protected static Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
#endregion
}
public class BaseManager
{
#region Fields
protected static Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
#endregion
}
}
+164 -164
View File
@@ -8,198 +8,198 @@ using Icarus.Models;
namespace Icarus.Controllers.Managers
{
public class DirectoryManager : BaseManager
{
#region Fields
private IConfiguration _config;
private Song _song;
private string _rootSongDirectory;
private string _songDirectory;
#endregion
public class DirectoryManager : BaseManager
{
#region Fields
private IConfiguration _config;
private Song _song;
private string _rootSongDirectory;
private string _songDirectory;
#endregion
#region Properties
public string SongDirectory
{
get => _songDirectory;
set => _songDirectory = value;
}
#endregion
#region Properties
public string SongDirectory
{
get => _songDirectory;
set => _songDirectory = value;
}
#endregion
#region Constructors
public DirectoryManager(IConfiguration config, Song song)
{
_config = config;
_song = song;
Initialize();
}
public DirectoryManager(IConfiguration config)
{
_config = config;
Initialize();
}
#endregion
#region Constructors
public DirectoryManager(IConfiguration config, Song song)
{
_config = config;
_song = song;
Initialize();
}
public DirectoryManager(IConfiguration config)
{
_config = config;
Initialize();
}
#endregion
#region Methods
public void CreateDirectory()
{
try
{
_songDirectory = AlbumDirectory();
#region Methods
public void CreateDirectory()
{
try
{
_songDirectory = AlbumDirectory();
if (!Directory.Exists(_songDirectory))
{
Directory.CreateDirectory(_songDirectory);
Console.WriteLine("The directory has been created");
}
if (!Directory.Exists(_songDirectory))
{
Directory.CreateDirectory(_songDirectory);
Console.WriteLine("The directory has been created");
}
Console.WriteLine($"The song will be saved in the following" +
$" directory: {_songDirectory}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred {ex.Message}");
}
}
public void DeleteEmptyDirectories()
{
try
{
var albumDirectory = AlbumDirectory();
var artistDirectory = ArtistDirectory();
if (IsDirectoryEmpty(albumDirectory))
{
Directory.Delete(albumDirectory);
Console.WriteLine($"directory {albumDirectory} deleted");
}
if (IsDirectoryEmpty(artistDirectory))
{
Directory.Delete(artistDirectory);
Console.WriteLine($"directory {artistDirectory} deleted");
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred {exMsg}");
}
}
public void DeleteEmptyDirectories(Song song)
{
try
{
var albumDirectory = AlbumDirectory(song);
var artistDirectory = ArtistDirectory(song);
Console.WriteLine($"The song will be saved in the following" +
$" directory: {_songDirectory}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred {ex.Message}");
}
}
public void DeleteEmptyDirectories()
{
try
{
var albumDirectory = AlbumDirectory();
var artistDirectory = ArtistDirectory();
if (IsDirectoryEmpty(albumDirectory))
{
Directory.Delete(albumDirectory);
Console.WriteLine($"directory {albumDirectory} deleted");
}
if (IsDirectoryEmpty(artistDirectory))
{
Directory.Delete(artistDirectory);
Console.WriteLine($"directory {artistDirectory} deleted");
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred {exMsg}");
}
}
public void DeleteEmptyDirectories(Song song)
{
try
{
var albumDirectory = AlbumDirectory(song);
var artistDirectory = ArtistDirectory(song);
if (IsDirectoryEmpty(albumDirectory))
{
Directory.Delete(albumDirectory);
_logger.Info("Album directory deleted");
}
if (IsDirectoryEmpty(artistDirectory))
{
Directory.Delete(artistDirectory);
_logger.Info("Artist directory deleted");
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
if (IsDirectoryEmpty(albumDirectory))
{
Directory.Delete(albumDirectory);
_logger.Info("Album directory deleted");
}
if (IsDirectoryEmpty(artistDirectory))
{
Directory.Delete(artistDirectory);
_logger.Info("Artist directory deleted");
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
}
public string RetrieveAlbumPath(Song song)
{
_logger.Info("Retrieving album song path");
public string RetrieveAlbumPath(Song song)
{
_logger.Info("Retrieving album song path");
var albumPath = string.Empty;
albumPath = AlbumDirectory(song);
var albumPath = string.Empty;
albumPath = AlbumDirectory(song);
return albumPath;
}
public string RetrieveArtistPath(Song song)
{
_logger.Info("Retrieving artist path");
return albumPath;
}
public string RetrieveArtistPath(Song song)
{
_logger.Info("Retrieving artist path");
var artistPath = string.Empty;
artistPath = ArtistDirectory(song);
var artistPath = string.Empty;
artistPath = ArtistDirectory(song);
return artistPath;
}
public string GenerateSongPath(Song song)
{
_logger.Info("Generating song path");
return artistPath;
}
public string GenerateSongPath(Song song)
{
_logger.Info("Generating song path");
var songPath = string.Empty;
var artistPath = ArtistDirectory(song);
var albumPath = AlbumDirectory(song);
var songPath = string.Empty;
var artistPath = ArtistDirectory(song);
var albumPath = AlbumDirectory(song);
if (!Directory.Exists(artistPath))
{
_logger.Info("Artist path does not exist");
if (!Directory.Exists(artistPath))
{
_logger.Info("Artist path does not exist");
Directory.CreateDirectory(artistPath);
Directory.CreateDirectory(artistPath);
_logger.Info("Creating artist path");
}
if (!Directory.Exists(albumPath))
{
_logger.Info("Album path does not exist");
_logger.Info("Creating artist path");
}
if (!Directory.Exists(albumPath))
{
_logger.Info("Album path does not exist");
Directory.CreateDirectory(albumPath);
Directory.CreateDirectory(albumPath);
_logger.Info("Created album path");
}
_logger.Info("Created album path");
}
songPath = albumPath;
songPath = albumPath;
return songPath;
}
return songPath;
}
private void Initialize()
{
_rootSongDirectory = _config.GetValue<string>("RootMusicPath");
}
private void Initialize()
{
_rootSongDirectory = _config.GetValue<string>("RootMusicPath");
}
private bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string AlbumDirectory()
{
string directory = _rootSongDirectory;
directory += $@"{_song.Artist}/{_song.AlbumTitle}/";
private string AlbumDirectory()
{
string directory = _rootSongDirectory;
directory += $@"{_song.Artist}/{_song.AlbumTitle}/";
return directory;
}
private string AlbumDirectory(Song song)
{
var directory = _rootSongDirectory;
directory += $@"{song.Artist}/{song.AlbumTitle}/";
Console.WriteLine($"Album directory {directory}");
return directory;
}
private string AlbumDirectory(Song song)
{
var directory = _rootSongDirectory;
directory += $@"{song.Artist}/{song.AlbumTitle}/";
Console.WriteLine($"Album directory {directory}");
return directory;
}
private string ArtistDirectory()
{
var directory = _rootSongDirectory;
directory += $@"{_song.Artist}/";
return directory;
}
private string ArtistDirectory()
{
var directory = _rootSongDirectory;
directory += $@"{_song.Artist}/";
return directory;
}
private string ArtistDirectory(Song song)
{
var directory = _rootSongDirectory;
directory += $@"{song.Artist}/";
Console.WriteLine($"Artist directory {directory}");
return directory;
}
private string ArtistDirectory(Song song)
{
var directory = _rootSongDirectory;
directory += $@"{song.Artist}/";
Console.WriteLine($"Artist directory {directory}");
return directory;
}
#endregion
}
return directory;
}
#endregion
}
}
+11 -11
View File
@@ -8,21 +8,21 @@ using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class GenreManager : BaseManager
{
#region Fields
#endregion
public class GenreManager : BaseManager
{
#region Fields
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
#endregion
#region Constructors
#endregion
#region Methods
#endregion
}
#region Methods
#endregion
}
}
File diff suppressed because it is too large Load Diff
+101 -108
View File
@@ -10,132 +10,125 @@ using Icarus.Models;
namespace Icarus.Controllers.Managers
{
public class TokenManager : BaseManager
{
#region Fields
private IConfiguration _config;
private string _clientId;
private string _clientSecret;
private string _audience;
private string _grantType;
private string _url;
#endregion
public class TokenManager : BaseManager
{
#region Fields
private IConfiguration _config;
private string _clientId;
private string _clientSecret;
private string _audience;
private string _grantType;
private string _url;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
public TokenManager(IConfiguration config)
{
_config = config;
InitializeValues();
}
#endregion
#region Constructors
public TokenManager(IConfiguration config)
{
_config = config;
InitializeValues();
}
#endregion
#region Methods
public LoginResult RetrieveLoginResult(User user)
{
_logger.Info("Preparing Auth0 API request");
#region Methods
public LoginResult RetrieveLoginResult(User user)
{
_logger.Info("Preparing Auth0 API request");
var client = new RestClient(_url);
var request = new RestRequest("oauth/token", Method.POST);
var tokenRequest = RetrieveTokenRequest();
var client = new RestClient(_url);
var request = new RestRequest("oauth/token", Method.POST);
var tokenRequest = RetrieveTokenRequest();
_logger.Info("Serializing token object into JSON");
var tokenObject = JsonConvert.SerializeObject(tokenRequest);
Console.WriteLine(tokenObject);
request.AddParameter("application/json; charset=utf-8",
tokenObject, ParameterType.RequestBody);
_logger.Info("Serializing token object into JSON");
var tokenObject = JsonConvert.SerializeObject(tokenRequest);
request.RequestFormat = DataFormat.Json;
request.AddParameter("application/json; charset=utf-8",
tokenObject, ParameterType.RequestBody);
_logger.Info("Sending request");
IRestResponse response = client.Execute(request);
_logger.Info("Response received");
request.RequestFormat = DataFormat.Json;
_logger.Info("Sending request");
IRestResponse response = client.Execute(request);
_logger.Info("Response received");
_logger.Info("Deserializing response");
var tokenResult = JsonConvert
.DeserializeObject<Token>(response.Content);
_logger.Info("Response deserialized");
Console.WriteLine(response.Content);
_logger.Info("Deserializing response");
var tokenResult = JsonConvert
.DeserializeObject<Token>(response.Content);
_logger.Info("Response deserialized");
return new LoginResult
{
UserId = user.Id,
Username = user.Username,
Token = tokenResult.AccessToken,
TokenType = tokenResult.TokenType,
Expiration = tokenResult.Expiration,
Message = "Successfully retrieved token"
};
}
private TokenRequest RetrieveTokenRequest()
{
_logger.Info("Retrieving token object");
return new LoginResult
{
UserId = user.Id, Username = user.Username, Token = tokenResult.AccessToken,
TokenType = tokenResult.TokenType, Expiration = tokenResult.Expiration,
Message = "Successfully retrieved token"
};
}
private TokenRequest RetrieveTokenRequest()
{
_logger.Info("Retrieving token object");
return new TokenRequest
{
ClientId = _clientId,
ClientSecret = _clientSecret,
Audience = _audience,
GrantType = _grantType
};
}
return new TokenRequest
{
ClientId = _clientId, ClientSecret = _clientSecret,
Audience = _audience, GrantType = _grantType
};
}
private void InitializeValues()
{
_logger.Info("Analyzing Auth0 information");
private void InitializeValues()
{
_logger.Info("Analyzing Auth0 information");
_clientId = _config["Auth0:ClientId"];
_clientSecret = _config["Auth0:ClientSecret"];
_audience = _config["Auth0:ApiIdentifier"];
_grantType = "client_credentials";
_url = $"https://{_config["Auth0:Domain"]}";
_clientId = _config["Auth0:ClientId"];
_clientSecret = _config["Auth0:ClientSecret"];
_audience = _config["Auth0:ApiIdentifier"];
_grantType = "client_credentials";
_url = $"https://{_config["Auth0:Domain"]}";
PrintCredentials();
PrintCredentials();
}
}
#region Testing Methods
// For testing purposes
private void PrintCredentials()
{
Console.WriteLine("Auth0 credentials:");
Console.WriteLine($"Client Id: {_clientId}");
Console.WriteLine($"Client Secret: {_clientSecret}");
Console.WriteLine($"Audience: {_audience}");
Console.WriteLine($"Url: {_url}");
}
#endregion
#endregion
#region Testing Methods
// For testing purposes
private void PrintCredentials()
{
Console.WriteLine("Auth0 credentials:");
Console.WriteLine($"Client Id: {_clientId}");
Console.WriteLine($"Client Secret: {_clientSecret}");
Console.WriteLine($"Audience: {_audience}");
Console.WriteLine($"Url: {_url}");
}
#endregion
#endregion
#region Classes
private class TokenRequest
{
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("grant_type")]
public string GrantType { get; set; }
}
private class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int Expiration { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
}
#endregion
}
#region Classes
private class TokenRequest
{
[JsonProperty("client_id")]
public string ClientId { get; set; }
[JsonProperty("client_secret")]
public string ClientSecret { get; set; }
[JsonProperty("audience")]
public string Audience { get; set; }
[JsonProperty("grant_type")]
public string GrantType { get; set; }
}
private class Token
{
[JsonProperty("access_token")]
public string AccessToken { get; set; }
[JsonProperty("expires_in")]
public int Expiration { get; set; }
[JsonProperty("token_type")]
public string TokenType { get; set; }
}
#endregion
}
}
+11 -11
View File
@@ -8,21 +8,21 @@ using Icarus.Database.Contexts;
namespace Icarus.Controllers.Managers
{
public class YearManager : BaseManager
{
#region Fields
#endregion
public class YearManager : BaseManager
{
#region Fields
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
#endregion
#region Constructors
#endregion
#region Methods
#endregion
}
#region Methods
#endregion
}
}
+252 -258
View File
@@ -9,284 +9,278 @@ using Icarus.Models;
namespace Icarus.Controllers.Utilities
{
public class MetadataRetriever
{
#region Fields
private static NLog.Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
private Song _updatedSong;
private string _message;
private string _title;
private string _artist;
private string _album;
private string _genre;
private int _year;
private int _duration;
#endregion
public class MetadataRetriever
{
#region Fields
private static NLog.Logger _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
private Song _updatedSong;
private string _message;
private string _title;
private string _artist;
private string _album;
private string _genre;
private int _year;
private int _duration;
#endregion
#region Properties
public Song UpdatedSongRecord
{
get => _updatedSong;
set => _updatedSong = value;
}
public string Message
{
get => _message;
set => _message = value;
}
#endregion
#region Properties
public Song UpdatedSongRecord
{
get => _updatedSong;
set => _updatedSong = value;
}
public string Message
{
get => _message;
set => _message = value;
}
#endregion
#region Constructors
#endregion
#region Constructors
#endregion
#region Methods
public static void PrintMetadata(Song song)
{
Console.WriteLine("\n\nMetadata of the song:");
Console.WriteLine($"Id: {song.Id}");
Console.WriteLine($"Title: {song.Title}");
Console.WriteLine($"Artist: {song.Artist}");
Console.WriteLine($"Album: {song.AlbumTitle}");
Console.WriteLine($"Genre: {song.Genre}");
Console.WriteLine($"Year: {song.Year}");
Console.WriteLine($"Duration: {song.Duration}");
Console.WriteLine($"AlbumId: {song.AlbumId}");
Console.WriteLine($"ArtistId: {song.ArtistId}");
Console.WriteLine($"GenreId: {song.GenreId}");
Console.WriteLine($"YearId: {song.YearId}");
Console.WriteLine($"Song Path: {song.SongPath}");
Console.WriteLine($"Filename: {song.Filename}");
Console.WriteLine("\n");
#region Methods
public static void PrintMetadata(Song song)
{
Console.WriteLine("\n\nMetadata of the song:");
Console.WriteLine($"Id: {song.Id}");
Console.WriteLine($"Title: {song.Title}");
Console.WriteLine($"Artist: {song.Artist}");
Console.WriteLine($"Album: {song.AlbumTitle}");
Console.WriteLine($"Genre: {song.Genre}");
Console.WriteLine($"Year: {song.Year}");
Console.WriteLine($"Duration: {song.Duration}");
Console.WriteLine($"AlbumId: {song.AlbumId}");
Console.WriteLine($"ArtistId: {song.ArtistId}");
Console.WriteLine($"GenreId: {song.GenreId}");
Console.WriteLine($"YearId: {song.YearId}");
Console.WriteLine($"Song Path: {song.SongPath}");
Console.WriteLine($"Filename: {song.Filename}");
Console.WriteLine("\n");
_logger.Info("Metadata of the song");
_logger.Info($"Title: {song.Title}");
_logger.Info($"Artist: {song.Artist}");
_logger.Info($"Album: {song.AlbumTitle}");
_logger.Info($"Genre: {song.Genre}");
_logger.Info($"Year: {song.Year}");
_logger.Info($"Duration: {song.Duration}");
}
public Song RetrieveMetaData(string filePath)
{
Song song = new Song();
_logger.Info("Metadata of the song");
_logger.Info($"Title: {song.Title}");
_logger.Info($"Artist: {song.Artist}");
_logger.Info($"Album: {song.AlbumTitle}");
_logger.Info($"Genre: {song.Genre}");
_logger.Info($"Year: {song.Year}");
_logger.Info($"Duration: {song.Duration}");
}
public Song RetrieveMetaData(string filePath)
{
Song song = new Song();
try
{
TagLib.File fileTag = TagLib.File.Create(filePath);
_title = fileTag.Tag.Title;
_artist = string.Join("", fileTag.Tag.Performers);
_album = fileTag.Tag.Album;
_genre = string.Join("", fileTag.Tag.Genres);
_year = (int)fileTag.Tag.Year;
_duration = (int)fileTag.Properties.Duration.TotalSeconds;
try
{
TagLib.File fileTag = TagLib.File.Create(filePath);
_title = fileTag.Tag.Title;
_artist = string.Join("", fileTag.Tag.Performers);
_album = fileTag.Tag.Album;
_genre = string.Join("", fileTag.Tag.Genres);
_year = (int)fileTag.Tag.Year;
_duration = (int)fileTag.Properties.Duration.TotalSeconds;
song.Title = _title;
song.Artist = _artist;
song.AlbumTitle = _album;
song.Genre = _genre;
song.Year = _year;
song.Duration = _duration;
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine("An error occurred in MetadataRetriever");
Console.WriteLine(msg);
_logger.Error(msg, "An error occurred in MetadataRetriever");
}
song.Title = _title;
song.Artist = _artist;
song.AlbumTitle = _album;
song.Genre = _genre;
song.Year = _year;
song.Duration = _duration;
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine("An error occurred in MetadataRetriever");
Console.WriteLine(msg);
_logger.Error(msg, "An error occurred in MetadataRetriever");
}
return song;
}
return song;
}
public void UpdateMetadata(Song song)
{
try
{
Console.WriteLine("Updating song metadata");
_logger.Info("Updating song metadata");
var filePath = song.SongPath;
TagLib.File fileTag = TagLib.File.Create(filePath);
fileTag.Tag.Title = song.Title;
fileTag.Tag.Genres = new []{song.Genre};
fileTag.Save();
Console.WriteLine("Song metadata updated");
_logger.Info("Song metadata updated");
public void UpdateMetadata(Song song)
{
try
{
Console.WriteLine("Updating song metadata");
_logger.Info("Updating song metadata");
var filePath = song.SongPath;
TagLib.File fileTag = TagLib.File.Create(filePath);
fileTag.Tag.Title = song.Title;
fileTag.Tag.Genres = new []{song.Genre};
fileTag.Save();
Console.WriteLine("Song metadata updated");
_logger.Info("Song metadata updated");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: \n{msg}");
_logger.Error(msg, "An error occurred");
}
}
public void UpdateMetadata(Song updatedSong, Song oldSong)
{
try
{
InitializeUpdatedSong(oldSong);
var songValues = CheckSongValues(updatedSong);
PerformUpdate(updatedSong, songValues);
Message = "Successfully updated metadata";
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: {msg}");
_logger.Error(msg, "An error occurred");
Message = "Failed to update metadata";
}
}
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: \n{msg}");
_logger.Error(msg, "An error occurred");
}
}
public void UpdateMetadata(Song updatedSong, Song oldSong)
{
try
{
InitializeUpdatedSong(oldSong);
var songValues = CheckSongValues(updatedSong);
PerformUpdate(updatedSong, songValues);
Message = "Successfully updated metadata";
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: {msg}");
_logger.Error(msg, "An error occurred");
Message = "Failed to update metadata";
}
}
private void PerformUpdate(Song updatedSong, SortedDictionary<string, bool> checkedValues)
{
var filePath = updatedSong.SongPath;
var title = updatedSong.Title;
var artist = updatedSong.Artist;
var album = updatedSong.AlbumTitle;
var genre = updatedSong.Genre;
var year = updatedSong.Year;
TagLib.File fileTag = TagLib.File.Create(filePath);
try
{
Console.WriteLine($"Updating metadata of {title}");
_logger.Info($"Updating metadata of {title}");
private void PerformUpdate(Song updatedSong, SortedDictionary<string, bool> checkedValues)
{
var filePath = updatedSong.SongPath;
var title = updatedSong.Title;
var artist = updatedSong.Artist;
var album = updatedSong.AlbumTitle;
var genre = updatedSong.Genre;
var year = updatedSong.Year;
TagLib.File fileTag = TagLib.File.Create(filePath);
try
{
Console.WriteLine($"Updating metadata of {title}");
_logger.Info($"Updating metadata of {title}");
foreach (var key in checkedValues.Keys)
{
bool result = checkedValues[key];
foreach (var key in checkedValues.Keys)
{
bool result = checkedValues[key];
if (!result)
{
switch (key.ToLower())
{
case "title":
_updatedSong.Title = title;
fileTag.Tag.Title = title;
break;
case "artists":
_updatedSong.Artist = artist;
fileTag.Tag.Performers = new []{artist};
break;
case "album":
_updatedSong.AlbumTitle = album;
fileTag.Tag.Album = album;
break;
case "genre":
_updatedSong.Genre = genre;
fileTag.Tag.Genres = new []{genre};
break;
case "year":
_updatedSong.Year = year;
fileTag.Tag.Year = (uint)year;
break;
}
}
}
if (!result)
switch (key.ToLower())
{
case "title":
_updatedSong.Title = title;
fileTag.Tag.Title = title;
break;
case "artists":
_updatedSong.Artist = artist;
fileTag.Tag.Performers = new []{artist};
break;
case "album":
_updatedSong.AlbumTitle = album;
fileTag.Tag.Album = album;
break;
case "genre":
_updatedSong.Genre = genre;
fileTag.Tag.Genres = new []{genre};
break;
case "year":
_updatedSong.Year = year;
fileTag.Tag.Year = (uint)year;
break;
}
}
fileTag.Save();
fileTag.Save();
Console.WriteLine("Successfully updated metadata");
_logger.Info("Successfully updated metadata");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred:\n{msg}");
_logger.Error(msg, "An error occurred");
}
}
private void InitializeUpdatedSong(Song song)
{
_updatedSong = new Song
{
Id = song.Id,
Title = song.Title,
AlbumTitle = song.AlbumTitle,
Artist = song.Artist,
Genre = song.Genre,
Year = song.Year,
Duration = song.Duration,
Filename = song.Filename,
SongPath = song.SongPath
};
}
private void PrintMetadata()
{
Console.WriteLine("\n\nMetadata of the song:");
Console.WriteLine($"Title: {_title}");
Console.WriteLine($"Artist: {_artist}");
Console.WriteLine($"Album: {_album}");
Console.WriteLine($"Genre: {_genre}");
Console.WriteLine($"Year: {_year}");
Console.WriteLine($"Duration: {_duration}\n\n");
Console.WriteLine("Successfully updated metadata");
_logger.Info("Successfully updated metadata");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred:\n{msg}");
_logger.Error(msg, "An error occurred");
}
}
private void InitializeUpdatedSong(Song song)
{
_updatedSong = new Song
{
Id = song.Id,
Title = song.Title,
AlbumTitle = song.AlbumTitle,
Artist = song.Artist,
Genre = song.Genre,
Year = song.Year,
Duration = song.Duration,
Filename = song.Filename,
SongPath = song.SongPath
};
}
private void PrintMetadata()
{
Console.WriteLine("\n\nMetadata of the song:");
Console.WriteLine($"Title: {_title}");
Console.WriteLine($"Artist: {_artist}");
Console.WriteLine($"Album: {_album}");
Console.WriteLine($"Genre: {_genre}");
Console.WriteLine($"Year: {_year}");
Console.WriteLine($"Duration: {_duration}\n\n");
_logger.Info("Metadata of the song");
_logger.Info($"Title: {_title}");
_logger.Info($"Artist: {_artist}");
_logger.Info($"Album: {_album}");
_logger.Info($"Genre: {_genre}");
_logger.Info($"Year: {_year}");
_logger.Info($"Duration: {_duration}");
}
private void PrintMetadata(Song song, string message)
{
Console.WriteLine($"\n\n{message}");
Console.WriteLine($"Title: {song.Title}");
Console.WriteLine($"Artist: {song.Artist}");
Console.WriteLine($"Album: {song.Album}");
Console.WriteLine($"Genre: {song.Genre}");
Console.WriteLine($"Year: {song.Year}");
Console.WriteLine($"Duration: {song.Duration}\n\n");
_logger.Info("Metadata of the song");
_logger.Info($"Title: {_title}");
_logger.Info($"Artist: {_artist}");
_logger.Info($"Album: {_album}");
_logger.Info($"Genre: {_genre}");
_logger.Info($"Year: {_year}");
_logger.Info($"Duration: {_duration}");
}
private void PrintMetadata(Song song, string message)
{
Console.WriteLine($"\n\n{message}");
Console.WriteLine($"Title: {song.Title}");
Console.WriteLine($"Artist: {song.Artist}");
Console.WriteLine($"Album: {song.Album}");
Console.WriteLine($"Genre: {song.Genre}");
Console.WriteLine($"Year: {song.Year}");
Console.WriteLine($"Duration: {song.Duration}\n\n");
_logger.Info(message);
_logger.Info($"Title: {_title}");
_logger.Info($"Artist: {_artist}");
_logger.Info($"Album: {_album}");
_logger.Info($"Genre: {_genre}");
_logger.Info($"Year: {_year}");
_logger.Info($"Duration: {_duration}");
}
_logger.Info(message);
_logger.Info($"Title: {_title}");
_logger.Info($"Artist: {_artist}");
_logger.Info($"Album: {_album}");
_logger.Info($"Genre: {_genre}");
_logger.Info($"Year: {_year}");
_logger.Info($"Duration: {_duration}");
}
private SortedDictionary<string, bool> CheckSongValues(Song song)
{
var songValues = new SortedDictionary<string, bool>();
Console.WriteLine("Checking for null data");
_logger.Info("Checking for null data");
try
{
songValues["Title"] = String.IsNullOrEmpty(song.Title);
songValues["Artists"] = String.IsNullOrEmpty(song.Artist);
songValues["Album"] = String.IsNullOrEmpty(song.AlbumTitle);
songValues["Genre"] = String.IsNullOrEmpty(song.Genre);
if (song.Year == null)
{
songValues["Year"] = true;
}
else if (song.Year==0)
{
songValues["Year"] = true;
}
else
{
songValues["Year"] = false;
}
Console.WriteLine("Checking for null data completed");
_logger.Info("Checking for null data completed");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: \n{msg}");
_logger.Error(msg, "An error occurred");
}
private SortedDictionary<string, bool> CheckSongValues(Song song)
{
var songValues = new SortedDictionary<string, bool>();
Console.WriteLine("Checking for null data");
_logger.Info("Checking for null data");
try
{
songValues["Title"] = String.IsNullOrEmpty(song.Title);
songValues["Artists"] = String.IsNullOrEmpty(song.Artist);
songValues["Album"] = String.IsNullOrEmpty(song.AlbumTitle);
songValues["Genre"] = String.IsNullOrEmpty(song.Genre);
return songValues;
}
#endregion
}
if (song.Year == null)
songValues["Year"] = true;
else if (song.Year==0)
songValues["Year"] = true;
else
songValues["Year"] = false;
Console.WriteLine("Checking for null data completed");
_logger.Info("Checking for null data completed");
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred: \n{msg}");
_logger.Error(msg, "An error occurred");
}
return songValues;
}
#endregion
}
}
+58 -61
View File
@@ -9,85 +9,82 @@ using Icarus.Models;
namespace Icarus.Controllers.Utilities
{
public class PasswordEncryption
{
#region Fields
private static Logger _logger = NLog.LogManager.GetCurrentClassLogger();
#endregion
public class PasswordEncryption
{
#region Fields
private static Logger _logger = NLog.LogManager.GetCurrentClassLogger();
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructor
#endregion
#region Constructor
#endregion
#region Methods
public bool VerifyPassword(User user, string password)
{
try
{
var result = BCrypt.Net.BCrypt.Verify(password, user.Password);
#region Methods
public bool VerifyPassword(User user, string password)
{
try
{
var result = BCrypt.Net.BCrypt.Verify(password, user.Password);
return result;
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
return result;
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
return false;
}
return false;
}
public string HashPassword(User user)
{
try
{
string hashedPassword = string.Empty;
hashedPassword = BCrypt.Net.BCrypt.HashPassword(user.Password);
public string HashPassword(User user)
{
try
{
string hashedPassword = string.Empty;
hashedPassword = BCrypt.Net.BCrypt.HashPassword(user.Password);
_logger.Info("Successfully hashed password");
_logger.Info("Successfully hashed password");
return hashedPassword;
return hashedPassword;
}
catch (Exception ex)
{
var exMsg = ex.Message;
_logger.Error(exMsg, "An error occurred");
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
_logger.Error(exMsg, "An error occurred");
}
return null;
}
return null;
}
string GenerateHash(string password, byte[] salt)
{
string GenerateHash(string password, byte[] salt)
{
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256/8));
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password, salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256/8));
return hashed;
}
return hashed;
}
byte[] GenerateSalt()
{
byte[] salt = new byte[128/8];
byte[] GenerateSalt()
{
byte[] salt = new byte[128/8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
using (var rng = RandomNumberGenerator.Create())
rng.GetBytes(salt);
return salt;
}
#endregion
}
return salt;
}
#endregion
}
}
+49 -57
View File
@@ -12,74 +12,66 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/album")]
[ApiController]
public class AlbumController : ControllerBase
{
#region Fields
private readonly ILogger<AlbumController> _logger;
#endregion
[Route("api/v1/album")]
[ApiController]
public class AlbumController : ControllerBase
{
#region Fields
private readonly ILogger<AlbumController> _logger;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
public AlbumController(ILogger<AlbumController> logger)
{
_logger = logger;
}
#endregion
#region Constructors
public AlbumController(ILogger<AlbumController> logger)
{
_logger = logger;
}
#endregion
#region HTTP Routes
[HttpGet]
[Authorize("read:albums")]
public IActionResult Get()
{
List<Album> albums = new List<Album>();
#region HTTP Routes
[HttpGet]
[Authorize("read:albums")]
public IActionResult Get()
{
List<Album> albums = new List<Album>();
AlbumRepository albumStoreContext = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
AlbumRepository albumStoreContext = HttpContext.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
albums = albumStoreContext.GetAlbums();
albums = albumStoreContext.GetAlbums();
if (albums.Count > 0)
{
return Ok(albums);
}
else
{
return NotFound();
}
}
if (albums.Count > 0)
return Ok(albums);
else
return NotFound();
}
[HttpGet("{id}")]
[Authorize("read:albums")]
public IActionResult Get(int id)
{
Album album = new Album
{
AlbumId = id
};
[HttpGet("{id}")]
[Authorize("read:albums")]
public IActionResult Get(int id)
{
Album album = new Album
{
AlbumId = id
};
AlbumRepository albumStoreContext = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
AlbumRepository albumStoreContext = HttpContext.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
if (albumStoreContext.DoesAlbumExist(album))
{
album = albumStoreContext.GetAlbum(album);
if (albumStoreContext.DoesAlbumExist(album))
{
album = albumStoreContext.GetAlbum(album);
return Ok(album);
}
else
{
return NotFound();
}
}
#endregion
}
return Ok(album);
}
else
return NotFound();
}
#endregion
}
}
+49 -58
View File
@@ -13,73 +13,64 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/artist")]
[ApiController]
public class ArtistController : ControllerBase
{
#region Fields
private readonly ILogger<ArtistController> _logger;
#endregion
[Route("api/v1/artist")]
[ApiController]
public class ArtistController : ControllerBase
{
#region Fields
private readonly ILogger<ArtistController> _logger;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
public ArtistController(ILogger<ArtistController> logger)
{
_logger = logger;
}
#endregion
#region Constructors
public ArtistController(ILogger<ArtistController> logger)
{
_logger = logger;
}
#endregion
#region HTTP Routes
[HttpGet]
[Authorize("read:artists")]
public IActionResult Get()
{
ArtistRepository artistStoreContext = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
#region HTTP Routes
[HttpGet]
[Authorize("read:artists")]
public IActionResult Get()
{
ArtistRepository artistStoreContext = HttpContext.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
var artists = artistStoreContext.GetArtists();
var artists = artistStoreContext.GetArtists();
if (artists.Count > 0)
{
return Ok(artists);
}
else
{
return NotFound();
}
}
if (artists.Count > 0)
return Ok(artists);
else
return NotFound();
}
[HttpGet("{id}")]
[Authorize("read:artists")]
public IActionResult Get(int id)
{
Artist artist = new Artist
{
ArtistId = id
};
ArtistRepository artistStoreContext = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
[HttpGet("{id}")]
[Authorize("read:artists")]
public IActionResult Get(int id)
{
Artist artist = new Artist
{
ArtistId = id
};
ArtistRepository artistStoreContext = HttpContext.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
if (artistStoreContext.DoesArtistExist(artist))
{
artist = artistStoreContext.GetArtist(artist);
if (artistStoreContext.DoesArtistExist(artist))
{
artist = artistStoreContext.GetArtist(artist);
return Ok(artist);
}
else
{
return NotFound();
}
}
#endregion
}
return Ok(artist);
}
else
return NotFound();
}
#endregion
}
}
+49 -57
View File
@@ -11,74 +11,66 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/genre")]
[ApiController]
public class GenreController : ControllerBase
{
#region Fields
private readonly ILogger<GenreController> _logger;
#endregion
[Route("api/v1/genre")]
[ApiController]
public class GenreController : ControllerBase
{
#region Fields
private readonly ILogger<GenreController> _logger;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
public GenreController(ILogger<GenreController> logger)
{
_logger = logger;
}
#endregion
#region Constructors
public GenreController(ILogger<GenreController> logger)
{
_logger = logger;
}
#endregion
#region HTTP Routes
[HttpGet]
[Authorize("read:genre")]
public IActionResult Get()
{
var genres = new List<Genre>();
#region HTTP Routes
[HttpGet]
[Authorize("read:genre")]
public IActionResult Get()
{
var genres = new List<Genre>();
var genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
var genreStore = HttpContext.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
genres = genreStore.GetGenres();
genres = genreStore.GetGenres();
if (genres.Count > 0)
{
return Ok(genres);
}
else
{
return NotFound(new List<Genre>());
}
}
if (genres.Count > 0)
return Ok(genres);
else
return NotFound(new List<Genre>());
}
[HttpGet("{id}")]
[Authorize("read:genre")]
public IActionResult Get(int id)
{
var genre = new Genre
{
GenreId = id
};
[HttpGet("{id}")]
[Authorize("read:genre")]
public IActionResult Get(int id)
{
var genre = new Genre
{
GenreId = id
};
var genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
var genreStore = HttpContext.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
if (genreStore.DoesGenreExist(genre))
{
genre = genreStore.GetGenre(genre);
if (genreStore.DoesGenreExist(genre))
{
genre = genreStore.GetGenre(genre);
return Ok(genre);
}
else
{
return NotFound(new Genre());
}
}
#endregion
}
return Ok(genre);
}
else
return NotFound(new Genre());
}
#endregion
}
}
+54 -55
View File
@@ -15,75 +15,74 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/login")]
[ApiController]
public class LoginController : ControllerBase
{
#region Fields
private IConfiguration _config;
private ILogger<LoginController> _logger;
#endregion
[Route("api/v1/login")]
[ApiController]
public class LoginController : ControllerBase
{
#region Fields
private IConfiguration _config;
private ILogger<LoginController> _logger;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Contructors
public LoginController(IConfiguration config, ILogger<LoginController> logger)
{
_config = config;
_logger = logger;
}
#endregion
#region Contructors
public LoginController(IConfiguration config, ILogger<LoginController> logger)
{
_config = config;
_logger = logger;
}
#endregion
#region HTTP endpoints
public IActionResult Post([FromBody] User user)
{
UserRepository context = HttpContext
.RequestServices
.GetService(typeof(UserRepository)) as UserRepository;
#region HTTP endpoints
public IActionResult Post([FromBody] User user)
{
UserRepository context = HttpContext.RequestServices
.GetService(typeof(UserRepository)) as UserRepository;
_logger.LogInformation("Starting process of validating credentials");
var message = "Invalid credentials";
var password = user.Password;
_logger.LogInformation("Starting process of validating credentials");
var message = "Invalid credentials";
var password = user.Password;
var loginRes = new LoginResult
{
Username = user.Username
};
var loginRes = new LoginResult
{
Username = user.Username
};
if (context.DoesUserExist(user))
{
user = context.RetrieveUser(user);
if (context.DoesUserExist(user))
{
user = context.RetrieveUser(user);
var validatePass = new PasswordEncryption();
var validated = validatePass.VerifyPassword(user, password);
if (!validated)
{
loginRes.Message = message;
_logger.LogInformation(message);
var validatePass = new PasswordEncryption();
var validated = validatePass.VerifyPassword(user, password);
if (!validated)
{
loginRes.Message = message;
_logger.LogInformation(message);
return Ok(loginRes);
}
return Ok(loginRes);
}
_logger.LogInformation("Successfully validated user credentials");
_logger.LogInformation("Successfully validated user credentials");
TokenManager tk = new TokenManager(_config);
TokenManager tk = new TokenManager(_config);
loginRes = tk.RetrieveLoginResult(user);
loginRes = tk.RetrieveLoginResult(user);
return Ok(loginRes);
}
else
{
loginRes.Message = message;
return Ok(loginRes);
}
else
{
loginRes.Message = message;
return NotFound(loginRes);
}
}
#endregion
}
return NotFound(loginRes);
}
}
#endregion
}
}
+42 -43
View File
@@ -14,58 +14,57 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/register")]
[ApiController]
public class RegisterController : ControllerBase
{
#region Fields
private IConfiguration _config;
#endregion
[Route("api/v1/register")]
[ApiController]
public class RegisterController : ControllerBase
{
#region Fields
private IConfiguration _config;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructor
public RegisterController(IConfiguration config)
{
_config = config;
}
#endregion
#region Constructor
public RegisterController(IConfiguration config)
{
_config = config;
}
#endregion
[HttpPost]
public IActionResult Post([FromBody] User user)
{
PasswordEncryption pe = new PasswordEncryption();
user.Password = pe.HashPassword(user);
user.EmailVerified = false;
[HttpPost]
public IActionResult Post([FromBody] User user)
{
PasswordEncryption pe = new PasswordEncryption();
user.Password = pe.HashPassword(user);
user.EmailVerified = false;
UserRepository context = HttpContext
.RequestServices
.GetService(typeof(UserRepository)) as UserRepository;
UserRepository context = HttpContext.RequestServices
.GetService(typeof(UserRepository)) as UserRepository;
context.SaveUser(user);
context.SaveUser(user);
var registerResult = new RegisterResult
{
Username = user.Username
};
var registerResult = new RegisterResult
{
Username = user.Username
};
if (context.DoesUserExist(user))
{
registerResult.Message = "Successful registration";
registerResult.SuccessfullyRegistered = true;
if (context.DoesUserExist(user))
{
registerResult.Message = "Successful registration";
registerResult.SuccessfullyRegistered = true;
return Ok(registerResult);
}
else
{
registerResult.Message = "Registration failed";
registerResult.SuccessfullyRegistered = false;
return Ok(registerResult);
}
else
{
registerResult.Message = "Registration failed";
registerResult.SuccessfullyRegistered = false;
return Ok(registerResult);
}
}
}
return Ok(registerResult);
}
}
}
}
+35 -36
View File
@@ -17,49 +17,48 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/compressed/data")]
[ApiController]
public class SongCompressedDataController : ControllerBase
{
#region Fields
private IConfiguration _config;
private string _songTempDir;
private string _archiveDir;
#endregion
[Route("api/v1/song/compressed/data")]
[ApiController]
public class SongCompressedDataController : ControllerBase
{
#region Fields
private IConfiguration _config;
private string _songTempDir;
private string _archiveDir;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructor
public SongCompressedDataController(IConfiguration config)
{
_config = config;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_archiveDir = _config.GetValue<string>("ArchivePath");
}
#endregion
#region Constructor
public SongCompressedDataController(IConfiguration config)
{
_config = config;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_archiveDir = _config.GetValue<string>("ArchivePath");
}
#endregion
#region API Routes
[HttpGet("{id}")]
[Authorize("download:songs")]
public async Task<IActionResult> Get(int id)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
#region API Routes
[HttpGet("{id}")]
[Authorize("download:songs")]
public async Task<IActionResult> Get(int id)
{
SongRepository context = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
SongCompression cmp = new SongCompression(_archiveDir);
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");
SongData song = await cmp.RetrieveCompressedSong(context.GetSong(id));
Console.WriteLine("Starting process of retrieving comrpessed song");
SongData song = await cmp.RetrieveCompressedSong(context.GetSong(id));
return File(song.Data, "application/x-msdownload", cmp.CompressedSongFilename);
}
#endregion
}
return File(song.Data, "application/x-msdownload", cmp.CompressedSongFilename);
}
#endregion
}
}
+78 -95
View File
@@ -16,118 +16,101 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song")]
[ApiController]
public class SongController : ControllerBase
{
#region Fields
private readonly ILogger<SongController> _logger;
private IConfiguration _config;
private SongManager _songMgr;
#endregion
[Route("api/v1/song")]
[ApiController]
public class SongController : ControllerBase
{
#region Fields
private readonly ILogger<SongController> _logger;
private IConfiguration _config;
private SongManager _songMgr;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructor
public SongController(IConfiguration config, ILogger<SongController> logger)
{
_config = config;
_logger = logger;
_songMgr = new SongManager(config);
}
#endregion
#region Constructor
public SongController(IConfiguration config, ILogger<SongController> logger)
{
_config = config;
_logger = logger;
_songMgr = new SongManager(config);
}
#endregion
[HttpGet]
[Authorize("read:song_details")]
public IActionResult Get()
{
List<Song> songs = new List<Song>();
Console.WriteLine("Attemtping to retrieve songs");
_logger.LogInformation("Attempting to retrieve songs");
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
[HttpGet]
[Authorize("read:song_details")]
public IActionResult Get()
{
List<Song> songs = new List<Song>();
Console.WriteLine("Attemtping to retrieve songs");
_logger.LogInformation("Attempting to retrieve songs");
SongRepository context = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
songs = context.GetAllSongs();
songs = context.GetAllSongs();
if (songs.Count > 0)
{
return Ok(songs);
}
else
{
return NotFound();
}
}
if (songs.Count > 0)
return Ok(songs);
else
return NotFound();
}
[HttpGet("{id}")]
[Authorize("read:song_details")]
public IActionResult Get(int id)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
Song song = new Song { Id = id };
song = context.GetSong(song);
[HttpGet("{id}")]
[Authorize("read:song_details")]
public IActionResult Get(int id)
{
SongRepository context = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
Song song = new Song { Id = id };
song = context.GetSong(song);
Console.WriteLine("Here");
Console.WriteLine("Here");
if (song.Id != 0)
{
return Ok(song);
}
else
{
return NotFound();
}
}
if (song.Id != 0)
return Ok(song);
else
return NotFound();
}
[Authorize("update:songs")]
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Song song)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
[Authorize("update:songs")]
[HttpPut("{id}")]
public IActionResult Put(int id, [FromBody] Song song)
{
SongRepository context = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
ArtistRepository artistStore = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
ArtistRepository artistStore = HttpContext.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
AlbumRepository albumStore = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
GenreRepository genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
AlbumRepository albumStore = HttpContext.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
GenreRepository genreStore = HttpContext.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
YearRepository yearStore = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
YearRepository yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
song.Id = id;
Console.WriteLine("Retrieving filepath of song");
_logger.LogInformation("Retrieving filepath of song");
song.Id = id;
Console.WriteLine("Retrieving filepath of song");
_logger.LogInformation("Retrieving filepath of song");
if (!context.DoesSongExist(song))
{
return NotFound(new SongResult
{
Message = "Song does not exist"
});
}
if (!context.DoesSongExist(song))
return NotFound(new SongResult
{
Message = "Song does not exist"
});
var songRes = _songMgr.UpdateSong(song, context, albumStore, artistStore, genreStore,
yearStore);
var songRes = _songMgr.UpdateSong(song, context, albumStore, artistStore, genreStore,
yearStore);
return Ok(songRes);
}
}
return Ok(songRes);
}
}
}
+110 -115
View File
@@ -17,133 +17,128 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/data")]
[ApiController]
public class SongDataController : ControllerBase
{
#region Fields
private IConfiguration _config;
private ILogger<SongDataController> _logger;
private SongManager _songMgr;
private string _songTempDir;
#endregion
[Route("api/v1/song/data")]
[ApiController]
public class SongDataController : ControllerBase
{
#region Fields
private IConfiguration _config;
private ILogger<SongDataController> _logger;
private SongManager _songMgr;
private string _songTempDir;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructor
public SongDataController(IConfiguration config, ILogger<SongDataController> logger)
{
_config = config;
_logger = logger;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_songMgr = new SongManager(config, _songTempDir);
}
#endregion
#region Constructor
public SongDataController(IConfiguration config, ILogger<SongDataController> logger)
{
_config = config;
_logger = logger;
_songTempDir = _config.GetValue<string>("TemporaryMusicPath");
_songMgr = new SongManager(config, _songTempDir);
}
#endregion
[HttpGet("{id}")]
[Route("private-scoped")]
[Authorize("download:songs")]
public async Task<IActionResult> Get(int id)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
var songMetaData = context.GetSong(id);
SongData song = await _songMgr.RetrieveSong(songMetaData);
return File(song.Data, "application/x-msdownload", songMetaData.Filename);
}
[HttpGet("{id}")]
[Route("private-scoped")]
[Authorize("download:songs")]
public async Task<IActionResult> Get(int id)
{
SongRepository context = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
var songMetaData = context.GetSong(id);
SongData song = await _songMgr.RetrieveSong(songMetaData);
return File(song.Data, "application/x-msdownload", songMetaData.Filename);
}
[HttpPost]
[Authorize("upload:songs")]
public async Task Post([FromForm(Name = "file")] List<IFormFile> songData)
{
try
{
SongRepository songRepository = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
AlbumRepository albumStoreContext = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
ArtistRepository artistStoreContext = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
GenreRepository genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
YearRepository yearStore = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
[HttpPost]
[Authorize("upload:songs")]
public async Task Post([FromForm(Name = "file")] List<IFormFile> songData)
{
try
{
SongRepository songRepository = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
Console.WriteLine("Uploading song...");
_logger.LogInformation("Uploading song...");
AlbumRepository albumStoreContext = HttpContext.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
var uploads = _songTempDir;
Console.WriteLine($"Song Root Path {uploads}");
_logger.LogInformation($"Song root path {uploads}");
foreach (var sng in songData)
{
if (sng.Length > 0) {
Console.WriteLine($"Song filename {sng.FileName}");
_logger.LogInformation($"Song filename {sng.FileName}");
ArtistRepository artistStoreContext = HttpContext.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
await _songMgr.SaveSongToFileSystem(sng, songRepository,
albumStoreContext, artistStoreContext,
genreStore, yearStore);
}
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.LogError(msg, "An error occurred");
}
}
GenreRepository genreStore = HttpContext.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
[HttpDelete("{id}")]
[Authorize("delete:songs")]
public IActionResult Delete(int id)
{
SongRepository context = HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
AlbumRepository albumStore = HttpContext
.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
ArtistRepository artistStore = HttpContext
.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
GenreRepository genreStore = HttpContext
.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
YearRepository yearStore = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
var songMetaData = new Song{ Id = id };
Console.WriteLine($"Id {songMetaData.Id}");
songMetaData = context.GetSong(songMetaData);
YearRepository yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
if (string.IsNullOrEmpty(songMetaData.Title))
{
_logger.LogInformation("Song does not exist");
return NotFound("Song does not exist");
}
else
{
_logger.LogInformation("Starting process of deleting song from the filesystem and database");
Console.WriteLine("Uploading song...");
_logger.LogInformation("Uploading song...");
_songMgr.DeleteSong(songMetaData, context, albumStore,
artistStore, genreStore, yearStore);
var uploads = _songTempDir;
Console.WriteLine($"Song Root Path {uploads}");
_logger.LogInformation($"Song root path {uploads}");
foreach (var sng in songData)
if (sng.Length > 0) {
Console.WriteLine($"Song filename {sng.FileName}");
_logger.LogInformation($"Song filename {sng.FileName}");
return Ok();
}
}
}
await _songMgr.SaveSongToFileSystem(sng, songRepository,
albumStoreContext, artistStoreContext,
genreStore, yearStore);
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.LogError(msg, "An error occurred");
}
}
[HttpDelete("{id}")]
[Authorize("delete:songs")]
public IActionResult Delete(int id)
{
SongRepository context = HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
AlbumRepository albumStore = HttpContext.RequestServices
.GetService(typeof(AlbumRepository)) as AlbumRepository;
ArtistRepository artistStore = HttpContext.RequestServices
.GetService(typeof(ArtistRepository)) as ArtistRepository;
GenreRepository genreStore = HttpContext.RequestServices
.GetService(typeof(GenreRepository)) as GenreRepository;
YearRepository yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
var songMetaData = new Song{ Id = id };
Console.WriteLine($"Id {songMetaData.Id}");
songMetaData = context.GetSong(songMetaData);
if (string.IsNullOrEmpty(songMetaData.Title))
{
_logger.LogInformation("Song does not exist");
return NotFound("Song does not exist");
}
else
{
_logger.LogInformation("Starting process of deleting song from the filesystem and database");
_songMgr.DeleteSong(songMetaData, context, albumStore,
artistStore, genreStore, yearStore);
return Ok();
}
}
}
}
+33 -36
View File
@@ -16,52 +16,49 @@ using Icarus.Database.Repositories;
namespace Icarus.Controllers.V1
{
[Route("api/v1/song/stream")]
[ApiController]
public class SongStreamController : ControllerBase
{
#region Fields
private ILogger<SongStreamController> _logger;
#endregion
[Route("api/v1/song/stream")]
[ApiController]
public class SongStreamController : ControllerBase
{
#region Fields
private ILogger<SongStreamController> _logger;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructor
public SongStreamController(ILogger<SongStreamController> logger)
{
_logger = logger;
}
#endregion
#region Constructor
public SongStreamController(ILogger<SongStreamController> logger)
{
_logger = logger;
}
#endregion
#region HTTP endpoints
[HttpGet("{id}")]
[Authorize("stream:songs")]
public async Task<IActionResult> Get(int id)
{
var songStore= HttpContext
.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
#region HTTP endpoints
[HttpGet("{id}")]
[Authorize("stream:songs")]
public async Task<IActionResult> Get(int id)
{
var songStore= HttpContext.RequestServices
.GetService(typeof(SongRepository)) as SongRepository;
var song = songStore.GetSong(new Song { Id = id });
var song = songStore.GetSong(new Song { Id = id });
var mem = new MemoryStream();
var mem = new MemoryStream();
using (var stream = new FileStream(song.SongPath, FileMode.Open, FileAccess.Read))
{
await stream.CopyToAsync(mem);
}
using (var stream = new FileStream(song.SongPath, FileMode.Open, FileAccess.Read))
await stream.CopyToAsync(mem);
mem.Position = 0;
mem.Position = 0;
_logger.LogInformation("Starting to stream song...>");
Console.WriteLine("Starting to streamsong...");
_logger.LogInformation("Starting to stream song...>");
Console.WriteLine("Starting to streamsong...");
return File(mem, "application/octet-stream", Path.GetFileName(song.SongPath));
}
#endregion
}
return File(mem, "application/octet-stream", Path.GetFileName(song.SongPath));
}
#endregion
}
}
+49 -57
View File
@@ -11,74 +11,66 @@ 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
[Route("api/v1/year")]
[ApiController]
public class YearController : ControllerBase
{
#region Fields
private readonly ILogger<YearController> _logger;
#endregion
#region Properties
#endregion
#region Properties
#endregion
#region Constructors
public YearController(ILogger<YearController> logger)
{
_logger = logger;
}
#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>();
#region HTTP Routes
[HttpGet]
[Authorize("read:year")]
public IActionResult Get()
{
var yearValues = new List<Year>();
var yearStore = HttpContext
.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
var yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
yearValues = yearStore.GetSongYears();
yearValues = yearStore.GetSongYears();
if (yearValues.Count > 0)
{
return Ok(yearValues);
}
else
{
return NotFound(new List<Year>());
}
}
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
};
[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;
var yearStore = HttpContext.RequestServices
.GetService(typeof(YearRepository)) as YearRepository;
if (yearStore.DoesYearExist(year))
{
year = yearStore.GetSongYear(year);
if (yearStore.DoesYearExist(year))
{
year = yearStore.GetSongYear(year);
return Ok(year);
}
else
{
return NotFound(new Year());
}
}
#endregion
}
return Ok(year);
}
else
return NotFound(new Year());
}
#endregion
}
}