diff --git a/.gitignore b/.gitignore index a15f445..9afb644 100644 --- a/.gitignore +++ b/.gitignore @@ -18,3 +18,7 @@ Icarus/bin Icarus/obj Models/bin Models/obj +Migrations +Icarus.txt +Storage +.DS_Store diff --git a/Icarus/Controllers/Managers/AlbumManager.cs b/Icarus/Controllers/Managers/AlbumManager.cs index e6a3642..8b80a93 100644 --- a/Icarus/Controllers/Managers/AlbumManager.cs +++ b/Icarus/Controllers/Managers/AlbumManager.cs @@ -85,7 +85,7 @@ public class AlbumManager : BaseManager if (string.IsNullOrEmpty(newAlbumTitle)) newAlbumTitle = oldAlbumTitle; - if ((string.IsNullOrEmpty(newAlbumTitle) && string.IsNullOrEmpty(newAlbumArtist) || + if ((string.IsNullOrEmpty(newAlbumTitle) && string.IsNullOrEmpty(newAlbumArtist) || oldAlbumTitle!.Equals(newAlbumTitle) && oldAlbumArtist!.Equals(newAlbumArtist))) { _logger.Info("No change to the song's album"); diff --git a/Icarus/Controllers/Managers/ArtistManager.cs b/Icarus/Controllers/Managers/ArtistManager.cs index 8e7dcdb..84c5a3d 100644 --- a/Icarus/Controllers/Managers/ArtistManager.cs +++ b/Icarus/Controllers/Managers/ArtistManager.cs @@ -84,7 +84,7 @@ public class ArtistManager : BaseManager _artistContext.Add(newArtistRecord); _artistContext.SaveChanges(); - + return newArtistRecord; } else diff --git a/Icarus/Controllers/Managers/CoverArtManager.cs b/Icarus/Controllers/Managers/CoverArtManager.cs index 51b48c7..afa9c06 100644 --- a/Icarus/Controllers/Managers/CoverArtManager.cs +++ b/Icarus/Controllers/Managers/CoverArtManager.cs @@ -48,7 +48,7 @@ public class CoverArtManager : BaseManager try { var stockCoverArtPath = _rootCoverArtPath + _filename; - if (!string.Equals(stockCoverArtPath, coverArt.ImagePath(), + if (!string.Equals(stockCoverArtPath, coverArt.ImagePath(), StringComparison.CurrentCultureIgnoreCase)) { _logger.Info("Song does not contain the stock cover art"); @@ -87,7 +87,7 @@ public class CoverArtManager : BaseManager var metaData = new MetadataRetriever(); var imgBytes = metaData.RetrieveCoverArtBytes(song); - + if (imgBytes != null) { _logger.Info("Saving cover art to the filesystem"); @@ -121,7 +121,7 @@ public class CoverArtManager : BaseManager var msg = ex.Message; _logger.Error(msg, "An error occurred"); } - + return null; } @@ -173,7 +173,7 @@ public class CoverArtManager : BaseManager if (!File.Exists(_rootCoverArtPath + _filename)) { - File.WriteAllBytes(_rootCoverArtPath + _filename, + File.WriteAllBytes(_rootCoverArtPath + _filename, _stockCoverArt!); Console.WriteLine("Copied Stock Cover Art"); } diff --git a/Icarus/Controllers/Managers/DirectoryManager.cs b/Icarus/Controllers/Managers/DirectoryManager.cs index f1522a4..3f89df8 100644 --- a/Icarus/Controllers/Managers/DirectoryManager.cs +++ b/Icarus/Controllers/Managers/DirectoryManager.cs @@ -53,7 +53,7 @@ public class DirectoryManager : BaseManager public static string GenerateDownloadFilename(int length, string extension, string title, bool? randomize) { - if (randomize.HasValue && randomize.Value) + if (randomize.HasValue && randomize.Value) { return GenerateFilename(length) + extension; } @@ -100,13 +100,13 @@ public class DirectoryManager : BaseManager var artistDirectory = ArtistDirectory(); if (IsDirectoryEmpty(albumDirectory)) { - Directory.Delete(albumDirectory); - Console.WriteLine($"directory {albumDirectory} deleted"); + Directory.Delete(albumDirectory); + Console.WriteLine($"directory {albumDirectory} deleted"); } if (IsDirectoryEmpty(artistDirectory)) { - Directory.Delete(artistDirectory); - Console.WriteLine($"directory {artistDirectory} deleted"); + Directory.Delete(artistDirectory); + Console.WriteLine($"directory {artistDirectory} deleted"); } } catch (Exception ex) @@ -116,6 +116,38 @@ public class DirectoryManager : BaseManager } } + public int DeleteEmptyDirectories(string? directory, int level) + { + var deleted = 0; + + try + { + var curDir = directory; + for (var i = 0; i < level; i++) + { + if (!System.IO.Directory.Exists(curDir)) + { + continue; + } + + if (this.IsDirectoryEmpty(curDir)) + { + System.IO.Directory.Delete(curDir); + deleted++; + } + + curDir = System.IO.Directory.GetParent(curDir).ToString(); + } + } + catch (Exception ex) + { + var exMsg = ex.Message; + Console.WriteLine($"An error occurred {exMsg}"); + } + + return deleted; + } + public void DeleteEmptyDirectories(Song song) { try @@ -125,12 +157,12 @@ public class DirectoryManager : BaseManager if (IsDirectoryEmpty(albumDirectory)) { - Directory.Delete(albumDirectory); + Directory.Delete(albumDirectory); _logger.Info("Album directory deleted"); } if (IsDirectoryEmpty(artistDirectory)) { - Directory.Delete(artistDirectory); + Directory.Delete(artistDirectory); _logger.Info("Artist directory deleted"); } } @@ -187,7 +219,7 @@ public class DirectoryManager : BaseManager private class DirEnt { - public string? Pre { get; set;} + public string? Pre { get; set; } public string? Path { get; set; } public string? Post { get; set; } } diff --git a/Icarus/Controllers/Managers/SongManager.cs b/Icarus/Controllers/Managers/SongManager.cs index 92b3ee6..d581671 100644 --- a/Icarus/Controllers/Managers/SongManager.cs +++ b/Icarus/Controllers/Managers/SongManager.cs @@ -3,9 +3,11 @@ using NLog; using Icarus.Controllers.Utilities; using Icarus.Models; using Icarus.Database.Contexts; +using TagLib.Mpeg4; namespace Icarus.Controllers.Managers; + public class SongManager : BaseManager { #region Fields @@ -107,11 +109,18 @@ public class SongManager : BaseManager try { var songPath = songMetaData.SongPath(); - File.Delete(songPath); - successful = true; + System.IO.File.Delete(songPath); + successful = !System.IO.File.Exists(songPath); + if (successful) + { + Console.WriteLine("Song successfully deleted"); + } DirectoryManager dirMgr = new DirectoryManager(_config!, songMetaData); - dirMgr.DeleteEmptyDirectories(); - Console.WriteLine("Song successfully deleted"); + var deletedAmount = dirMgr.DeleteEmptyDirectories(songMetaData.SongDirectory, 1); + if (deletedAmount > 0) + { + Console.WriteLine($"{deletedAmount} directories deleted"); + } } catch (Exception ex) { @@ -196,6 +205,7 @@ public class SongManager : BaseManager } // Change the name of this method to only focus on wav files + [Obsolete("Support for uplodaing wav files will end. Use the flac alternative instead - SaveFlacSongToFileSystem(..)")] public Song SaveSongToFileSystem(IFormFile songFile, IFormFile coverArtData, Song song) { if (string.IsNullOrEmpty(song.SongDirectory)) @@ -252,8 +262,8 @@ public class SongManager : BaseManager return song; } - public Song SaveFlacSongToFileSystem(IFormFile songFile, IFormFile coverArtData, Song song) - { + public Song SaveFlacSongToFileSystem(IFormFile songFile, IFormFile coverArtData, Song song) + { // Save temp song (Should already be saved to the filesystem by the time it gets to this method) // Save cover art // Update the song's metadata with the song object @@ -283,10 +293,10 @@ public class SongManager : BaseManager SaveSongToDatabase(song, coverArt); return song; - } + } - private void MoveSongToFinalDestination(string sourcePath, string targetPath) - { + private void MoveSongToFinalDestination(string sourcePath, string targetPath) + { using (var fileStream = new FileStream(targetPath, FileMode.Create)) { var songBytes = System.IO.File.ReadAllBytes(sourcePath); @@ -315,8 +325,8 @@ public class SongManager : BaseManager _logger.Info("Song successfully saved to filesystem"); } - } - + } + public async Task RetrieveSong(Song songMetaData) { var song = new SongData(); @@ -340,7 +350,7 @@ public class SongManager : BaseManager private async Task RetrieveSongFromFileSystem(Song details) { byte[] uncompressedSong = await System.IO.File.ReadAllBytesAsync(details.SongPath()); - + return new SongData { Data = uncompressedSong @@ -366,6 +376,28 @@ public class SongManager : BaseManager } + public Icarus.Models.CreateFileResult Create(IFormFile file, string filePath, string prompt) + { + if (System.IO.File.Exists(filePath)) + { + return CreateFileResult.AlreadyExists; + } + + using (var filestream = new FileStream(filePath, FileMode.Create)) + { + Console.WriteLine(prompt); + file.CopyTo(filestream); + + if (System.IO.File.Exists(filePath)) + { + return CreateFileResult.FileCreatedAndExists; + } + } + + return 0; + } + + private bool SongRecordChanged(Song currentSong, Song songUpdates) { var currentTitle = currentSong.Title; @@ -402,9 +434,9 @@ public class SongManager : BaseManager Console.WriteLine($"Error Occurred: {ex.Message}"); } } - - + + private void SaveSongToDatabase(Song song, CoverArt? cover) { _logger.Info("Starting process to save the song to the database"); @@ -425,7 +457,7 @@ public class SongManager : BaseManager coverMgr.SaveCoverArtToDatabase(ref song, ref cover!); } - + private bool DeleteSongFromFilesystem(Song song, bool deleteDirectory = false) { @@ -439,7 +471,7 @@ public class SongManager : BaseManager DeleteEmptyDirectories(ref song, ref song); } - catch(Exception ex) + catch (Exception ex) { var msg = ex.Message; _logger.Error(msg, "An error occurred when attempting to delete the song from the filesystem"); @@ -463,7 +495,7 @@ public class SongManager : BaseManager return true; } - + private void UpdateSongInDatabase(ref Song oldSongRecord, ref Song newSongRecord, ref SongResult result) { var updatedSongRecord = oldSongRecord; diff --git a/Icarus/Controllers/Managers/TokenManager.cs b/Icarus/Controllers/Managers/TokenManager.cs index 8db8dc7..dfa1f2e 100644 --- a/Icarus/Controllers/Managers/TokenManager.cs +++ b/Icarus/Controllers/Managers/TokenManager.cs @@ -53,7 +53,7 @@ public class TokenManager : BaseManager _logger.Info("Serializing token object into JSON"); var tokenObject = JsonConvert.SerializeObject(tokenRequest); - request.AddParameter("application/json; charset=utf-8", + request.AddParameter("application/json; charset=utf-8", tokenObject, ParameterType.RequestBody); request.RequestFormat = DataFormat.Json; @@ -74,7 +74,7 @@ public class TokenManager : BaseManager public LoginResult LoginSymmetric(User user) { - var tokenResult = new TokenTierOne{ TokenType = "JWT" }; + var tokenResult = new TokenTierOne { TokenType = "JWT" }; var payload = Payload(); payload.Add(new Claim("user_id", user.Id.ToString(), ClaimValueTypes.Integer)); @@ -91,7 +91,7 @@ public class TokenManager : BaseManager Expires = DateTime.UtcNow.AddHours(1), SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature), Issuer = _config["Jwt:Issuer"], // Add this line - Audience = _config["Jwt:Audience"] + Audience = _config["Jwt:Audience"] }; tokenResult.AccessToken = tokenHandler.WriteToken(tokenHandler.CreateToken(tokenDescriptor)); @@ -112,8 +112,11 @@ public class TokenManager : BaseManager { return new LoginResult { - UserId = user.Id, Username = user.Username, Token = token.AccessToken, - TokenType = token.TokenType, Expiration = token.Expiration, + UserId = user.Id, + Username = user.Username, + Token = token.AccessToken, + TokenType = token.TokenType, + Expiration = token.Expiration, Message = SUCCESSFUL_TOKEN_MESSAGE }; } @@ -162,13 +165,13 @@ public class TokenManager : BaseManager "download:songs", "read:song_details", "upload:songs", - "delete:songs", - "read:albums", + "delete:songs", + "read:albums", "read:artists", - "update:songs", - "stream:songs", - "read:genre", - "read:year", + "update:songs", + "stream:songs", + "read:genre", + "read:year", "download:cover_art" }; @@ -217,15 +220,17 @@ public class TokenManager : BaseManager { return await System.IO.File.ReadAllTextAsync(filepath); } - + private TokenRequest RetrieveTokenRequest() { _logger.Info("Retrieving token object"); return new TokenRequest { - ClientId = _clientId, ClientSecret = _clientSecret, - Audience = _audience, GrantType = _grantType + ClientId = _clientId, + ClientSecret = _clientSecret, + Audience = _audience, + GrantType = _grantType }; } diff --git a/Icarus/Controllers/Utilities/MetadataRetriever.cs b/Icarus/Controllers/Utilities/MetadataRetriever.cs index 6ebe2da..86d2076 100644 --- a/Icarus/Controllers/Utilities/MetadataRetriever.cs +++ b/Icarus/Controllers/Utilities/MetadataRetriever.cs @@ -9,8 +9,8 @@ public class MetadataRetriever { #region Fields private static NLog.Logger? _logger = NLog.Web.NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger(); - private List? _supportedAudioFileTypes = new List {"wav", "flac"}; - private List? _supportedImageFileTypes = new List {"jpeg", "jpg", "png"}; + private List? _supportedAudioFileTypes = new List { "wav", "flac" }; + private List? _supportedImageFileTypes = new List { "jpeg", "jpg", "png" }; private Song? _updatedSong; private string? _message; private string? _title; @@ -99,7 +99,7 @@ public class MetadataRetriever public bool IsSupportedFile(IFormFile file) { var supportedTypes = this._supportedAudioFileTypes; - this._supportedImageFileTypes!.ForEach(t => + this._supportedImageFileTypes!.ForEach(t => { if (!supportedTypes!.Contains(t)) { @@ -115,7 +115,7 @@ public class MetadataRetriever public bool IsSupportedFile(string path) { var supportedTypes = this._supportedAudioFileTypes; - this._supportedImageFileTypes!.ForEach(t => + this._supportedImageFileTypes!.ForEach(t => { if (!supportedTypes!.Contains(t)) { @@ -199,7 +199,7 @@ public class MetadataRetriever return []; } - + public void UpdateMetadata(Song updatedSong, Song oldSong) { try @@ -267,7 +267,7 @@ public class MetadataRetriever break; case "artists": _updatedSong!.Artist = artist; - fileTag.Tag.Performers = new []{artist}; + fileTag.Tag.Performers = new[] { artist }; break; case "album": _updatedSong!.AlbumTitle = album; @@ -275,7 +275,7 @@ public class MetadataRetriever break; case "genre": _updatedSong!.Genre = genre; - fileTag.Tag.Genres = new []{genre}; + fileTag.Tag.Genres = new[] { genre }; break; case "year": _updatedSong!.Year = year; @@ -283,7 +283,7 @@ public class MetadataRetriever break; case "albumartist": _updatedSong!.AlbumArtist = albumArtist; - fileTag.Tag.AlbumArtists = new []{albumArtist}; + fileTag.Tag.AlbumArtists = new[] { albumArtist }; break; case "track": _updatedSong!.Track = track; @@ -352,7 +352,7 @@ public class MetadataRetriever } return songValues; - } + } private bool CheckIntField(int? value) { diff --git a/Icarus/Controllers/Utilities/PasswordEncryption.cs b/Icarus/Controllers/Utilities/PasswordEncryption.cs index f09374e..9ab73a4 100644 --- a/Icarus/Controllers/Utilities/PasswordEncryption.cs +++ b/Icarus/Controllers/Utilities/PasswordEncryption.cs @@ -70,14 +70,14 @@ public class PasswordEncryption password: password, salt: salt, prf: KeyDerivationPrf.HMACSHA1, iterationCount: 10000, - numBytesRequested: 256/8)); + numBytesRequested: 256 / 8)); return hashed; } byte[] GenerateSalt() { - byte[] salt = new byte[128/8]; + byte[] salt = new byte[128 / 8]; using (var rng = RandomNumberGenerator.Create()) rng.GetBytes(salt); diff --git a/Icarus/Controllers/Utilities/SongCompression.cs b/Icarus/Controllers/Utilities/SongCompression.cs index ea72b2c..078d27d 100644 --- a/Icarus/Controllers/Utilities/SongCompression.cs +++ b/Icarus/Controllers/Utilities/SongCompression.cs @@ -43,10 +43,10 @@ public class SongCompression { var archivePath = RetrieveCompressesSongPath(song); Console.WriteLine($"Compressed song saved to: {archivePath}"); - + songData.Data = await System.IO.File.ReadAllBytesAsync(archivePath); } - catch(Exception ex) + catch (Exception ex) { var exMsg = ex.Message; Console.WriteLine($"An error ocurred: \n{exMsg}"); diff --git a/Icarus/Controllers/v1/AlbumController.cs b/Icarus/Controllers/v1/AlbumController.cs index 2956ffb..76834de 100644 --- a/Icarus/Controllers/v1/AlbumController.cs +++ b/Icarus/Controllers/v1/AlbumController.cs @@ -48,7 +48,7 @@ public class AlbumController : BaseController [HttpGet("{id}")] public IActionResult GetAlbum(int id) { - Album album = new Album{ Id = id }; + Album album = new Album { Id = id }; var albumContext = new AlbumContext(_connectionString!); diff --git a/Icarus/Controllers/v1/ArtistController.cs b/Icarus/Controllers/v1/ArtistController.cs index 7cc9be9..b336088 100644 --- a/Icarus/Controllers/v1/ArtistController.cs +++ b/Icarus/Controllers/v1/ArtistController.cs @@ -49,7 +49,7 @@ public class ArtistController : BaseController public IActionResult GetArtist(int id) { Artist artist = new Artist { Id = id }; - + var artistContext = new ArtistContext(_connectionString!); if (artistContext.DoesRecordExist(artist)) diff --git a/Icarus/Controllers/v1/BaseController.cs b/Icarus/Controllers/v1/BaseController.cs index 03a3221..5ed5b83 100644 --- a/Icarus/Controllers/v1/BaseController.cs +++ b/Icarus/Controllers/v1/BaseController.cs @@ -20,7 +20,7 @@ public class BaseController : ControllerBase const string otherTokenType = "Jwt"; var req = Request; - var auth = req.Headers.Authorization; + var auth = req.Headers.Authorization; var val = auth.ToString(); if ((val.Contains(tokenType) || val.Contains(otherTokenType)) && val.Split(" ").Count() > 1) @@ -31,7 +31,7 @@ public class BaseController : ControllerBase return token; - } + } #endregion } diff --git a/Icarus/Controllers/v1/CoverArtController.cs b/Icarus/Controllers/v1/CoverArtController.cs index 199a9e3..d28af2c 100644 --- a/Icarus/Controllers/v1/CoverArtController.cs +++ b/Icarus/Controllers/v1/CoverArtController.cs @@ -63,7 +63,7 @@ public class CoverArtController : BaseController var coverArtBytes = System.IO.File.ReadAllBytes( coverArt.ImagePath()); - return File(coverArtBytes, "application/x-msdownload", + return File(coverArtBytes, "application/x-msdownload", coverArt.SongTitle); } else @@ -78,14 +78,14 @@ public class CoverArtController : BaseController { var songContext = new SongContext(_connectionString!); var covMgr = new CoverArtManager(this._config!); - - var songMetaData = songContext.RetrieveRecord(new Song { Id = id}); + + var songMetaData = songContext.RetrieveRecord(new Song { Id = id }); var c = covMgr.GetCoverArt(songMetaData); var filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.JPG_EXTENSION, songMetaData.Title!, randomizeFilename); var data = await c.GetData(); - + return File(data, "application/x-msdownload", filename); } #endregion diff --git a/Icarus/Controllers/v1/GenreController.cs b/Icarus/Controllers/v1/GenreController.cs index 47b4e13..6cdec26 100644 --- a/Icarus/Controllers/v1/GenreController.cs +++ b/Icarus/Controllers/v1/GenreController.cs @@ -58,7 +58,7 @@ public class GenreController : BaseController if (genreStore.DoesRecordExist(genre)) { - genre = genreStore.RetrieveRecord(genre); + genre = genreStore.RetrieveRecord(genre); return Ok(genre); } diff --git a/Icarus/Controllers/v1/LoginController.cs b/Icarus/Controllers/v1/LoginController.cs index 4834471..11fac99 100644 --- a/Icarus/Controllers/v1/LoginController.cs +++ b/Icarus/Controllers/v1/LoginController.cs @@ -44,7 +44,7 @@ public class LoginController : ControllerBase var context = new UserContext(_connectionString!); _logger.LogInformation("Starting process of validating credentials"); - + var message = "Invalid credentials"; var password = user.Password; diff --git a/Icarus/Controllers/v1/SongCompressedDataControllers.cs b/Icarus/Controllers/v1/SongCompressedDataControllers.cs index 43a66b6..57dd630 100644 --- a/Icarus/Controllers/v1/SongCompressedDataControllers.cs +++ b/Icarus/Controllers/v1/SongCompressedDataControllers.cs @@ -42,11 +42,11 @@ public class SongCompressedDataController : BaseController var context = new SongContext(_connectionString!); SongCompression cmp = new SongCompression(_archiveDir!); - + Console.WriteLine($"Archive directory root: {_archiveDir}"); Console.WriteLine("Starting process of retrieving comrpessed song"); - var sng = context.RetrieveRecord(new Song{ Id = id }); + var sng = context.RetrieveRecord(new Song { Id = id }); SongData song = await cmp.RetrieveCompressedSong(sng); var filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.ZIP_EXTENSION, sng.Title!, randomizeFilename); diff --git a/Icarus/Controllers/v1/SongController.cs b/Icarus/Controllers/v1/SongController.cs index 622c877..6011260 100644 --- a/Icarus/Controllers/v1/SongController.cs +++ b/Icarus/Controllers/v1/SongController.cs @@ -41,7 +41,7 @@ public class SongController : BaseController { Console.WriteLine("Attemtping to retrieve songs"); _logger!.LogInformation("Attempting to retrieve songs"); - + var context = new SongContext(_connectionString!); var songs = context.Songs!.ToList(); @@ -60,8 +60,8 @@ public class SongController : BaseController public IActionResult GetSong(int id) { var context = new SongContext(_connectionString!); - - var song = context.RetrieveRecord(new Song{ Id = id }); + + var song = context.RetrieveRecord(new Song { Id = id }); Console.WriteLine("Here"); diff --git a/Icarus/Controllers/v1/SongDataController.cs b/Icarus/Controllers/v1/SongDataController.cs index dd9e271..1c1eb00 100644 --- a/Icarus/Controllers/v1/SongDataController.cs +++ b/Icarus/Controllers/v1/SongDataController.cs @@ -7,6 +7,8 @@ using Icarus.Database.Contexts; namespace Icarus.Controllers.V1; + + [Route("api/v1/song/data")] [ApiController] [Authorize] @@ -40,23 +42,23 @@ public class SongDataController : BaseController public IActionResult Download(int id, [FromQuery] bool? randomizeFilename) { var songContext = new SongContext(_connectionString!); - var songMetaData = songContext.RetrieveRecord(new Song { Id = id}); - + var songMetaData = songContext.RetrieveRecord(new Song { Id = id }); + var song = _songMgr!.RetrieveSong(songMetaData).Result; string filename; switch (songMetaData.AudioType) { case "wav": - filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.WAV_EXTENSION, + filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.WAV_EXTENSION, songMetaData.Title!, randomizeFilename); break; case "flac": - filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.FLAC_EXTENSION, + filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.FLAC_EXTENSION, songMetaData.Title!, randomizeFilename); break; default: - filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.DEFAULT_AUDIO_EXTENSION, + filename = DirectoryManager.GenerateDownloadFilename(10, Constants.FileExtensions.DEFAULT_AUDIO_EXTENSION, songMetaData.Title!, randomizeFilename); break; } @@ -151,8 +153,13 @@ public class SongDataController : BaseController switch (song.AudioType) { case "wav": - song = _songMgr.SaveSongToFileSystem(up.SongData, up.CoverArtData, song); - break; + var _ = _songMgr.DeleteSongFromFileSystem(tmpSong); + return BadRequest(new UploadSongWithDataResponse + { + Subject = "No longer supported", + Message = "No support for .wav files", + Songs = new List() + }); case "flac": song = _songMgr.SaveFlacSongToFileSystem(up.SongData, up.CoverArtData, song); break; @@ -176,7 +183,7 @@ public class SongDataController : BaseController { var songContext = new SongContext(_connectionString!); - var songMetaData = new Song{ Id = id }; + var songMetaData = new Song { Id = id }; Console.WriteLine($"Id {songMetaData.Id}"); songMetaData = songContext.RetrieveRecord(songMetaData); @@ -207,4 +214,16 @@ public class SongDataController : BaseController [FromForm(Name = "metadata")] public string? SongFile { get; set; } } + + public class UploadSongWithDataResponse + { + #region Properties + [Newtonsoft.Json.JsonProperty("message")] + public string Message { get; set; } + [Newtonsoft.Json.JsonProperty("subject")] + public string Subject { get; set; } + [Newtonsoft.Json.JsonProperty("data")] + public List Songs { get; set; } + #endregion + } } diff --git a/Icarus/Controllers/v1/SongStreamController.cs b/Icarus/Controllers/v1/SongStreamController.cs index 45c2da6..7a347bb 100644 --- a/Icarus/Controllers/v1/SongStreamController.cs +++ b/Icarus/Controllers/v1/SongStreamController.cs @@ -39,7 +39,7 @@ public class SongStreamController : BaseController var stream = new FileStream(song!.SongPath(), FileMode.Open, FileAccess.Read); stream.Position = 0; var filename = song.Filename; - + if (string.IsNullOrEmpty(song.Filename)) { filename = song.GenerateFilename(); @@ -48,7 +48,8 @@ public class SongStreamController : BaseController _logger!.LogInformation("Starting to stream song...>"); Console.WriteLine("Starting to streamsong..."); - return await Task.Run(() => { + return await Task.Run(() => + { return File(stream, "application/octet-stream", filename); }); } diff --git a/Icarus/Database/Contexts/AlbumContext.cs b/Icarus/Database/Contexts/AlbumContext.cs index f78c37d..5a312ee 100644 --- a/Icarus/Database/Contexts/AlbumContext.cs +++ b/Icarus/Database/Contexts/AlbumContext.cs @@ -12,7 +12,7 @@ public class AlbumContext : DbContext public AlbumContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { - } + } protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Icarus/Database/Contexts/ArtistContext.cs b/Icarus/Database/Contexts/ArtistContext.cs index 142a236..6f77d81 100644 --- a/Icarus/Database/Contexts/ArtistContext.cs +++ b/Icarus/Database/Contexts/ArtistContext.cs @@ -8,11 +8,11 @@ public class ArtistContext : DbContext { public DbSet Artists { get; set; } - public ArtistContext(DbContextOptions options) : base (options) { } + public ArtistContext(DbContextOptions options) : base(options) { } public ArtistContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { - } + } protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Icarus/Database/Contexts/CoverArtContext.cs b/Icarus/Database/Contexts/CoverArtContext.cs index 5ec75bd..5a5f6d1 100644 --- a/Icarus/Database/Contexts/CoverArtContext.cs +++ b/Icarus/Database/Contexts/CoverArtContext.cs @@ -14,8 +14,8 @@ public class CoverArtContext : DbContext public CoverArtContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { - } - + } + protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity() diff --git a/Icarus/Database/Contexts/GenreContext.cs b/Icarus/Database/Contexts/GenreContext.cs index 77db307..1091119 100644 --- a/Icarus/Database/Contexts/GenreContext.cs +++ b/Icarus/Database/Contexts/GenreContext.cs @@ -14,7 +14,7 @@ public class GenreContext : DbContext public GenreContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { - } + } protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/Icarus/Database/Contexts/SongContext.cs b/Icarus/Database/Contexts/SongContext.cs index bbab8c2..192b011 100644 --- a/Icarus/Database/Contexts/SongContext.cs +++ b/Icarus/Database/Contexts/SongContext.cs @@ -1,7 +1,7 @@ using Microsoft.EntityFrameworkCore; using Icarus.Models; - + namespace Icarus.Database.Contexts; public class SongContext : DbContext @@ -11,7 +11,7 @@ public class SongContext : DbContext public SongContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { - } + } public SongContext(DbContextOptions options) : base(options) { } diff --git a/Icarus/Database/Contexts/UserContext.cs b/Icarus/Database/Contexts/UserContext.cs index 008aa49..3bb0cec 100644 --- a/Icarus/Database/Contexts/UserContext.cs +++ b/Icarus/Database/Contexts/UserContext.cs @@ -1,7 +1,7 @@ using Microsoft.EntityFrameworkCore; using Icarus.Models; - + namespace Icarus.Database.Contexts; public class UserContext : DbContext @@ -15,7 +15,7 @@ public class UserContext : DbContext public UserContext(string connString) : base(new DbContextOptionsBuilder() .UseMySQL(connString).Options) { - } + } #endregion @@ -29,7 +29,7 @@ public class UserContext : DbContext .Property(u => u.DateCreated).HasDefaultValue(DateTime.Now); } - + public User RetrieveRecord(User user) { return Users.FirstOrDefault(usr => usr.Id == user.Id)!; diff --git a/Icarus/Icarus.csproj b/Icarus/Icarus.csproj index 82181da..02628be 100644 --- a/Icarus/Icarus.csproj +++ b/Icarus/Icarus.csproj @@ -34,9 +34,10 @@ - + + diff --git a/Icarus/Program.cs b/Icarus/Program.cs index 4f015a5..f6d1ad2 100644 --- a/Icarus/Program.cs +++ b/Icarus/Program.cs @@ -56,14 +56,16 @@ builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJw { options.RequireHttpsMetadata = false; options.SaveToken = true; + var audience = Configuration["JWT:Audience"]; + var issuer = Configuration["JWT:Issuer"]; options.TokenValidationParameters = new TokenValidationParameters() { ValidateIssuer = true, ValidateAudience = true, ValidateIssuerSigningKey = true, ValidateLifetime = true, - ValidAudience = Configuration["JWT:Audience"], - ValidIssuer = Configuration["JWT:Issuer"], + ValidAudience = audience, + ValidIssuer = issuer, IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Configuration["JWT:Secret"]!)) }; }); diff --git a/nlog.config b/Icarus/nlog.config similarity index 100% rename from nlog.config rename to Icarus/nlog.config diff --git a/Models/CoverArt.cs b/Models/CoverArt.cs index 4692f95..3343e17 100644 --- a/Models/CoverArt.cs +++ b/Models/CoverArt.cs @@ -23,7 +23,7 @@ public class CoverArt { var fullPath = this.Directory; - if (fullPath![fullPath.Length -1] != '/') + if (fullPath![fullPath.Length - 1] != '/') { fullPath += "/"; } diff --git a/Models/CreateFile.cs b/Models/CreateFile.cs new file mode 100644 index 0000000..6e16e3d --- /dev/null +++ b/Models/CreateFile.cs @@ -0,0 +1,11 @@ + + + +namespace Icarus.Models; + +public enum CreateFileResult +{ + Unknwon = 0, + AlreadyExists = 1, + FileCreatedAndExists = 2 +} \ No newline at end of file diff --git a/Models/Models.csproj b/Models/Models.csproj index e6928d4..96fc5db 100644 --- a/Models/Models.csproj +++ b/Models/Models.csproj @@ -12,4 +12,8 @@ + + + + diff --git a/Models/Song.cs b/Models/Song.cs index 8ee4377..c314adf 100644 --- a/Models/Song.cs +++ b/Models/Song.cs @@ -80,7 +80,7 @@ public class Song { var fullPath = SongDirectory; - if (fullPath![fullPath.Length -1] != '/') + if (fullPath![fullPath.Length - 1] != '/') { fullPath += "/"; } @@ -112,6 +112,27 @@ public class Song return includeExtension ? $"{filename}{extension}" : filename; } + public CreateSongResult Create(Microsoft.AspNetCore.Http.IFormFile file, string filePath, string prompt) + { + if (System.IO.File.Exists(filePath)) + { + return CreateSongResult.AlreadyExists; + } + + using (var filestream = new FileStream(filePath, FileMode.Create)) + { + Console.WriteLine(prompt); + file.CopyTo(filestream); + + if (System.IO.File.Exists(filePath)) + { + return CreateSongResult.Created; + } + } + + return CreateSongResult.NotCreated; + } + private string DetermineFileExtension(AudioFileExtensionsType flag) { switch (flag) @@ -135,11 +156,22 @@ public class Song return filename; } #endregion + } +#region Enums public enum AudioFileExtensionsType { Default = 0, WAV = 1, FLAC = 2 } + +public enum CreateSongResult +{ + NotCreated = 0, + AlreadyExists = 1, + Created = 2 +} +#endregion +