Contining work on #55

This commit is contained in:
kdeng00
2019-08-04 14:25:45 -04:00
parent 15948c4783
commit 610d4fb08d
6 changed files with 160 additions and 426 deletions
+19 -35
View File
@@ -1,6 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Icarus.Constants;
using Icarus.Controllers.Utilities;
@@ -14,7 +15,6 @@ namespace Icarus.Controllers.Managers
{
#region Fields
private string _rootCoverArtPath;
private byte[] _stockCoverArt = null;
#endregion
@@ -48,36 +48,27 @@ namespace Icarus.Controllers.Managers
}
public void DeleteCoverArt(CoverArt coverArt)
{
try
{
var stockCoverArtPath = _rootCoverArtPath + "CoverArt.png";
if (!string.Equals(stockCoverArtPath, coverArt.ImagePath,
StringComparison.CurrentCultureIgnoreCase))
{
_logger.Info("Song does not contain the stock cover art");
File.Delete(coverArt.ImagePath);
_logger.Info("Cover art deleted from the filesystem");
}
else
{
_logger.Info("Song contains the stock cover art");
_logger.Info("Will not delete from from the filesystem");
}
}
catch (Exception ex)
{
var msg = ex.Message;
_logger.Error(msg, "An error occurred");
}
var stockCoverArtPath = _rootCoverArtPath + "CoverArtPath.png";
DirectoryManager.delete_cover_art(coverArt.ImagePath, stockCoverArtPath);
}
public CoverArt SaveCoverArt(Song song)
{
try
{
var dirMgr = new DirectoryManager(_rootCoverArtPath);
dirMgr.CreateDirectory(song);
var imagePath = dirMgr.SongDirectory + song.Title + ".png";
// TODO: Change logic so it attempts to create the directory
// after it has been determined that the song does not have
// a cover art image
var strCount = _rootCoverArtPath.Length + song.Artist.Length +
song.AlbumTitle.Length + 2;
var imgPath = new StringBuilder(strCount);
DirectoryManager.create_directory(SongManager.ConvertSongToSng(song),
_rootCoverArtPath, imgPath);
var imagePath = imgPath.ToString().Substring(0, strCount);
imagePath += song.Title + ".png";
var coverArt = new CoverArt
{
SongTitle = song.Title,
@@ -97,7 +88,6 @@ namespace Icarus.Controllers.Managers
_logger.Info("Song has no cover art, applying stock cover art");
coverArt.ImagePath = _rootCoverArtPath + "CoverArt.png";
metaData.UpdateCoverArt(song, coverArt);
File.WriteAllBytes(coverArt.ImagePath, _stockCoverArt);
}
return coverArt;
@@ -113,15 +103,9 @@ namespace Icarus.Controllers.Managers
private void Initialize()
{
if (System.IO.File.Exists(DirectoryPaths.CoverArtPath))
_stockCoverArt = File.ReadAllBytes(DirectoryPaths.CoverArtPath);
if (!File.Exists(_rootCoverArtPath + "CoverArt.png"))
{
File.WriteAllBytes(_rootCoverArtPath + "CoverArt.png",
_stockCoverArt);
Console.WriteLine("Copied Stock Cover Art");
}
var stockCover = _rootCoverArtPath + "CoverArt.png";
DirectoryManager.copy_stock_cover_art(stockCover,
DirectoryPaths.CoverArtPath);
}
#region Testing
private void PrintCoverArtDetails(CoverArt cover)
+7 -1
View File
@@ -94,9 +94,15 @@ namespace Icarus.Controllers.Managers
_logger.Error(msg, "An error occurred");
}
}
#region C++ libs
[DllImport("libicarus.so")]
public static extern void create_directory(SongManager.Sng song, string root_path, StringBuilder created_dir);
//public static extern void create_directory(SongManager.Sng song, string root_path, string created_dir);
[DllImport("libicarus.so")]
public static extern void copy_stock_cover_art(string target_path, string source_path);
[DllImport("libicarus.so")]
public static extern void delete_cover_art(string cover_art_path, string stock_path);
#endregion
public void DeleteEmptyDirectories()
{
try
+3 -313
View File
@@ -10,13 +10,6 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Id3;
using Id3.Frames;
using MySql.Data;
using MySql.Data.MySqlClient;
using NLog;
using TagLib;
using Icarus.Controllers.Utilities;
using Icarus.Models;
using Icarus.Database.Contexts;
@@ -27,14 +20,8 @@ namespace Icarus.Controllers.Managers
public class SongManager : BaseManager
{
#region Fields
private MySqlConnection _conn;
private MySqlCommand _cmd;
private MySqlDataAdapter _dataDump;
private DataTable _results;
private List<Song> _songs;
private Song _song;
private IConfiguration _config;
private string _connectionString;
private string _tempDirectoryRoot;
private string _archiveDirectoryRoot;
private string _compressedSongFilename;
@@ -70,28 +57,20 @@ namespace Icarus.Controllers.Managers
#region Constructors
public SongManager()
{
Initialize();
InitializeConnection();
}
public SongManager(Song song)
{
Initialize();
InitializeConnection();
_song = song;
}
public SongManager(IConfiguration config)
{
_config = config;
Initialize();
InitializeConnection();
}
public SongManager(IConfiguration config, string tempDirectoryRoot)
{
_config = config;
_tempDirectoryRoot = tempDirectoryRoot;
Initialize();
InitializeConnection();
}
#endregion
@@ -193,91 +172,6 @@ namespace Icarus.Controllers.Managers
}
}
public void SaveSongDetails()
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "INSERT INTO Songs(Title, AlbumTitle, Artist, Year, Genre, Duration, " +
"Filename, SongPath) VALUES(@Title, @AlbumTitle, @Artist, @Year, @Genre, " +
"@Duration, @Filename, @SongPath)";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Title", _song.Title);
cmd.Parameters.AddWithValue("@AlbumTitle", _song.AlbumTitle);
cmd.Parameters.AddWithValue("@Artist", _song.Artist);
cmd.Parameters.AddWithValue("@Year", _song.Year);
cmd.Parameters.AddWithValue("@Genre", _song.Genre);
cmd.Parameters.AddWithValue("@Duration", _song.Duration);
cmd.Parameters.AddWithValue("@Filename", _song.Filename);
cmd.Parameters.AddWithValue("@SongPath", _song.SongPath);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An Error Occurred: {exMsg}");
}
}
public void SaveSongDetails(Song song)
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "INSERT INTO Songs(Title, AlbumTitle, Artist, Year, Genre, Duration, " +
", Filename, SongPath) VALUES(@Title, @AlbumTitle, @Artist, @Year, @Genre, " +
"@Duration, @Filename, @SongPath)";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Title", song.Title);
cmd.Parameters.AddWithValue("@AlbumTitle", song.AlbumTitle);
cmd.Parameters.AddWithValue("@Artist", song.Artist);
cmd.Parameters.AddWithValue("@Year", song.Year);
cmd.Parameters.AddWithValue("@Genre", song.Genre);
cmd.Parameters.AddWithValue("@Duration", song.Duration);
cmd.Parameters.AddWithValue("@Filename", song.Filename);
cmd.Parameters.AddWithValue("@SongPath", song.SongPath);
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An Error Occurred: {exMsg}");
}
}
public void SaveSong(SongData songData)
{
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "INSERT INTO SongData(Data) VALUES(@Data)";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Data", songData.Data);
cmd.ExecuteNonQuery();
}
}
}
catch(Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
}
public async Task SaveSongToFileSystem(IFormFile song)
{
try
@@ -363,15 +257,13 @@ namespace Icarus.Controllers.Managers
var song = await SaveSongTemp(songFile, fileTempPath);
song.SongPath = fileTempPath;
var sng = ConvertSongToSng(song);
var rootPath = _config.GetValue<string>("RootMusicPath");
var strCount = rootPath.Length + song.Artist.Length +
song.AlbumTitle.Length + 2;
var filePathSB = new StringBuilder(strCount);
DirectoryManager.create_directory(sng,
DirectoryManager.create_directory(ConvertSongToSng(song),
rootPath, filePathSB);
var filePath = filePathSB.ToString().Substring(0, strCount);
@@ -411,90 +303,6 @@ namespace Icarus.Controllers.Managers
}
}
public async Task<List<Song>> RetrieveAllSongDetails()
{
try
{
InitializeResults();
_songs = new List<Song>();
_conn.Open();
string query = "SELECT * FROM Songs";
_cmd = new MySqlCommand(query, _conn);
_cmd.ExecuteNonQuery();
_dataDump = new MySqlDataAdapter(_cmd);
_dataDump.Fill(_results);
_dataDump.Dispose();
await PopulateSongDetails();
_conn.Close();
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error ocurred: {exMsg}");
}
return _songs;
}
public Song RetrieveSongDetails(int id)
{
DataTable results = new DataTable();
try
{
using (MySqlConnection conn = new MySqlConnection(_connectionString))
{
conn.Open();
string query = "SELECT * FROM Songs WHERE Id=@Id";
using (MySqlCommand cmd = new MySqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("@Id", id);
cmd.ExecuteNonQuery();
using (MySqlDataAdapter dataDump = new MySqlDataAdapter(cmd))
{
dataDump.Fill(results);
}
}
}
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred");
}
DataRow row = results.Rows[0];
return new Song
{
Id = Int32.Parse(row["Id"].ToString()),
Filename = row["Filename"].ToString(),
SongPath = row["SongPath"].ToString()
};
}
public async Task<SongData> RetrieveSong(int id)
{
SongData song = new SongData();
try
{
_song = RetrieveSongDetails(id);
song = await RetrieveSongFromFileSystem(_song);
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error occurred: {exMsg}");
}
return song;
}
public async Task<SongData> RetrieveSong(Song songMetaData)
{
SongData song = new SongData();
@@ -512,7 +320,7 @@ namespace Icarus.Controllers.Managers
return song;
}
private Sng ConvertSongToSng(Song song)
public static Sng ConvertSongToSng(Song song)
{
return new Sng
{
@@ -525,65 +333,10 @@ namespace Icarus.Controllers.Managers
};
}
private Song RetrieveMetaData(string filePath)
{
Song newSong = new Song
{
Title = "Untitled",
Artist = "Untitled",
AlbumTitle = "Untitled",
Year = 0,
Genre = "Untitled",
Duration = 0,
SongPath = ""
};
string title, artist, album, genre;
int year, duration;
Console.WriteLine("Stripping song metadata");
try
{
TagLib.File tfile = TagLib.File.Create(filePath);
using (var mp3 = new Mp3(filePath))
{
Id3Tag tag = mp3.GetTag(Id3TagFamily.Version2X);
title = tag.Title;
Console.WriteLine("Title: {0}", title);
newSong.Title = title;
artist = tag.Artists;
Console.WriteLine("Artist: {0}", artist);
newSong.Artist = artist;
album = tag.Album;
Console.WriteLine("Album: {0}", album);
newSong.AlbumTitle = album;
genre = "Not Implemented";
Console.WriteLine("Genre: {0}", genre);
newSong.Genre = genre;
year = (int)tag.Year;
Console.WriteLine("Year: {0}", year);
newSong.Year = year;
duration = (int)tfile.Properties.Duration.TotalSeconds;
Console.WriteLine("Duration: {0}", duration);
newSong.Duration = duration;
}
_song = newSong;
}
catch (Exception ex)
{
var msg = ex.Message;
Console.WriteLine($"An error occurred when stripping metadata\n{msg}");
_song = newSong;
}
return newSong;
}
private async Task<SongData> RetrieveSongFromFileSystem(Song details)
{
byte[] uncompressedSong = System.IO.File.ReadAllBytes(details.SongPath);
byte[] uncompressedSong = await System.IO.File.ReadAllBytesAsync(details.SongPath);
return new SongData
{
@@ -652,27 +405,6 @@ namespace Icarus.Controllers.Managers
mgr.DeleteEmptyDirectories(oldSong);
}
private void Initialize()
{
try
{
_connectionString = _config.GetConnectionString("IcarusDev");
}
catch (Exception ex)
{
Console.WriteLine($"Error Occurred: {ex.Message}");
}
}
private void InitializeConnection()
{
_conn = new MySqlConnection(_connectionString);
}
private void InitializeResults()
{
_results = new DataTable();
}
private void SaveSongToDatabase(Song song, SongRepository songStore, AlbumRepository albumStore,
ArtistRepository artistStore)
{
@@ -1199,48 +931,6 @@ namespace Icarus.Controllers.Managers
yearStore.DeleteYear(year);
}
private async Task PopulateSongDetails()
{
foreach (DataRow row in _results.Rows)
{
Song song = new Song();
foreach (DataColumn col in _results.Columns)
{
string colStr = col.ToString().ToUpper();
switch (colStr)
{
case "ID":
song.Id = Int32.Parse(row[col].ToString());
break;
case "TITLE":
song.Title = row[col].ToString();
break;
case "ALBUM":
song.AlbumTitle = row[col].ToString();
break;
case "ARTIST":
song.Artist = row[col].ToString();
break;
case "YEAR":
song.Year = Int32.Parse(row[col].ToString());
break;
case "GENRE":
song.Genre = row[col].ToString();
break;
case "DURATION":
song.Duration = Int32.Parse(row[col].ToString());
break;
case "FILENAME":
song.Filename = row[col].ToString();
break;
case "SONGPATH":
song.SongPath = row[col].ToString();
break;
}
}
_songs.Add(song);
}
}
#endregion
+66 -66
View File
@@ -13,18 +13,18 @@ namespace Icarus.Controllers.Utilities
public class SongCompression
{
#region Fields
string _compressedSongFilename;
string _tempDirectory;
string _compressedSongFilename;
string _tempDirectory;
byte[] _uncompressedSong;
#endregion
#region Propterties
public string CompressedSongFilename
{
get => _compressedSongFilename;
set => _compressedSongFilename = value;
}
public string CompressedSongFilename
{
get => _compressedSongFilename;
set => _compressedSongFilename = value;
}
#endregion
@@ -32,10 +32,10 @@ namespace Icarus.Controllers.Utilities
public SongCompression()
{
}
public SongCompression(string tempDirectory)
{
_tempDirectory = tempDirectory;
}
public SongCompression(string tempDirectory)
{
_tempDirectory = tempDirectory;
}
public SongCompression(byte[] uncompressedSong)
{
_uncompressedSong = uncompressedSong;
@@ -44,60 +44,60 @@ namespace Icarus.Controllers.Utilities
#region Methods
public async Task<SongData> RetrieveCompressedSong(Song song)
{
SongData songData = new SongData();
try
{
var archivePath = RetrieveCompressesSongPath(song);
Console.WriteLine($"Compressed song saved to: {archivePath}");
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}");
}
songData.Data = await System.IO.File.ReadAllBytesAsync(archivePath);
}
catch(Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine($"An error ocurred: \n{exMsg}");
}
return songData;
}
return songData;
}
public string RetrieveCompressesSongPath(Song songDetails)
{
string tmpZipFilePath = _tempDirectory + songDetails.Filename;
public string RetrieveCompressesSongPath(Song songDetails)
{
string tmpZipFilePath = _tempDirectory + songDetails.Filename;
try
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile(songDetails.SongPath);
zip.Save(tmpZipFilePath);
}
Console.WriteLine("Successfully compressed");
}
catch (Exception ex)
{
var exMsg = ex.Message;
Console.WriteLine("An error ocurred");
Console.WriteLine(exMsg);
}
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);
}
if (songDetails.Filename.Contains(".mp3"))
{
_compressedSongFilename = StripMP3Extension(songDetails.Filename);
}
return tmpZipFilePath;
}
return tmpZipFilePath;
}
// Method not being used
// Method not being used
public byte[] CompressedSong(byte[] uncompressedSong)
{
byte[] compressedSong = null;
try
{
Console.WriteLine("Song has been successfully compressed");
Console.WriteLine("Song has been successfully compressed");
}
catch (Exception ex)
{
@@ -110,20 +110,20 @@ namespace Icarus.Controllers.Utilities
}
string StripMP3Extension(string filename)
{
Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1;
var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4);
stripped += ".zip";
Console.WriteLine($"After {stripped}");
string StripMP3Extension(string filename)
{
Console.WriteLine($"Before: {filename}");
int filenameLength = filename.Length;
Console.WriteLine($"Filename length {filenameLength}");
var endIndex = filenameLength - 1;
var startIndex = endIndex - 3;
Console.WriteLine($"Starting index {startIndex} and ending index {endIndex}");
var stripped = filename.Remove(startIndex, 4);
stripped += ".zip";
Console.WriteLine($"After {stripped}");
return stripped;
}
return stripped;
}
#endregion
}
}
+2 -2
View File
@@ -32,7 +32,7 @@ namespace Icarus.Controllers.V1
#region HTTP Routes
public async Task<IActionResult> Get()
public IActionResult Get()
{
var coverArtRepository = HttpContext
.RequestServices
@@ -70,7 +70,7 @@ namespace Icarus.Controllers.V1
if (coverArt != null)
{
_logger.LogInformation("Found cover art record");
var coverArtBytes = System.IO.File.ReadAllBytes(
var coverArtBytes = await System.IO.File.ReadAllBytesAsync(
coverArt.ImagePath);
return File(coverArtBytes, "application/x-msdownload",
+62 -8
View File
@@ -1,5 +1,6 @@
#include <iostream>
#include <filesystem>
#include <fstream>
#include <string>
#include "directory_manager.h"
@@ -36,24 +37,77 @@ std::string create_directory_process(Song song, const char *root_path)
return alb_path.string() + "/";
}
std::string read_cover_art(const char *source)
{
auto source_path = fs::path(source);
std::fstream cov(source, std::ios::in | std::ios::binary);
if (!cov.is_open()) {
std::cout<<"file is not open"<<std::endl;
}
cov.seekg(0, cov.end);
int cov_len = cov.tellg();
cov.seekg(0, cov.beg);
char buff[cov_len];
cov.read(buff, cov_len);
cov.close();
return std::string{buff};
}
void copy_stock_to_root(const char *target, const std::string buff)
{
std::cout<<"starting process"<<std::endl;
auto target_path = fs::path(target);
if (fs::exists(target_path)) {
std::cout<<target_path.string()<<" exists"<<std::endl;
return;
}
std::cout<<target_path.string()<<" does not exist, copying over"<<std::endl;
std::fstream cov(target, std::ios::out | std::ios::binary);
cov.write(buff.c_str(), buff.size());
cov.close();
std::cout<<"copy finished"<<std::endl;
}
void delete_cover_art_file(const std::string cov_path)
{
auto cov = fs::path(cov_path);
fs::remove(cov);
}
extern "C"
{
void create_directory(Song, const char*, char*);
void copy_stock_cover_art(const char*, const char*);
void print_song_details(const Song);
void create_directory(Song song, const char *root_path, char *dir)
{
std::cout<<"c++ creating directory"<<std::endl;
std::string tmp = create_directory_process(song, root_path);
std::cout<<"tmp size "<<tmp.size()<<std::endl;
//dir = (char*)tmp.c_str();
std::cout<<"done"<<std::endl;
const auto tmp = create_directory_process(song, root_path);
size_t tmp_sz = tmp.size();
tmp.copy(dir, tmp_sz, 0);
//std::copy(tmp.begin(), tmp.end()-1, dir);
std::cout<<"still c++ "<<dir<<"\n\n";
}
void copy_stock_cover_art(const char *target, const char *source)
{
const auto buff = read_cover_art(source);
copy_stock_to_root(target, buff);
}
void delete_cover_art(const char *cover_path, const char *stock_path)
{
std::cout<<"starting process to delete cover art"<<std::endl;
const auto cov_path = std::string{cover_path};
const auto s_path = std::string{stock_path};
if (cov_path.compare(s_path) != 0) {
std::cout<<"cover art is not the stock path"<<std::endl;
delete_cover_art_file(cov_path);
} else {
std::cout<<"cover art is the stock path and will not be deleted"<<std::endl;
}
}
void print_song_details(const Song song)
{