Code cleanup

This commit is contained in:
kdeng00
2019-11-17 13:33:58 -05:00
parent ca1fcb801d
commit 69f5a37eb3
74 changed files with 4397 additions and 4717 deletions
+4 -5
View File
@@ -7,20 +7,19 @@
#include "oatpp/web/protocol/http/outgoing/ChunkedBody.hpp" #include "oatpp/web/protocol/http/outgoing/ChunkedBody.hpp"
namespace callback { namespace callback {
class StreamCallback : public oatpp::data::stream::ReadCallback class StreamCallback : public oatpp::data::stream::ReadCallback {
{ public:
public:
StreamCallback(); StreamCallback();
StreamCallback(const std::string&); StreamCallback(const std::string&);
oatpp::data::v_io_size read(void*, oatpp::data::v_io_size); oatpp::data::v_io_size read(void*, oatpp::data::v_io_size);
private: private:
std::string m_songPath; std::string m_songPath;
long m_bytesRead; long m_bytesRead;
long m_counter; long m_counter;
long m_fileSize; long m_fileSize;
}; };
} }
#endif #endif
+13 -10
View File
@@ -9,29 +9,32 @@
#include "oatpp/web/server/HttpConnectionHandler.hpp" #include "oatpp/web/server/HttpConnectionHandler.hpp"
namespace component { namespace component {
class AppComponent {
class AppComponent public:
{ OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>,
public: serverConnectionProvider)([&] {
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::ServerConnectionProvider>, serverConnectionProvider)([] { return oatpp::network::server::SimpleTCPConnectionProvider::
return oatpp::network::server::SimpleTCPConnectionProvider::createShared(5002); createShared(appPort());
}()); }());
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] { OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, httpRouter)([] {
return oatpp::web::server::HttpRouter::createShared(); return oatpp::web::server::HttpRouter::createShared();
}()); }());
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::server::ConnectionHandler>, serverConnectionHandler)([] { OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::network::server::ConnectionHandler>,
serverConnectionHandler)([] {
OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router);
return oatpp::web::server::HttpConnectionHandler::createShared(router); return oatpp::web::server::HttpConnectionHandler::createShared(router);
}()); }());
OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>, apiObjectMapper)([] { OATPP_CREATE_COMPONENT(std::shared_ptr<oatpp::data::mapping::ObjectMapper>,
apiObjectMapper)([] {
return oatpp::parser::json::mapping::ObjectMapper::createShared(); return oatpp::parser::json::mapping::ObjectMapper::createShared();
}()); }());
private: private:
}; constexpr int appPort() noexcept { return 5002; }
};
} }
#endif #endif
+18 -21
View File
@@ -29,33 +29,29 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace controller { namespace controller {
class AlbumController : public oatpp::web::server::api::ApiController class AlbumController : public oatpp::web::server::api::ApiController {
{ public:
public: AlbumController(const model::BinaryPath& bConf,
AlbumController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p) : oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
{ }
AlbumController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all album records in json format // endpoint for retrieving all album records in json format
ENDPOINT("GET", "/api/v1/album", albumRecords, ENDPOINT("GET", "/api/v1/album", albumRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveAlbum), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveAlbum), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving album" << std::endl; std::cout << "starting process of retrieving album\n";
database::AlbumRepository albRepo(m_bConf); database::AlbumRepository albRepo(m_bConf);
auto albsDb = albRepo.retrieveRecords(); auto albsDb = albRepo.retrieveRecords();
auto albums = oatpp::data::mapping::type::List<dto::AlbumDto::ObjectWrapper>::createShared(); auto albums = oatpp::data::mapping::type::
List<dto::AlbumDto::ObjectWrapper>::createShared();
for (auto& albDb : albsDb) { for (auto& albDb : albsDb) {
auto alb = dto::conversion::DtoConversions::toAlbumDto(albDb); auto alb = dto::conversion::DtoConversions::toAlbumDto(albDb);
@@ -73,14 +69,16 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveAlbum), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveAlbum), Status::CODE_403, "Not allowed");
database::AlbumRepository albRepo(m_bConf); database::AlbumRepository albRepo(m_bConf);
model::Album albDb(id); model::Album albDb(id);
OATPP_ASSERT_HTTP(albRepo.doesAlbumExists(albDb, type::AlbumFilter::id) , Status::CODE_403, "album does not exist"); OATPP_ASSERT_HTTP(albRepo.doesAlbumExists(albDb,
type::AlbumFilter::id) , Status::CODE_403, "album does not exist");
std::cout << "album exists" << std::endl; std::cout << "album exists\n";
albDb = albRepo.retrieveRecord(albDb, type::AlbumFilter::id); albDb = albRepo.retrieveRecord(albDb, type::AlbumFilter::id);
auto album = dto::conversion::DtoConversions::toAlbumDto(albDb); auto album = dto::conversion::DtoConversions::toAlbumDto(albDb);
@@ -89,9 +87,8 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::string m_exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
+18 -21
View File
@@ -28,33 +28,29 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace controller { namespace controller {
class ArtistController : public oatpp::web::server::api::ApiController class ArtistController : public oatpp::web::server::api::ApiController {
{ public:
public: ArtistController(const model::BinaryPath& bConf,
ArtistController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p) : oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
{ }
ArtistController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all artist records in json format // endpoint for retrieving all artist records in json format
ENDPOINT("GET", "/api/v1/artist", artistRecords, ENDPOINT("GET", "/api/v1/artist", artistRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveArtist), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveArtist), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving artist" << std::endl; std::cout << "starting process of retrieving artist\n";
database::ArtistRepository artRepo(m_bConf); database::ArtistRepository artRepo(m_bConf);
auto artsDb = artRepo.retrieveRecords(); auto artsDb = artRepo.retrieveRecords();
auto artists = oatpp::data::mapping::type::List<dto::ArtistDto::ObjectWrapper>::createShared(); auto artists = oatpp::data::mapping::type::
List<dto::ArtistDto::ObjectWrapper>::createShared();
for (auto& artDb : artsDb) { for (auto& artDb : artsDb) {
auto art = dto::ArtistDto::createShared(); auto art = dto::ArtistDto::createShared();
@@ -74,14 +70,16 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveArtist), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveArtist), Status::CODE_403, "Not allowed");
database::ArtistRepository artRepo(m_bConf); database::ArtistRepository artRepo(m_bConf);
model::Artist artDb(id); model::Artist artDb(id);
OATPP_ASSERT_HTTP(artRepo.doesArtistExist(artDb, type::ArtistFilter::id) , Status::CODE_403, "artist does not exist"); OATPP_ASSERT_HTTP(artRepo.doesArtistExist(artDb,
type::ArtistFilter::id) , Status::CODE_403, "artist does not exist");
std::cout << "artist exist" << std::endl; std::cout << "artist exist\n";
artDb = artRepo.retrieveRecord(artDb, type::ArtistFilter::id); artDb = artRepo.retrieveRecord(artDb, type::ArtistFilter::id);
auto artist = dto::ArtistDto::createShared(); auto artist = dto::ArtistDto::createShared();
@@ -92,9 +90,8 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::string m_exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
+20 -22
View File
@@ -27,33 +27,29 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace controller { namespace controller {
class CoverArtController : public oatpp::web::server::api::ApiController class CoverArtController : public oatpp::web::server::api::ApiController {
{ public:
public: CoverArtController(const model::BinaryPath& bConf,
CoverArtController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p) : oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
{ }
CoverArtController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all cover art records in json format // endpoint for retrieving all cover art records in json format
ENDPOINT("GET", "/api/v1/coverart", coverArtRecords, ENDPOINT("GET", "/api/v1/coverart", coverArtRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving cover art" << std::endl; std::cout << "starting process of retrieving cover art\n";
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
auto covsDb = covRepo.retrieveRecords(); auto covsDb = covRepo.retrieveRecords();
auto coverArts = oatpp::data::mapping::type::List<dto::CoverArtDto::ObjectWrapper>::createShared(); auto coverArts = oatpp::data::mapping::type::
List<dto::CoverArtDto::ObjectWrapper>::createShared();
for (auto& covDb : covsDb) { for (auto& covDb : covsDb) {
auto cov = dto::CoverArtDto::createShared(); auto cov = dto::CoverArtDto::createShared();
@@ -73,15 +69,17 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed");
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
model::Cover covDb; model::Cover covDb;
covDb.id = id; covDb.id = id;
OATPP_ASSERT_HTTP(covRepo.doesCoverArtExist(covDb, type::CoverFilter::id) , Status::CODE_403, "song does not exist"); OATPP_ASSERT_HTTP(covRepo.doesCoverArtExist(covDb,
type::CoverFilter::id) , Status::CODE_403, "song does not exist");
std::cout << "cover art exists" << std::endl; std::cout << "cover art exists\n";
covDb = covRepo.retrieveRecord(covDb, type::CoverFilter::id); covDb = covRepo.retrieveRecord(covDb, type::CoverFilter::id);
auto coverArt = dto::CoverArtDto::createShared(); auto coverArt = dto::CoverArtDto::createShared();
@@ -97,7 +95,8 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::downloadCoverArt), Status::CODE_403, "Not allowed");
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
model::Cover covDb; model::Cover covDb;
@@ -113,9 +112,8 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::string m_exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
+18 -21
View File
@@ -28,33 +28,29 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace controller { namespace controller {
class GenreController : public oatpp::web::server::api::ApiController class GenreController : public oatpp::web::server::api::ApiController {
{ public:
public: GenreController(const model::BinaryPath& bConf,
GenreController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p) : oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
{ }
GenreController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all genre records in json format // endpoint for retrieving all genre records in json format
ENDPOINT("GET", "/api/v1/genre", genreRecords, ENDPOINT("GET", "/api/v1/genre", genreRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveGenre), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveGenre), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving genre" << std::endl; std::cout << "starting process of retrieving genre\n";
database::GenreRepository gnrRepo(m_bConf); database::GenreRepository gnrRepo(m_bConf);
auto gnrsDb = gnrRepo.retrieveRecords(); auto gnrsDb = gnrRepo.retrieveRecords();
auto genres = oatpp::data::mapping::type::List<dto::GenreDto::ObjectWrapper>::createShared(); auto genres = oatpp::data::mapping::type::
List<dto::GenreDto::ObjectWrapper>::createShared();
for (auto& gnrDb : gnrsDb) { for (auto& gnrDb : gnrsDb) {
auto gnr = dto::GenreDto::createShared(); auto gnr = dto::GenreDto::createShared();
@@ -74,14 +70,16 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveGenre), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveGenre), Status::CODE_403, "Not allowed");
database::GenreRepository gnrRepo(m_bConf); database::GenreRepository gnrRepo(m_bConf);
model::Genre gnrDb(id); model::Genre gnrDb(id);
OATPP_ASSERT_HTTP(gnrRepo.doesGenreExist(gnrDb, type::GenreFilter::id) , Status::CODE_403, "genre does not exist"); OATPP_ASSERT_HTTP(gnrRepo.doesGenreExist(gnrDb,
type::GenreFilter::id) , Status::CODE_403, "genre does not exist");
std::cout << "genre exist" << std::endl; std::cout << "genre exist\n";
gnrDb = gnrRepo.retrieveRecord(gnrDb, type::GenreFilter::id); gnrDb = gnrRepo.retrieveRecord(gnrDb, type::GenreFilter::id);
auto genre = dto::GenreDto::createShared(); auto genre = dto::GenreDto::createShared();
@@ -92,9 +90,8 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::string m_exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
+9 -13
View File
@@ -16,14 +16,11 @@
#include "model/Models.h" #include "model/Models.h"
namespace controller { namespace controller {
class LoginController : public oatpp::web::server::api::ApiController { class LoginController : public oatpp::web::server::api::ApiController {
public: public:
LoginController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) LoginController(const model::BinaryPath& bConf,
: oatpp::web::server::api::ApiController(objectMapper), exe_path(p) OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
{ } :oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
LoginController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
:oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
@@ -37,11 +34,11 @@ public:
if (!usrMgr.doesUserExist(user) || !usrMgr.validatePassword(user)) { if (!usrMgr.doesUserExist(user) || !usrMgr.validatePassword(user)) {
auto logRes = dto::LoginResultDto::createShared(); auto logRes = dto::LoginResultDto::createShared();
logRes->message = "invalid credentials"; logRes->message = "invalid credentials";
std::cout << "user does not exist" << std::endl; std::cout << "user does not exist\n";
return createDtoResponse(Status::CODE_401, logRes); return createDtoResponse(Status::CODE_401, logRes);
} }
std::cout << "user exists" << std::endl; std::cout << "user exists\n";
manager::TokenManager tok; manager::TokenManager tok;
auto token = tok.retrieveToken(m_bConf); auto token = tok.retrieveToken(m_bConf);
@@ -53,9 +50,8 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::string exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
@@ -26,6 +26,9 @@ namespace controller {
BODY_DTO(dto::UserDto::ObjectWrapper, usr)) { BODY_DTO(dto::UserDto::ObjectWrapper, usr)) {
manager::UserManager usrMgr(m_bConf); manager::UserManager usrMgr(m_bConf);
auto user = dto::conversion::DtoConversions::toUser(usr); auto user = dto::conversion::DtoConversions::toUser(usr);
if (usrMgr.doesUserExist(user)) {
return createResponse(Status::CODE_401, "user already exists");
}
auto res = usrMgr.registerUser(user); auto res = usrMgr.registerUser(user);
auto registerResult = dto::conversion::DtoConversions::toRegisterResultDto(res); auto registerResult = dto::conversion::DtoConversions::toRegisterResultDto(res);
+27 -27
View File
@@ -32,33 +32,31 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace controller { namespace controller {
class SongController : public oatpp::web::server::api::ApiController { class SongController : public oatpp::web::server::api::ApiController {
public: public:
SongController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p)
{ }
SongController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) SongController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) : oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for uploading a song // endpoint for uploading a song
ENDPOINT("POST", "/api/v1/song/data", songUpload, ENDPOINT("POST", "/api/v1/song/data", songUpload,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::upload), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::upload), Status::CODE_403, "Not allowed");
auto mp = std::make_shared<oatpp::web::mime::multipart::Multipart>(request->getHeaders()); auto mp =
std::make_shared<oatpp::web::mime::multipart::Multipart>
(request->getHeaders());
oatpp::web::mime::multipart::Reader mp_reader(mp.get()); oatpp::web::mime::multipart::Reader mp_reader(mp.get());
mp_reader.setPartReader("file", oatpp::web::mime::multipart::createInMemoryPartReader(m_dataSize)); mp_reader.setPartReader("file",
oatpp::web::mime::multipart::createInMemoryPartReader(m_dataSize));
request->transferBody(&mp_reader); request->transferBody(&mp_reader);
@@ -92,20 +90,19 @@ public:
// endpoint for retrieving all song records in json format // endpoint for retrieving all song records in json format
ENDPOINT("GET", "/api/v1/song", songRecords, ENDPOINT("GET", "/api/v1/song", songRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveSong), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveSong), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving songs" << std::endl; std::cout << "starting process of retrieving songs\n";
database::SongRepository songRepo(m_bConf); database::SongRepository songRepo(m_bConf);
auto songsDb = songRepo.retrieveRecords(); auto songsDb = songRepo.retrieveRecords();
auto songs = oatpp::data::mapping::type::List<dto::SongDto::ObjectWrapper>::createShared(); auto songs = oatpp::data::mapping::type::List<dto::SongDto::ObjectWrapper>::createShared();
std::cout << "creating object to send" << std::endl; std::cout << "creating object to send\n";
for (auto& songDb : songsDb) { for (auto& songDb : songsDb) {
auto song = dto::conversion::DtoConversions::toSongDto(songDb); auto song = dto::conversion::DtoConversions::toSongDto(songDb);
@@ -131,7 +128,7 @@ public:
return songDoesNotExist(); return songDoesNotExist();
} }
std::cout << "song exists" << std::endl; std::cout << "song exists\n";
songDb = songRepo.retrieveRecord(songDb, type::SongFilter::id); songDb = songRepo.retrieveRecord(songDb, type::SongFilter::id);
auto song = dto::conversion::DtoConversions::toSongDto(songDb); auto song = dto::conversion::DtoConversions::toSongDto(songDb);
@@ -145,7 +142,8 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::download), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::download), Status::CODE_403, "Not allowed");
database::SongRepository songRepo(m_bConf); database::SongRepository songRepo(m_bConf);
model::Song songDb(id); model::Song songDb(id);
@@ -171,7 +169,8 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::updateSong), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::updateSong), Status::CODE_403, "Not allowed");
auto updatedSong = dto::conversion::DtoConversions::toSong(songDto); auto updatedSong = dto::conversion::DtoConversions::toSong(songDto);
manager::SongManager songMgr(m_bConf); manager::SongManager songMgr(m_bConf);
@@ -190,7 +189,8 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::deleteSong), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::deleteSong), Status::CODE_403, "Not allowed");
model::Song song(id); model::Song song(id);
@@ -210,7 +210,8 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::stream), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::stream), Status::CODE_403, "Not allowed");
database::SongRepository songRepo(m_bConf); database::SongRepository songRepo(m_bConf);
model::Song songDb(id); model::Song songDb(id);
@@ -223,7 +224,8 @@ public:
oatpp::data::v_io_size dSize = 1024; oatpp::data::v_io_size dSize = 1024;
auto db = std::make_shared<oatpp::web::protocol::http::outgoing::ChunkedBody>( auto db = std::make_shared<oatpp::web::protocol::http::outgoing::ChunkedBody>(
std::make_shared<callback::StreamCallback>(songDb.songPath), nullptr, dSize); std::make_shared<callback::StreamCallback>(songDb.songPath),
nullptr, dSize);
auto response = OutgoingResponse::createShared(Status::CODE_200, db); auto response = OutgoingResponse::createShared(Status::CODE_200, db);
response->putHeader(Header::CONNECTION, Header::Value::CONNECTION_KEEP_ALIVE); response->putHeader(Header::CONNECTION, Header::Value::CONNECTION_KEEP_ALIVE);
@@ -233,18 +235,16 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::shared_ptr<oatpp::web::protocol::http::outgoing::Response> std::shared_ptr<oatpp::web::protocol::http::outgoing::Response>
songDoesNotExist() { songDoesNotExist() {
return createResponse(Status::CODE_404, "Song not found"); return createResponse(Status::CODE_404, "Song not found");
} }
std::string m_exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
const long m_dataSize = std::numeric_limits<long long int>::max(); const long m_dataSize = std::numeric_limits<long long int>::max();
}; };
} }
#endif #endif
+19 -21
View File
@@ -27,33 +27,29 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace controller { namespace controller {
class YearController : public oatpp::web::server::api::ApiController class YearController : public oatpp::web::server::api::ApiController {
{ public:
public: YearController(const model::BinaryPath& bConf,
YearController(std::string p, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper)) OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_exe_path(p) : oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf) { }
{ }
YearController(const model::BinaryPath& bConf, OATPP_COMPONENT(std::shared_ptr<ObjectMapper>, objectMapper))
: oatpp::web::server::api::ApiController(objectMapper), m_bConf(bConf)
{ }
#include OATPP_CODEGEN_BEGIN(ApiController) #include OATPP_CODEGEN_BEGIN(ApiController)
// endpoint for retrieving all year records in json format // endpoint for retrieving all year records in json format
ENDPOINT("GET", "/api/v1/year", yearRecords, ENDPOINT("GET", "/api/v1/year", yearRecords,
REQUEST(std::shared_ptr<IncomingRequest>, request)) REQUEST(std::shared_ptr<IncomingRequest>, request)) {
{
auto authHeader = request->getHeader("Authorization"); auto authHeader = request->getHeader("Authorization");
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveYear), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveYear), Status::CODE_403, "Not allowed");
std::cout << "starting process of retrieving year" << std::endl; std::cout << "starting process of retrieving year\n";
database::YearRepository yrRepo(m_bConf); database::YearRepository yrRepo(m_bConf);
auto yrsDb = yrRepo.retrieveRecords(); auto yrsDb = yrRepo.retrieveRecords();
auto yearRecs = oatpp::data::mapping::type::List<dto::YearDto::ObjectWrapper>::createShared(); auto yearRecs = oatpp::data::mapping::type::
List<dto::YearDto::ObjectWrapper>::createShared();
for (auto& yrDb : yrsDb) { for (auto& yrDb : yrsDb) {
auto yr = dto::YearDto::createShared(); auto yr = dto::YearDto::createShared();
@@ -73,14 +69,16 @@ public:
OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope"); OATPP_ASSERT_HTTP(authHeader, Status::CODE_403, "Nope");
auto auth = authHeader->std_str(); auto auth = authHeader->std_str();
manager::TokenManager tok; manager::TokenManager tok;
OATPP_ASSERT_HTTP(tok.isTokenValid(auth, type::Scope::retrieveYear), Status::CODE_403, "Not allowed"); OATPP_ASSERT_HTTP(tok.isTokenValid(auth,
type::Scope::retrieveYear), Status::CODE_403, "Not allowed");
database::YearRepository yrRepo(m_bConf); database::YearRepository yrRepo(m_bConf);
model::Year yrDb(id); model::Year yrDb(id);
OATPP_ASSERT_HTTP(yrRepo.doesYearExist(yrDb, type::YearFilter::id) , Status::CODE_403, "year does not exist"); OATPP_ASSERT_HTTP(yrRepo.doesYearExist(yrDb,
type::YearFilter::id) , Status::CODE_403, "year does not exist");
std::cout << "year exist" << std::endl; std::cout << "year exist\n";
yrDb = yrRepo.retrieveRecord(yrDb, type::YearFilter::id); yrDb = yrRepo.retrieveRecord(yrDb, type::YearFilter::id);
auto year = dto::YearDto::createShared(); auto year = dto::YearDto::createShared();
@@ -91,9 +89,9 @@ public:
} }
#include OATPP_CODEGEN_END(ApiController) #include OATPP_CODEGEN_END(ApiController)
private: private:
std::string m_exe_path;
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
+2 -4
View File
@@ -9,10 +9,8 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/AlbumFilter.h" #include "type/AlbumFilter.h"
namespace database namespace database {
{ class AlbumRepository : public BaseRepository {
class AlbumRepository : public BaseRepository
{
public: public:
AlbumRepository(const model::BinaryPath&); AlbumRepository(const model::BinaryPath&);
+12 -8
View File
@@ -1,6 +1,7 @@
#ifndef ARTISTREPOSITORY_H_ #ifndef ARTISTREPOSITORY_H_
#define ARTISTREPOSITORY_H_ #define ARTISTREPOSITORY_H_
#include <memory>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -8,16 +9,15 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/ArtistFilter.h" #include "type/ArtistFilter.h"
namespace database namespace database {
{ class ArtistRepository : public BaseRepository {
class ArtistRepository : public BaseRepository
{
public: public:
ArtistRepository(const model::BinaryPath&); ArtistRepository(const model::BinaryPath&);
std::vector<model::Artist> retrieveRecords(); std::vector<model::Artist> retrieveRecords();
std::pair<model::Artist, int> retrieveRecordWithSongCount(model::Artist&, type::ArtistFilter); std::pair<model::Artist, int> retrieveRecordWithSongCount(
model::Artist&, type::ArtistFilter);
model::Artist retrieveRecord(model::Artist&, type::ArtistFilter); model::Artist retrieveRecord(model::Artist&, type::ArtistFilter);
@@ -30,9 +30,13 @@ namespace database
std::pair<model::Artist, int> parseRecordWithSongCount(MYSQL_STMT*); std::pair<model::Artist, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented std::shared_ptr<MYSQL_BIND> valueBind(model::Artist&,
// remove parseRecord(MYSQL_RES*) std::tuple<char*>&);
model::Artist parseRecord(MYSQL_RES*); std::shared_ptr<MYSQL_BIND> valueBindWithSongCount(model::Artist&,
std::tuple<char*>&, int&);
std::tuple<char*> metadataBuffer();
model::Artist parseRecord(MYSQL_STMT*); model::Artist parseRecord(MYSQL_STMT*);
}; };
} }
+3 -5
View File
@@ -7,12 +7,10 @@
#include "model/Models.h" #include "model/Models.h"
namespace database namespace database {
{ class BaseRepository {
class BaseRepository
{
public: public:
BaseRepository(); BaseRepository() = default;
BaseRepository(const std::string&); BaseRepository(const std::string&);
BaseRepository(const model::BinaryPath&); BaseRepository(const model::BinaryPath&);
+9 -9
View File
@@ -1,6 +1,7 @@
#ifndef COVERARTREPOSITORY_H_ #ifndef COVERARTREPOSITORY_H_
#define COVERARTREPOSITORY_H_ #define COVERARTREPOSITORY_H_
#include <memory>
#include <vector> #include <vector>
#include <mysql/mysql.h> #include <mysql/mysql.h>
@@ -9,12 +10,9 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/CoverFilter.h" #include "type/CoverFilter.h"
namespace database namespace database {
{ class CoverArtRepository : public BaseRepository {
class CoverArtRepository : public BaseRepository
{
public: public:
CoverArtRepository(const std::string&);
CoverArtRepository(const model::BinaryPath&); CoverArtRepository(const model::BinaryPath&);
std::vector<model::Cover> retrieveRecords(); std::vector<model::Cover> retrieveRecords();
@@ -23,15 +21,17 @@ namespace database
bool doesCoverArtExist(const model::Cover&, type::CoverFilter); bool doesCoverArtExist(const model::Cover&, type::CoverFilter);
void deleteRecord(const model::Cover&); void deleteRecord(const model::Cover&, type::CoverFilter = type::CoverFilter::id);
void saveRecord(const model::Cover&); void saveRecord(const model::Cover&);
void updateRecord(const model::Cover&); void updateRecord(const model::Cover&);
private: private:
std::vector<model::Cover> parseRecords(MYSQL_STMT*); std::vector<model::Cover> parseRecords(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented std::shared_ptr<MYSQL_BIND> valueBind(model::Cover&,
// remove parseRecord(MYSQL_RES*) std::tuple<char*, char*>&);
model::Cover parseRecord(MYSQL_RES*);
std::tuple<char*, char*> metadataBuffer();
model::Cover parseRecord(MYSQL_STMT*); model::Cover parseRecord(MYSQL_STMT*);
}; };
} }
+10 -7
View File
@@ -1,6 +1,7 @@
#ifndef GENREREPOSITORY_H_ #ifndef GENREREPOSITORY_H_
#define GENREREPOSITORY_H_ #define GENREREPOSITORY_H_
#include <memory>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -8,10 +9,8 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/GenreFilter.h" #include "type/GenreFilter.h"
namespace database namespace database {
{ class GenreRepository : public BaseRepository {
class GenreRepository : public BaseRepository
{
public: public:
GenreRepository(const model::BinaryPath&); GenreRepository(const model::BinaryPath&);
@@ -30,9 +29,13 @@ namespace database
std::pair<model::Genre, int> parseRecordWithSongCount(MYSQL_STMT*); std::pair<model::Genre, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented std::shared_ptr<MYSQL_BIND> valueBind(model::Genre&,
// remove parseRecord(MYSQL_RES*) std::tuple<char*>&);
model::Genre parseRecord(MYSQL_RES*); std::shared_ptr<MYSQL_BIND> valueBindWithSongCount(model::Genre&,
std::tuple<char*>&, int&);
std::tuple<char*> metadataBuffer();
model::Genre parseRecord(MYSQL_STMT*); model::Genre parseRecord(MYSQL_STMT*);
}; };
} }
+4 -6
View File
@@ -11,18 +11,16 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/SongFilter.h" #include "type/SongFilter.h"
namespace database namespace database {
{ class SongRepository : public BaseRepository {
class SongRepository : public BaseRepository
{
public: public:
SongRepository(const model::BinaryPath&); SongRepository(const model::BinaryPath&);
std::vector<model::Song> retrieveRecords(); std::vector<model::Song> retrieveRecords();
model::Song retrieveRecord(const model::Song&, type::SongFilter); model::Song retrieveRecord(const model::Song&, type::SongFilter = type::SongFilter::id);
bool doesSongExist(const model::Song&, type::SongFilter); bool doesSongExist(const model::Song&, type::SongFilter = type::SongFilter::id);
bool deleteRecord(const model::Song&); bool deleteRecord(const model::Song&);
void saveRecord(const model::Song&); void saveRecord(const model::Song&);
+12 -12
View File
@@ -11,8 +11,8 @@
#include "type/UserFilter.h" #include "type/UserFilter.h"
namespace database { namespace database {
class UserRepository : BaseRepository { class UserRepository : BaseRepository {
public: public:
UserRepository(const model::BinaryPath&); UserRepository(const model::BinaryPath&);
model::User retrieveUserRecord(model::User&, type::UserFilter); model::User retrieveUserRecord(model::User&, type::UserFilter);
@@ -22,12 +22,11 @@ public:
void saveUserRecord(const model::User&); void saveUserRecord(const model::User&);
void saveUserSalt(const model::PassSec&); void saveUserSalt(const model::PassSec&);
private: private:
struct UserLengths; struct UserLengths;
struct SaltLengths; struct SaltLengths;
struct UserLengths struct UserLengths {
{
unsigned long firstnameLength; unsigned long firstnameLength;
unsigned long lastnameLength; unsigned long lastnameLength;
unsigned long phoneLength; unsigned long phoneLength;
@@ -35,14 +34,16 @@ private:
unsigned long usernameLength; unsigned long usernameLength;
unsigned long passwordLength; unsigned long passwordLength;
}; };
struct SaltLengths struct SaltLengths {
{
unsigned long saltLength; unsigned long saltLength;
}; };
std::shared_ptr<MYSQL_BIND> insertUserValues(const model::User&, std::shared_ptr<UserLengths>); std::shared_ptr<MYSQL_BIND> insertUserValues(const model::User&,
std::shared_ptr<MYSQL_BIND> insertSaltValues(const model::PassSec&, std::shared_ptr<SaltLengths>); std::shared_ptr<UserLengths>);
std::shared_ptr<MYSQL_BIND> valueBind(model::User&, std::tuple<char*, char*, char*, char*, char*, char*>&); std::shared_ptr<MYSQL_BIND> insertSaltValues(const model::PassSec&,
std::shared_ptr<SaltLengths>);
std::shared_ptr<MYSQL_BIND> valueBind(model::User&,
std::tuple<char*, char*, char*, char*, char*, char*>&);
std::shared_ptr<MYSQL_BIND> saltValueBind(model::PassSec&, char*); std::shared_ptr<MYSQL_BIND> saltValueBind(model::PassSec&, char*);
std::shared_ptr<UserLengths> fetchUserLengths(const model::User&); std::shared_ptr<UserLengths> fetchUserLengths(const model::User&);
std::shared_ptr<SaltLengths> fetchSaltLengths(const model::PassSec&); std::shared_ptr<SaltLengths> fetchSaltLengths(const model::PassSec&);
@@ -51,8 +52,7 @@ private:
model::User parseRecord(MYSQL_STMT*); model::User parseRecord(MYSQL_STMT*);
model::PassSec parseSaltRecord(MYSQL_STMT*); model::PassSec parseSaltRecord(MYSQL_STMT*);
}; };
} }
#endif #endif
+12 -11
View File
@@ -1,6 +1,7 @@
#ifndef YEARREPOSITORY_H_ #ifndef YEARREPOSITORY_H_
#define YEARREPOSITORY_H_ #define YEARREPOSITORY_H_
#include <memory>
#include <utility> #include <utility>
#include <vector> #include <vector>
@@ -8,31 +9,31 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/YearFilter.h" #include "type/YearFilter.h"
namespace database namespace database {
{ class YearRepository : public BaseRepository {
class YearRepository : public BaseRepository
{
public: public:
YearRepository(const model::BinaryPath&); YearRepository(const model::BinaryPath&);
std::vector<model::Year> retrieveRecords(); std::vector<model::Year> retrieveRecords();
std::pair<model::Year, int> retrieveRecordWithSongCount(model::Year&, type::YearFilter); std::pair<model::Year, int> retrieveRecordWithSongCount(model::Year&,
type::YearFilter = type::YearFilter::id);
model::Year retrieveRecord(model::Year&, type::YearFilter); model::Year retrieveRecord(model::Year&, type::YearFilter = type::YearFilter::id);
bool doesYearExist(const model::Year&, type::YearFilter); bool doesYearExist(const model::Year&, type::YearFilter = type::YearFilter::id);
void saveRecord(const model::Year&); void saveRecord(const model::Year&);
void deleteYear(const model::Year&, type::YearFilter); void deleteYear(const model::Year&, type::YearFilter = type::YearFilter::id);
private: private:
std::vector<model::Year> parseRecords(MYSQL_STMT*); std::vector<model::Year> parseRecords(MYSQL_STMT*);
std::pair<model::Year, int> parseRecordWithSongCount(MYSQL_STMT*); std::pair<model::Year, int> parseRecordWithSongCount(MYSQL_STMT*);
// TODO: After parseRecord(MYSQL_STMT*) is implemented std::shared_ptr<MYSQL_BIND> valueBind(model::Year&);
// remove parseRecord(MYSQL_RES*) std::shared_ptr<MYSQL_BIND> valueBindWithSongCount(model::Year&,
model::Year parseRecord(MYSQL_RES*); int&);
model::Year parseRecord(MYSQL_STMT*); model::Year parseRecord(MYSQL_STMT*);
}; };
} }
+2 -4
View File
@@ -4,12 +4,10 @@
#include "oatpp/core/data/mapping/type/Object.hpp" #include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/codegen.hpp"
namespace dto namespace dto {
{
#include OATPP_CODEGEN_BEGIN(DTO) #include OATPP_CODEGEN_BEGIN(DTO)
class AlbumDto : public oatpp::data::mapping::type::Object class AlbumDto : public oatpp::data::mapping::type::Object {
{
DTO_INIT(AlbumDto, Object) DTO_INIT(AlbumDto, Object)
DTO_FIELD(Int32, id); DTO_FIELD(Int32, id);
+2 -4
View File
@@ -4,12 +4,10 @@
#include "oatpp/core/data/mapping/type/Object.hpp" #include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/codegen.hpp"
namespace dto namespace dto {
{
#include OATPP_CODEGEN_BEGIN(DTO) #include OATPP_CODEGEN_BEGIN(DTO)
class ArtistDto : public oatpp::data::mapping::type::Object class ArtistDto : public oatpp::data::mapping::type::Object {
{
DTO_INIT(ArtistDto, Object) DTO_INIT(ArtistDto, Object)
DTO_FIELD(Int32, id); DTO_FIELD(Int32, id);
+2 -4
View File
@@ -4,12 +4,10 @@
#include "oatpp/core/data/mapping/type/Object.hpp" #include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/codegen.hpp"
namespace dto namespace dto {
{
#include OATPP_CODEGEN_BEGIN(DTO) #include OATPP_CODEGEN_BEGIN(DTO)
class CoverArtDto : public oatpp::data::mapping::type::Object class CoverArtDto : public oatpp::data::mapping::type::Object {
{
DTO_INIT(CoverArtDto, Object) DTO_INIT(CoverArtDto, Object)
DTO_FIELD(Int32, id); DTO_FIELD(Int32, id);
+2 -4
View File
@@ -4,12 +4,10 @@
#include "oatpp/core/data/mapping/type/Object.hpp" #include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/codegen.hpp"
namespace dto namespace dto {
{
#include OATPP_CODEGEN_BEGIN(DTO) #include OATPP_CODEGEN_BEGIN(DTO)
class GenreDto : public oatpp::data::mapping::type::Object class GenreDto : public oatpp::data::mapping::type::Object {
{
DTO_INIT(GenreDto, Object) DTO_INIT(GenreDto, Object)
DTO_FIELD(Int32, id); DTO_FIELD(Int32, id);
+2 -4
View File
@@ -6,12 +6,10 @@
#include "model/Models.h" #include "model/Models.h"
namespace dto namespace dto {
{
#include OATPP_CODEGEN_BEGIN(DTO) #include OATPP_CODEGEN_BEGIN(DTO)
class SongDto : public oatpp::data::mapping::type::Object class SongDto : public oatpp::data::mapping::type::Object {
{
DTO_INIT(SongDto, Object) DTO_INIT(SongDto, Object)
DTO_FIELD(Int32, id); DTO_FIELD(Int32, id);
+2 -4
View File
@@ -4,12 +4,10 @@
#include "oatpp/core/data/mapping/type/Object.hpp" #include "oatpp/core/data/mapping/type/Object.hpp"
#include "oatpp/core/macro/codegen.hpp" #include "oatpp/core/macro/codegen.hpp"
namespace dto namespace dto {
{
#include OATPP_CODEGEN_BEGIN(DTO) #include OATPP_CODEGEN_BEGIN(DTO)
class YearDto : public oatpp::data::mapping::type::Object class YearDto : public oatpp::data::mapping::type::Object {
{
DTO_INIT(YearDto, Object) DTO_INIT(YearDto, Object)
DTO_FIELD(Int32, id); DTO_FIELD(Int32, id);
+2 -4
View File
@@ -3,10 +3,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace manager namespace manager {
{ class AlbumManager {
class AlbumManager
{
public: public:
AlbumManager(const model::BinaryPath&); AlbumManager(const model::BinaryPath&);
+2 -4
View File
@@ -3,10 +3,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace manager namespace manager {
{ class ArtistManager {
class ArtistManager
{
public: public:
ArtistManager(const model::BinaryPath&); ArtistManager(const model::BinaryPath&);
+2 -6
View File
@@ -6,12 +6,9 @@
#include "model/Models.h" #include "model/Models.h"
namespace manager namespace manager {
{ class CoverArtManager {
class CoverArtManager
{
public: public:
CoverArtManager(const std::string&);
CoverArtManager(const model::BinaryPath& bConf); CoverArtManager(const model::BinaryPath& bConf);
model::Cover saveCover(const model::Song&); model::Cover saveCover(const model::Song&);
@@ -25,7 +22,6 @@ namespace manager
std::string createImagePath(const model::Song&); std::string createImagePath(const model::Song&);
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
std::string path;
}; };
} }
+4 -5
View File
@@ -9,13 +9,12 @@
#include "model/Models.h" #include "model/Models.h"
#include "type/PathType.h" #include "type/PathType.h"
namespace manager namespace manager {
{ class DirectoryManager {
class DirectoryManager
{
public: public:
static std::string createDirectoryProcess(model::Song, const std::string&); static std::string createDirectoryProcess(model::Song, const std::string&);
static std::string createDirectoryProcess(const model::Song&, const model::BinaryPath&, type::PathType); static std::string createDirectoryProcess(const model::Song&,
const model::BinaryPath&, type::PathType);
static std::string configPath(std::string_view); static std::string configPath(std::string_view);
static std::string configPath(const model::BinaryPath&); static std::string configPath(const model::BinaryPath&);
static std::string contentOfPath(const std::string&); static std::string contentOfPath(const std::string&);
+2 -4
View File
@@ -3,10 +3,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace manager namespace manager {
{ class GenreManager {
class GenreManager
{
public: public:
GenreManager(const model::BinaryPath&); GenreManager(const model::BinaryPath&);
+1 -2
View File
@@ -14,8 +14,7 @@
#include "type/SongUpload.h" #include "type/SongUpload.h"
namespace manager { namespace manager {
class SongManager class SongManager {
{
public: public:
SongManager(const model::BinaryPath&); SongManager(const model::BinaryPath&);
+4 -4
View File
@@ -14,15 +14,15 @@
#include "type/Scopes.h" #include "type/Scopes.h"
namespace manager { namespace manager {
class TokenManager { class TokenManager {
public: public:
TokenManager() = default; TokenManager() = default;
model::Token retrieveToken(const model::BinaryPath&); model::Token retrieveToken(const model::BinaryPath&);
bool isTokenValid(std::string&, type::Scope); bool isTokenValid(std::string&, type::Scope);
bool testAuth(const model::BinaryPath&); bool testAuth(const model::BinaryPath&);
private: private:
cpr::Response sendRequest(std::string_view, nlohmann::json&); cpr::Response sendRequest(std::string_view, nlohmann::json&);
nlohmann::json createTokenBody(const model::AuthCredentials&); nlohmann::json createTokenBody(const model::AuthCredentials&);
@@ -33,7 +33,7 @@ private:
std::pair<bool, std::vector<std::string>> fetchAuthHeader(const std::string&); std::pair<bool, std::vector<std::string>> fetchAuthHeader(const std::string&);
bool tokenSupportsScope(const std::vector<std::string>&, const std::string&&); bool tokenSupportsScope(const std::vector<std::string>&, const std::string&&);
}; };
} }
#endif #endif
+4 -4
View File
@@ -7,8 +7,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace manager { namespace manager {
class UserManager { class UserManager {
public: public:
UserManager(const model::BinaryPath&); UserManager(const model::BinaryPath&);
model::RegisterResult registerUser(model::User&); model::RegisterResult registerUser(model::User&);
@@ -17,9 +17,9 @@ public:
bool validatePassword(const model::User&); bool validatePassword(const model::User&);
void printUser(const model::User&); void printUser(const model::User&);
private: private:
model::BinaryPath m_bConf; model::BinaryPath m_bConf;
}; };
} }
#endif #endif
+2 -4
View File
@@ -3,10 +3,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace manager namespace manager {
{ class YearManager {
class YearManager
{
public: public:
YearManager(const model::BinaryPath&); YearManager(const model::BinaryPath&);
+37 -37
View File
@@ -5,8 +5,8 @@
#include <vector> #include <vector>
namespace model { namespace model {
class Song { class Song {
public: public:
Song() = default; Song() = default;
Song(const int id) : id(id) { } Song(const int id) : id(id) { }
Song(const int id, const std::string& title, const std::string& artist, Song(const int id, const std::string& title, const std::string& artist,
@@ -35,20 +35,20 @@ public:
int albumId; int albumId;
int genreId; int genreId;
int yearId; int yearId;
}; };
class Artist { class Artist {
public: public:
Artist() = default; Artist() = default;
Artist(const Song& song) : id(song.artistId), artist(song.artist) { } Artist(const Song& song) : id(song.artistId), artist(song.artist) { }
Artist(const int id) : id(id) { } Artist(const int id) : id(id) { }
int id; int id;
std::string artist; std::string artist;
}; };
class Album { class Album {
public: public:
Album() = default; Album() = default;
Album(const Song& song) : Album(const Song& song) :
id(song.albumId), title(song.album),artist(song.artist), year(song.year) { } id(song.albumId), title(song.album),artist(song.artist), year(song.year) { }
@@ -59,10 +59,10 @@ public:
std::string artist; std::string artist;
int year; int year;
std::vector<Song> songs; std::vector<Song> songs;
}; };
class Genre { class Genre {
public: public:
Genre() = default; Genre() = default;
Genre(const Song& song) : Genre(const Song& song) :
id(song.genreId), category(song.genre) { } id(song.genreId), category(song.genre) { }
@@ -71,10 +71,10 @@ public:
int id; int id;
std::string category; std::string category;
}; };
class Year { class Year {
public: public:
Year() = default; Year() = default;
Year(const Song& song) : Year(const Song& song) :
id(song.yearId), year(song.year) { } id(song.yearId), year(song.year) { }
@@ -82,10 +82,10 @@ public:
int id; int id;
int year; int year;
}; };
class Cover { class Cover {
public: public:
Cover() = default; Cover() = default;
Cover(const Song& song) : Cover(const Song& song) :
id(song.coverArtId), songTitle(song.title) { } id(song.coverArtId), songTitle(song.title) { }
@@ -96,10 +96,10 @@ public:
std::string imagePath; std::string imagePath;
// Not being used but it should be // Not being used but it should be
std::vector<unsigned char> data; std::vector<unsigned char> data;
}; };
class Token { class Token {
public: public:
Token() = default; Token() = default;
Token(const std::string& accessToken) : Token(const std::string& accessToken) :
accessToken(accessToken) { } accessToken(accessToken) { }
@@ -111,25 +111,25 @@ public:
std::string accessToken; std::string accessToken;
int expiration; int expiration;
std::string tokenType; std::string tokenType;
}; };
struct LoginResult { struct LoginResult {
int userId; int userId;
std::string username; std::string username;
std::string accessToken; std::string accessToken;
std::string tokenType; std::string tokenType;
std::string message; std::string message;
int expiration; int expiration;
}; };
class RegisterResult { class RegisterResult {
public: public:
std::string username; std::string username;
bool registered; bool registered;
std::string message; std::string message;
}; };
struct User { struct User {
int id; int id;
std::string firstname; std::string firstname;
std::string lastname; std::string lastname;
@@ -137,40 +137,40 @@ struct User {
std::string phone; std::string phone;
std::string username; std::string username;
std::string password; std::string password;
}; };
struct PassSec { struct PassSec {
int id; int id;
std::string hashPassword; std::string hashPassword;
std::string salt; std::string salt;
int userId; int userId;
}; };
struct AuthCredentials { struct AuthCredentials {
std::string domain; std::string domain;
std::string apiIdentifier; std::string apiIdentifier;
std::string clientId; std::string clientId;
std::string clientSecret; std::string clientSecret;
std::string uri; std::string uri;
std::string endpoint; std::string endpoint;
}; };
struct DatabaseConnection { struct DatabaseConnection {
std::string server; std::string server;
std::string username; std::string username;
std::string password; std::string password;
std::string database; std::string database;
}; };
class BinaryPath { class BinaryPath {
public: public:
BinaryPath() = default; BinaryPath() = default;
BinaryPath(const char *p) : path(p) { } BinaryPath(const char *p) : path(p) { }
BinaryPath(const std::string& p) : path(p) { } BinaryPath(const std::string& p) : path(p) { }
BinaryPath(const std::string&& p) : path(p) { } BinaryPath(const std::string&& p) : path(p) { }
std::string path; std::string path;
}; };
} }
#endif #endif
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef ALBUMFILTER_H_ #ifndef ALBUMFILTER_H_
#define ALBUMFILTER_H_ #define ALBUMFILTER_H_
namespace type namespace type {
{ enum class AlbumFilter {
enum class AlbumFilter
{
id = 0, id = 0,
title, title,
year year
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef ARTISTFILTER_H_ #ifndef ARTISTFILTER_H_
#define ARTISTFILTER_H_ #define ARTISTFILTER_H_
namespace type namespace type {
{ enum class ArtistFilter {
enum class ArtistFilter
{
id = 0, id = 0,
artist artist
}; };
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef COVERFILTER_H_ #ifndef COVERFILTER_H_
#define COVERFILTER_H_ #define COVERFILTER_H_
namespace type namespace type {
{ enum class CoverFilter {
enum class CoverFilter
{
id = 0, id = 0,
songTitle, songTitle,
imagePath imagePath
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef GENREFILTER_H_ #ifndef GENREFILTER_H_
#define GENREFILTER_H_ #define GENREFILTER_H_
namespace type namespace type {
{ enum class GenreFilter {
enum class GenreFilter
{
id = 0, id = 0,
category category
}; };
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef PATHTYPE_H_ #ifndef PATHTYPE_H_
#define PATHTYPE_H_ #define PATHTYPE_H_
namespace type namespace type {
{ enum PathType {
enum PathType
{
music = 0, music = 0,
archive, archive,
temp, temp,
+1 -2
View File
@@ -2,8 +2,7 @@
#define SALTFILTER_H_ #define SALTFILTER_H_
namespace type { namespace type {
enum class SaltFilter enum class SaltFilter {
{
id = 0, id = 0,
salt, salt,
userId userId
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef SCOPES_H_ #ifndef SCOPES_H_
#define SCOPES_H_ #define SCOPES_H_
namespace type namespace type {
{ enum class Scope {
enum class Scope
{
upload = 0, upload = 0,
download, download,
stream, stream,
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef SONGCHANGED_H_ #ifndef SONGCHANGED_H_
#define SONGCHANGED_H_ #define SONGCHANGED_H_
namespace type namespace type {
{ enum SongChanged {
enum SongChanged
{
title = 0, title = 0,
artist, artist,
album, album,
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef SONGFILTER_H_ #ifndef SONGFILTER_H_
#define SONGFILTER_H_ #define SONGFILTER_H_
namespace type namespace type {
{ enum class SongFilter {
enum class SongFilter
{
id = 0, id = 0,
title, title,
album, album,
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef SONGUPLOAD_H_ #ifndef SONGUPLOAD_H_
#define SONGUPLOAD_H_ #define SONGUPLOAD_H_
namespace type namespace type {
{ enum class SongUpload {
enum class SongUpload
{
Successful = 0, Successful = 0,
AlreadyExist = 1, AlreadyExist = 1,
Failed = 2 Failed = 2
+1 -2
View File
@@ -2,8 +2,7 @@
#define USERFILTER_H_ #define USERFILTER_H_
namespace type { namespace type {
enum class UserFilter enum class UserFilter {
{
id = 0, id = 0,
username username
}; };
+2 -4
View File
@@ -1,10 +1,8 @@
#ifndef YEARFILTER_H_ #ifndef YEARFILTER_H_
#define YEARFILTER_H_ #define YEARFILTER_H_
namespace type namespace type {
{ enum class YearFilter {
enum class YearFilter
{
id = 0, id = 0,
year year
}; };
+2 -4
View File
@@ -13,10 +13,8 @@
#include <tpropertymap.h> #include <tpropertymap.h>
#include <id3v2tag.h> #include <id3v2tag.h>
namespace utility namespace utility {
{ class ImageFile : public TagLib::File {
class ImageFile : public TagLib::File
{
public: public:
ImageFile(const char *file); ImageFile(const char *file);
+4 -5
View File
@@ -7,9 +7,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace utility { namespace utility {
class MetadataRetriever class MetadataRetriever {
{ public:
public:
model::Song retrieveMetadata(model::Song&); model::Song retrieveMetadata(model::Song&);
model::Cover updateCoverArt(const model::Song&, model::Cover&, const std::string&); model::Cover updateCoverArt(const model::Song&, model::Cover&, const std::string&);
@@ -19,8 +18,8 @@ public:
bool songContainsCoverArt(const model::Song&); bool songContainsCoverArt(const model::Song&);
void updateMetadata(model::Song&, const model::Song&); void updateMetadata(model::Song&, const model::Song&);
private: private:
}; };
} }
#endif #endif
+1 -1
View File
@@ -12,7 +12,7 @@ public:
bool isPasswordValid(const model::User&, const model::PassSec&); bool isPasswordValid(const model::User&, const model::PassSec&);
private: private:
int saltSize(); constexpr int saltSize() noexcept;
}; };
} }
+2 -4
View File
@@ -5,10 +5,8 @@
#include "model/Models.h" #include "model/Models.h"
namespace verify namespace verify {
{ class Initialization {
class Initialization
{
public: public:
static bool skipVerification(const std::string&); static bool skipVerification(const std::string&);
+3 -5
View File
@@ -23,8 +23,7 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
void run(const model::BinaryPath& bConf) void run(const model::BinaryPath& bConf) {
{
component::AppComponent component; component::AppComponent component;
OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router); OATPP_COMPONENT(std::shared_ptr<oatpp::web::server::HttpRouter>, router);
@@ -58,8 +57,7 @@ void run(const model::BinaryPath& bConf)
server.run(); server.run();
} }
int main(int argc, char **argv) int main(int argc, char **argv) {
{
oatpp::base::Environment::init(); oatpp::base::Environment::init();
model::BinaryPath bConf(std::move(argv[0])); model::BinaryPath bConf(std::move(argv[0]));
@@ -68,7 +66,7 @@ int main(int argc, char **argv)
if (!verify::Initialization::skipVerification(argv[1])) { if (!verify::Initialization::skipVerification(argv[1])) {
verify::Initialization::checkIcarus(bConf); verify::Initialization::checkIcarus(bConf);
} else { } else {
std::cout << "skiping verifyication" << std::endl; std::cout << "skiping verifyication\n";
} }
} else { } else {
verify::Initialization::checkIcarus(bConf); verify::Initialization::checkIcarus(bConf);
+8 -11
View File
@@ -5,25 +5,22 @@
#include <memory> #include <memory>
namespace callback { namespace callback {
StreamCallback::StreamCallback() : StreamCallback::StreamCallback() : m_counter(0) { }
m_counter(0) { }
StreamCallback::StreamCallback(const std::string& songPath) : StreamCallback::StreamCallback(const std::string& songPath) :
m_songPath(songPath), m_songPath(songPath),
m_counter(0), m_counter(0),
m_bytesRead(0) m_bytesRead(0) {
{
// getting file size // getting file size
std::ifstream song(m_songPath.c_str(), std::ios::binary | std::ios::in | std::ios::ate); std::ifstream song(m_songPath.c_str(), std::ios::binary | std::ios::in | std::ios::ate);
m_fileSize = song.tellg(); m_fileSize = song.tellg();
std::cout << "file size is " << m_fileSize << " bytes" << std::endl; std::cout << "file size is " << m_fileSize << " bytes\n";
} }
oatpp::data::v_io_size StreamCallback::read(void *buff, oatpp::data::v_io_size count) oatpp::data::v_io_size StreamCallback::read(void *buff, oatpp::data::v_io_size count) {
{
if (m_counter >= m_fileSize) { if (m_counter >= m_fileSize) {
std::cout << "done streaming song" << std::endl; std::cout << "done streaming song\n";
return 0; return 0;
} }
@@ -40,5 +37,5 @@ oatpp::data::v_io_size StreamCallback::read(void *buff, oatpp::data::v_io_size c
song.close(); song.close();
return count; return count;
} }
} }
+53 -65
View File
@@ -8,13 +8,10 @@
#include <cstring> #include <cstring>
namespace database { namespace database {
AlbumRepository::AlbumRepository(const model::BinaryPath& bConf) AlbumRepository::AlbumRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { }
: BaseRepository(bConf)
{ }
std::vector<model::Album> AlbumRepository::retrieveRecords() std::vector<model::Album> AlbumRepository::retrieveRecords() {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -28,12 +25,12 @@ std::vector<model::Album> AlbumRepository::retrieveRecords()
mysql_close(conn); mysql_close(conn);
return albums; return albums;
} }
std::pair<model::Album, int> AlbumRepository::retrieveRecordWithSongCount(model::Album& album, type::AlbumFilter filter = type::AlbumFilter::id) std::pair<model::Album, int> AlbumRepository::retrieveRecordWithSongCount(model::Album& album,
{ type::AlbumFilter filter = type::AlbumFilter::id) {
std::cout << "retrieving album with song count" << std::endl; std::cout << "retrieving album with song count\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -70,11 +67,10 @@ std::pair<model::Album, int> AlbumRepository::retrieveRecordWithSongCount(model:
mysql_close(conn); mysql_close(conn);
return albWSC; return albWSC;
} }
model::Album AlbumRepository::retrieveRecord(model::Album& album, type::AlbumFilter filter) model::Album AlbumRepository::retrieveRecord(model::Album& album, type::AlbumFilter filter) {
{ std::cout << "retrieving album record\n";
std::cout << "retrieving album record" << std::endl;
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -118,13 +114,12 @@ model::Album AlbumRepository::retrieveRecord(model::Album& album, type::AlbumFil
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "done" << std::endl; std::cout << "done\n";
return album; return album;
} }
bool AlbumRepository::doesAlbumExists(const model::Album& album, type::AlbumFilter filter) bool AlbumRepository::doesAlbumExists(const model::Album& album, type::AlbumFilter filter) {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -163,20 +158,19 @@ bool AlbumRepository::doesAlbumExists(const model::Album& album, type::AlbumFilt
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
::mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = ::mysql_stmt_num_rows(stmt); auto rowCount = mysql_stmt_num_rows(stmt);
::mysql_stmt_close(stmt); mysql_stmt_close(stmt);
::mysql_close(conn); mysql_close(conn);
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
void AlbumRepository::saveAlbum(const model::Album& album) void AlbumRepository::saveAlbum(const model::Album& album) {
{ std::cout << "beginning to insert album record\n";
std::cout << "beginning to insert album record" << std::endl;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
MYSQL_STMT *stmt = mysql_stmt_init(conn); MYSQL_STMT *stmt = mysql_stmt_init(conn);
@@ -211,12 +205,12 @@ void AlbumRepository::saveAlbum(const model::Album& album)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "done inserting album record" << std::endl; std::cout << "done inserting album record\n";
} }
void AlbumRepository::deleteAlbum(const model::Album& album, type::AlbumFilter filter = type::AlbumFilter::id) void AlbumRepository::deleteAlbum(const model::Album& album,
{ type::AlbumFilter filter = type::AlbumFilter::id) {
std::cout << "deleting album record" << std::endl; std::cout << "deleting album record\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
@@ -246,13 +240,12 @@ void AlbumRepository::deleteAlbum(const model::Album& album, type::AlbumFilter f
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "execute delete query" << std::endl; std::cout << "execute delete query\n";
} }
std::vector<model::Album> AlbumRepository::parseRecords(MYSQL_STMT* stmt) std::vector<model::Album> AlbumRepository::parseRecords(MYSQL_STMT* stmt) {
{ std::cout << "parsing album record\n";
std::cout << "parsing album record" << std::endl;
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
std::vector<model::Album> albums; std::vector<model::Album> albums;
@@ -270,28 +263,25 @@ std::vector<model::Album> AlbumRepository::parseRecords(MYSQL_STMT* stmt)
status = mysql_stmt_bind_result(stmt, bindedValues.get()); status = mysql_stmt_bind_result(stmt, bindedValues.get());
while (true) { while (true) {
std::cout << "fetching statement result" << std::endl; std::cout << "fetching statement result\n";
status = mysql_stmt_fetch(stmt); status = mysql_stmt_fetch(stmt);
if (status == 1 || status == MYSQL_NO_DATA) { if (status == 1 || status == MYSQL_NO_DATA) break;
break;
}
alb.title = std::get<0>(metaBuff); alb.title = std::get<0>(metaBuff);
alb.artist = std::get<1>(metaBuff); alb.artist = std::get<1>(metaBuff);
albums.push_back(std::move(alb)); albums.push_back(std::move(alb));
} }
} }
std::cout << "fetching next result" << std::endl; std::cout << "fetching next result\n";
} }
return albums; return albums;
} }
std::pair<model::Album, int> AlbumRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) std::pair<model::Album, int> AlbumRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) {
{ std::cout << "parsing album record with song count\n";
std::cout << "parsing album record with song count" << std::endl;
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = mysql_stmt_num_rows(stmt); auto rowCount = mysql_stmt_num_rows(stmt);
@@ -301,7 +291,7 @@ std::pair<model::Album, int> AlbumRepository::parseRecordWithSongCount(MYSQL_STM
auto val = valueBindWithSongCount(album, metaBuff, songCount); auto val = valueBindWithSongCount(album, metaBuff, songCount);
if (rowCount == 0) { if (rowCount == 0) {
std::cout << "no results" << std::endl; std::cout << "no results\n";
return std::make_pair(album, songCount); return std::make_pair(album, songCount);
} }
@@ -311,17 +301,16 @@ std::pair<model::Album, int> AlbumRepository::parseRecordWithSongCount(MYSQL_STM
album.title = std::get<0>(metaBuff); album.title = std::get<0>(metaBuff);
album.artist = std::get<1>(metaBuff); album.artist = std::get<1>(metaBuff);
std::cout << "done parsing album record with song count" << std::endl; std::cout << "done parsing album record with song count\n";
auto albWSC = std::make_pair(album, songCount); auto albWSC = std::make_pair(album, songCount);
return albWSC; return albWSC;
} }
std::shared_ptr<MYSQL_BIND> AlbumRepository::valueBind(model::Album& album, std::shared_ptr<MYSQL_BIND> AlbumRepository::valueBind(model::Album& album,
std::tuple<char*, char*>& metadata) std::tuple<char*, char*>& metadata) {
{
constexpr auto wordLen = 1024; constexpr auto wordLen = 1024;
constexpr auto valueCount = 4; constexpr auto valueCount = 4;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(valueCount, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(valueCount, sizeof(MYSQL_BIND)));
@@ -341,14 +330,14 @@ std::shared_ptr<MYSQL_BIND> AlbumRepository::valueBind(model::Album& album,
values.get()[3].buffer = (char*)&album.year; values.get()[3].buffer = (char*)&album.year;
return values; return values;
} }
std::shared_ptr<MYSQL_BIND> AlbumRepository::valueBindWithSongCount(model::Album& album, std::shared_ptr<MYSQL_BIND> AlbumRepository::valueBindWithSongCount(model::Album& album,
std::tuple<char*, char*>& metadata, int& songCount) std::tuple<char*, char*>& metadata, int& songCount) {
{
constexpr auto wordLen = 1024; constexpr auto wordLen = 1024;
constexpr auto valueCount = 5; constexpr auto valueCount = 5;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(valueCount, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values(
(MYSQL_BIND*) std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG; values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = (char*)&album.id; values.get()[0].buffer = (char*)&album.id;
@@ -368,22 +357,21 @@ std::shared_ptr<MYSQL_BIND> AlbumRepository::valueBindWithSongCount(model::Album
values.get()[4].buffer = (char*)&songCount; values.get()[4].buffer = (char*)&songCount;
return values; return values;
} }
std::tuple<char*, char*> AlbumRepository::metadataBuffer() std::tuple<char*, char*> AlbumRepository::metadataBuffer() {
{
constexpr auto wordLen = 1024; constexpr auto wordLen = 1024;
char title[wordLen]; char title[wordLen];
char artist[wordLen]; char artist[wordLen];
return std::make_tuple(title, artist); return std::make_tuple(title, artist);
} }
model::Album AlbumRepository::parseRecord(MYSQL_STMT *stmt) model::Album AlbumRepository::parseRecord(MYSQL_STMT *stmt)
{ {
std::cout << "parsing album record" << std::endl; std::cout << "parsing album record\n";
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rows = mysql_stmt_num_rows(stmt); auto rows = mysql_stmt_num_rows(stmt);
@@ -396,8 +384,8 @@ model::Album AlbumRepository::parseRecord(MYSQL_STMT *stmt)
album.title = std::get<0>(metaBuff); album.title = std::get<0>(metaBuff);
album.artist = std::get<1>(metaBuff); album.artist = std::get<1>(metaBuff);
std::cout << "done parsing album record" << std::endl; std::cout << "done parsing album record\n";
return album; return album;
} }
} }
+130 -185
View File
@@ -7,14 +7,11 @@
#include <cstring> #include <cstring>
namespace database { namespace database {
ArtistRepository::ArtistRepository(const model::BinaryPath& binConf) ArtistRepository::ArtistRepository(const model::BinaryPath& binConf) :
: BaseRepository(binConf) BaseRepository(binConf) { }
{
}
std::vector<model::Artist> ArtistRepository::retrieveRecords() std::vector<model::Artist> ArtistRepository::retrieveRecords() {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
const std::string query = "SELECT * FROM Artist"; const std::string query = "SELECT * FROM Artist";
@@ -28,11 +25,11 @@ std::vector<model::Artist> ArtistRepository::retrieveRecords()
mysql_close(conn); mysql_close(conn);
return artists; return artists;
} }
std::pair<model::Artist, int> ArtistRepository::retrieveRecordWithSongCount(model::Artist& artist, type::ArtistFilter filter = type::ArtistFilter::id) std::pair<model::Artist, int> ArtistRepository::retrieveRecordWithSongCount(
{ model::Artist& artist, type::ArtistFilter filter = type::ArtistFilter::id) {
std::cout << "retrieving artist record with song count" << std::endl; std::cout << "retrieving artist record with song count\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -64,7 +61,7 @@ std::pair<model::Artist, int> ArtistRepository::retrieveRecordWithSongCount(mode
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "Artist record with song count query "; std::cout << "Artist record with song count query ";
std::cout << "has been performed" << std::endl; std::cout << "has been performed\n";
auto artWSC = parseRecordWithSongCount(stmt); auto artWSC = parseRecordWithSongCount(stmt);
@@ -72,11 +69,11 @@ std::pair<model::Artist, int> ArtistRepository::retrieveRecordWithSongCount(mode
mysql_close(conn); mysql_close(conn);
return artWSC; return artWSC;
} }
model::Artist ArtistRepository::retrieveRecord(model::Artist& artist, type::ArtistFilter filter) model::Artist ArtistRepository::retrieveRecord(model::Artist& artist,
{ type::ArtistFilter filter) {
std::cout << "retrieving artist record" << std::endl; std::cout << "retrieving artist record\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -119,13 +116,12 @@ model::Artist ArtistRepository::retrieveRecord(model::Artist& artist, type::Arti
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "retrieved record" << std::endl; std::cout << "retrieved record\n";
return artist; return artist;
} }
bool ArtistRepository::doesArtistExist(const model::Artist& artist, type::ArtistFilter filter) bool ArtistRepository::doesArtistExist(const model::Artist& artist, type::ArtistFilter filter) {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -164,7 +160,7 @@ bool ArtistRepository::doesArtistExist(const model::Artist& artist, type::Artist
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = mysql_stmt_num_rows(stmt); auto rowCount = mysql_stmt_num_rows(stmt);
@@ -173,11 +169,10 @@ bool ArtistRepository::doesArtistExist(const model::Artist& artist, type::Artist
mysql_close(conn); mysql_close(conn);
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
void ArtistRepository::saveRecord(const model::Artist& artist) void ArtistRepository::saveRecord(const model::Artist& artist) {
{ std::cout << "inserting artist record\n";
std::cout << "inserting artist record" << std::endl;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
MYSQL_STMT *stmt = mysql_stmt_init(conn); MYSQL_STMT *stmt = mysql_stmt_init(conn);
@@ -201,11 +196,12 @@ void ArtistRepository::saveRecord(const model::Artist& artist)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout<< "inserted artist record" << std::endl; std::cout<< "inserted artist record\n";
} }
void ArtistRepository::deleteArtist(const model::Artist& artist, type::ArtistFilter filter = type::ArtistFilter::id) { void ArtistRepository::deleteArtist(const model::Artist& artist,
std::cout << "delete Artist record" << std::endl; type::ArtistFilter filter = type::ArtistFilter::id) {
std::cout << "delete Artist record\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -237,180 +233,129 @@ void ArtistRepository::deleteArtist(const model::Artist& artist, type::ArtistFil
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "deleted artist record" << std::endl; std::cout << "deleted artist record\n";
} }
std::vector<model::Artist> ArtistRepository::parseRecords(MYSQL_STMT *stmt) std::vector<model::Artist> ArtistRepository::parseRecords(MYSQL_STMT *stmt) {
{
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
std::vector<model::Artist> artists; std::vector<model::Artist> artists;
artists.reserve(mysql_stmt_num_rows(stmt)); artists.reserve(mysql_stmt_num_rows(stmt));
if (mysql_stmt_field_count(stmt) == 0) { constexpr auto valAmt = 2;
std::cout << "field count is 0" << std::endl;
return artists;
}
model::Artist art;
const auto valAmt = 2;
unsigned long len[valAmt]; unsigned long len[valAmt];
my_bool nullRes[valAmt]; my_bool nullRes[valAmt];
auto res = mysql_stmt_result_metadata(stmt); for (auto status = 0; status == 0; status = mysql_stmt_next_result(stmt)) {
auto fields = mysql_fetch_fields(res);
const auto strLen = 1024;
char artist[strLen];
MYSQL_BIND val[valAmt];
memset(val, 0, sizeof(val));
val[0].buffer_type = MYSQL_TYPE_LONG;
val[0].buffer = (char*)&art.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_STRING;
val[1].buffer = (char*)artist;
val[1].buffer_length = strLen;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
for (auto status = mysql_stmt_bind_result(stmt, val); status == 0; ) {
std::cout << "fetching statement result" << std::endl;
status = mysql_stmt_fetch(stmt);
if (status == 0) {
art.artist = artist;
artists.push_back(std::move(art));
}
}
return artists;
}
model::Artist ArtistRepository::parseRecord(MYSQL_RES* results)
{
std::cout << "parsing artist record" << std::endl;
model::Artist artist;
auto fieldNum = mysql_num_fields(results);
auto row = mysql_fetch_row(results);
for (auto i = 0; i != fieldNum; ++i) {
const std::string field(mysql_fetch_field(results)->name);
if (field.compare("ArtistId") == 0) {
artist.id = std::stoi(row[i]);
}
if (field.compare("Artist") == 0) {
artist.artist = row[i];
}
}
std::cout << "parsed artist record" << std::endl;
return artist;
}
std::pair<model::Artist, int> ArtistRepository::parseRecordWithSongCount(MYSQL_STMT *stmt)
{
std::cout << "parsing artist record with song count" << std::endl;
mysql_stmt_store_result(stmt);
const auto strLen = 1024;
const auto valAmt = 3;
unsigned long len[valAmt];
my_bool nullRes[valAmt];
model::Artist artist;
int songCount = 0;
if (mysql_stmt_num_rows(stmt) == 0) {
std::cout << "no results" << std::endl;
return std::make_pair(artist, songCount);
}
MYSQL_BIND params[valAmt];
std::memset(params, 0, sizeof(params));
char art[strLen];
params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = (char*)&artist.id;
params[0].length = &len[0];
params[0].is_null = &nullRes[0];
params[1].buffer_type = MYSQL_TYPE_STRING;
params[1].buffer = (char*)art;
params[1].buffer_length = strLen;
params[1].length = &len[1];
params[1].is_null = &nullRes[1];
params[2].buffer_type = MYSQL_TYPE_LONG;
params[2].buffer = (char*)&songCount;
params[2].length = &len[2];
params[2].is_null = &nullRes[2];
mysql_stmt_bind_result(stmt, params);
mysql_stmt_fetch(stmt);
artist.artist = std::move(art);
std::cout << "parsed artist record with song count" << std::endl;
return std::make_pair(artist, songCount);
}
model::Artist ArtistRepository::parseRecord(MYSQL_STMT *stmt)
{
std::cout << "parsing artist record" << std::endl;
mysql_stmt_store_result(stmt);
model::Artist art;
auto status = 0;
auto time = 0;
auto valAmt = 2;
unsigned long len[valAmt];
my_bool nullRes[valAmt];
while (status == 0) {
if (mysql_stmt_field_count(stmt) > 0) { if (mysql_stmt_field_count(stmt) > 0) {
auto res = mysql_stmt_result_metadata(stmt); model::Artist art;
auto fields = mysql_fetch_fields(res); auto metaBuff = metadataBuffer();
auto strLen = 1024; auto bindedValues = valueBind(art, metaBuff);
status = mysql_stmt_bind_result(stmt, bindedValues.get());
MYSQL_BIND val[valAmt];
memset(val, 0, sizeof(val));
char artist[strLen];
val[0].buffer_type = MYSQL_TYPE_LONG;
val[0].buffer = (char*)&art.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_STRING;
val[1].buffer = (char*)&artist;
val[1].buffer_length = strLen;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
status = mysql_stmt_bind_result(stmt, val);
mysql_stmt_store_result(stmt);
std::cout << "fetching statement result\n";
status = mysql_stmt_fetch(stmt); status = mysql_stmt_fetch(stmt);
art.artist = artist; if (status == 1 || status == MYSQL_NO_DATA) break;
art.artist = std::get<0>(metaBuff);
artists.push_back(art);
}
std::cout << "fetching next result\n";
} }
status = mysql_stmt_next_result(stmt); return artists;
} }
std::cout << "done parsing artist record" << std::endl;
std::pair<model::Artist, int> ArtistRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) {
std::cout << "parsing artist record with song count\n";
mysql_stmt_store_result(stmt);
const auto rowCount = mysql_stmt_num_rows(stmt);
model::Artist artist;
auto metaBuff = metadataBuffer();
auto songCount = 0;
auto val = valueBindWithSongCount(artist, metaBuff, songCount);
if (rowCount == 0) {
std::cout << "no results\n";
return std::make_pair(artist, songCount);
}
auto status = mysql_stmt_bind_result(stmt, val.get());
status = mysql_stmt_fetch(stmt);
artist.artist = std::get<0>(metaBuff);
std::cout << "done parsing album record with song count\n";
return std::make_pair(artist, songCount);
}
std::shared_ptr<MYSQL_BIND> ArtistRepository::valueBind(model::Artist& artist,
std::tuple<char*>& metadata) {
constexpr auto valueCount = 2;
constexpr auto wordLen = 1024;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = (char*)&artist.id;
values.get()[1].buffer_type = MYSQL_TYPE_STRING;
values.get()[1].buffer = (char*)std::get<0>(metadata);
values.get()[1].buffer_length = wordLen;
return values;
}
std::shared_ptr<MYSQL_BIND> ArtistRepository::valueBindWithSongCount(model::Artist& artist,
std::tuple<char*>& metadata, int& songCount) {
constexpr auto valueCount = 3;
constexpr auto wordLen = 1024;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = reinterpret_cast<char*>(&artist.id);
values.get()[1].buffer_type = MYSQL_TYPE_STRING;
values.get()[1].buffer = reinterpret_cast<char*>(std::get<0>(metadata));
values.get()[1].buffer_length = wordLen;
values.get()[2].buffer_type = MYSQL_TYPE_LONG;
values.get()[2].buffer = reinterpret_cast<char*>(&songCount);
return values;
}
std::tuple<char*> ArtistRepository::metadataBuffer() {
constexpr auto wordLen = 1024;
char artist[wordLen];
return std::make_tuple(artist);
}
model::Artist ArtistRepository::parseRecord(MYSQL_STMT *stmt) {
std::cout << "parsing artist record\n";
mysql_stmt_store_result(stmt);
model::Artist art;
auto metaBuff = metadataBuffer();
auto bindedValues = valueBind(art, metaBuff);
auto status = mysql_stmt_bind_result(stmt, bindedValues.get());
status = mysql_stmt_fetch(stmt);
art.artist = std::get<0>(metaBuff);
std::cout << "done parsing artist record\n";
return art; return art;
} }
} }
+28 -38
View File
@@ -7,85 +7,75 @@
#include "manager/DirectoryManager.h" #include "manager/DirectoryManager.h"
namespace database { namespace database {
BaseRepository::BaseRepository() BaseRepository::BaseRepository(const std::string& path) : path(path) {
{ }
BaseRepository::BaseRepository(const std::string& path) : path(path)
{
intitalizeDetails(); intitalizeDetails();
} }
BaseRepository::BaseRepository(const model::BinaryPath& bConf) BaseRepository::BaseRepository(const model::BinaryPath& bConf) {
{
initializeDetails(bConf); initializeDetails(bConf);
} }
bool BaseRepository::testConnection() bool BaseRepository::testConnection() {
{
auto conn = mysql_init(nullptr); auto conn = mysql_init(nullptr);
if (!mysql_real_connect(conn, details.server.c_str(), details.username.c_str(), if (!mysql_real_connect(conn, details.server.c_str(), details.username.c_str(),
details.password.c_str(), details.database.c_str(), 0, details.password.c_str(), details.database.c_str(), 0, nullptr, 0)) {
nullptr, 0)) { std::cout << "failed to connect to the database\n";
std::cout << "failed to connect to the database" << std::endl;
return false; return false;
} }
mysql_close(conn); mysql_close(conn);
return true; return true;
} }
MYSQL* BaseRepository::setupMysqlConnection() MYSQL* BaseRepository::setupMysqlConnection() {
{
MYSQL *conn = mysql_init(nullptr); MYSQL *conn = mysql_init(nullptr);
if (!mysql_real_connect(conn, details.server.c_str(), details.username.c_str(), if (!mysql_real_connect(conn, details.server.c_str(), details.username.c_str(),
details.password.c_str(), details.database.c_str(), 0, nullptr, 0)) { details.password.c_str(), details.database.c_str(), 0, nullptr, 0)) {
std::cout << "connection error" << std::endl; std::cout << "connection error\n";
} }
return conn; return conn;
} }
MYSQL* BaseRepository::setupMysqlConnection(model::DatabaseConnection details) MYSQL* BaseRepository::setupMysqlConnection(model::DatabaseConnection details) {
{
MYSQL *connection = mysql_init(NULL); MYSQL *connection = mysql_init(NULL);
// connect to the database with the details attached. // connect to the database with the details attached.
if (!mysql_real_connect(connection,details.server.c_str(), details.username.c_str(), details.password.c_str(), details.database.c_str(), 0, NULL, 0)) { if (!mysql_real_connect(connection,details.server.c_str(), details.username.c_str(),
printf("Conection error : %s\n", mysql_error(connection)); details.password.c_str(), details.database.c_str(), 0, NULL, 0)) {
exit(1); std::cout << "Connection error: " << mysql_error(connection) << "\n";
std::exit(-1);
} }
return connection; return connection;
} }
MYSQL_RES* BaseRepository::performMysqlQuery(MYSQL *conn, const std::string& query) MYSQL_RES* BaseRepository::performMysqlQuery(MYSQL *conn, const std::string& query) {
{
// send the query to the database // send the query to the database
if (mysql_query(conn, query.c_str())) if (mysql_query(conn, query.c_str())) {
{
printf("MySQL query error : %s\n", mysql_error(conn)); printf("MySQL query error : %s\n", mysql_error(conn));
exit(1); std::cout << "MySQL query error : " << mysql_error(conn) << "\n";
std::exit(1);
} }
return mysql_use_result(conn); return mysql_use_result(conn);
} }
void BaseRepository::intitalizeDetails() void BaseRepository::intitalizeDetails() {
{
auto databaseConfig = manager::DirectoryManager::databaseConfigContent(path); auto databaseConfig = manager::DirectoryManager::databaseConfigContent(path);
details.database = databaseConfig["database"].get<std::string>(); details.database = databaseConfig["database"].get<std::string>();
details.password = databaseConfig["password"].get<std::string>(); details.password = databaseConfig["password"].get<std::string>();
details.server = databaseConfig["server"].get<std::string>(); details.server = databaseConfig["server"].get<std::string>();
details.username = databaseConfig["username"].get<std::string>(); details.username = databaseConfig["username"].get<std::string>();
} }
void BaseRepository::initializeDetails(const model::BinaryPath& bConf) void BaseRepository::initializeDetails(const model::BinaryPath& bConf)
{ {
auto databaseConfig = manager::DirectoryManager::databaseConfigContent(bConf); auto databaseConfig = manager::DirectoryManager::databaseConfigContent(bConf);
details.database = databaseConfig["database"].get<std::string>(); details.database = databaseConfig["database"].get<std::string>();
@@ -93,6 +83,6 @@ void BaseRepository::initializeDetails(const model::BinaryPath& bConf)
details.username = databaseConfig["username"].get<std::string>(); details.username = databaseConfig["username"].get<std::string>();
details.password = databaseConfig["password"].get<std::string>(); details.password = databaseConfig["password"].get<std::string>();
std::cout << "retrieved database details" << std::endl; std::cout << "retrieved database details\n";
} }
} }
+101 -151
View File
@@ -7,15 +7,11 @@
#include <cstring> #include <cstring>
namespace database { namespace database {
CoverArtRepository::CoverArtRepository(const std::string& path) : BaseRepository(path) CoverArtRepository::CoverArtRepository(const model::BinaryPath& bConf) :
{ } BaseRepository(bConf) { }
CoverArtRepository::CoverArtRepository(const model::BinaryPath& bConf) : BaseRepository(bConf)
{ }
std::vector<model::Cover> CoverArtRepository::retrieveRecords() std::vector<model::Cover> CoverArtRepository::retrieveRecords() {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
const std::string query = "SELECT * FROM CoverArt"; const std::string query = "SELECT * FROM CoverArt";
@@ -29,10 +25,10 @@ std::vector<model::Cover> CoverArtRepository::retrieveRecords()
mysql_close(conn); mysql_close(conn);
return coverArts; return coverArts;
} }
model::Cover CoverArtRepository::retrieveRecord(model::Cover& cov, type::CoverFilter filter = type::CoverFilter::id) model::Cover CoverArtRepository::retrieveRecord(model::Cover& cov,
{ type::CoverFilter filter = type::CoverFilter::id) {
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -75,14 +71,14 @@ model::Cover CoverArtRepository::retrieveRecord(model::Cover& cov, type::CoverFi
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "retrieved cover art record" << std::endl; std::cout << "retrieved cover art record\n";
return covDb; return covDb;
} }
bool CoverArtRepository::doesCoverArtExist(const model::Cover& cover, type::CoverFilter filter) bool CoverArtRepository::doesCoverArtExist(const model::Cover& cover,
{ type::CoverFilter filter) {
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -121,7 +117,7 @@ bool CoverArtRepository::doesCoverArtExist(const model::Cover& cover, type::Cove
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = mysql_stmt_num_rows(stmt); auto rowCount = mysql_stmt_num_rows(stmt);
@@ -130,22 +126,46 @@ bool CoverArtRepository::doesCoverArtExist(const model::Cover& cover, type::Cove
mysql_close(conn); mysql_close(conn);
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
// TODO: change to prepared statement void CoverArtRepository::deleteRecord(const model::Cover& cov,
void CoverArtRepository::deleteRecord(const model::Cover& cov) type::CoverFilter filter) {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
const std::string query("DELETE FROM CoverArt WHERE CoverArtId = " + std::to_string(cov.id)); auto stmt = mysql_stmt_init(conn);
std::cout << "delete CoverArt record\n";
std::stringstream qry;
qry << "DELETE FROM CoverArt WHERE ";
auto result = performMysqlQuery(conn, query); MYSQL_BIND params[1];
std::memset(params, 0, sizeof(params));
switch (filter) {
case type::CoverFilter::id:
qry << "CoverArtId = ?";
params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = (char*)&cov.id;
params[0].length = 0;
params[0].is_null = 0;
break;
default:
break;
}
const auto query = qry.str();
auto status = mysql_stmt_prepare(stmt, query.c_str(), query.size());
status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt);
mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
}
void CoverArtRepository::saveRecord(const model::Cover& cov) std::cout << "deleted CoverArt record\n";
{ }
void CoverArtRepository::saveRecord(const model::Cover& cov) {
std::cout << "saving cover art record"; std::cout << "saving cover art record";
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -176,11 +196,10 @@ void CoverArtRepository::saveRecord(const model::Cover& cov)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "saved cover art record" << std::endl; std::cout << "saved cover art record\n";
} }
void CoverArtRepository::updateRecord(const model::Cover& cover) void CoverArtRepository::updateRecord(const model::Cover& cover) {
{
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -219,158 +238,89 @@ void CoverArtRepository::updateRecord(const model::Cover& cover)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "updated cover art record" << std::endl; std::cout << "updated cover art record\n";
} }
std::vector<model::Cover> CoverArtRepository::parseRecords(MYSQL_STMT *stmt) std::vector<model::Cover> CoverArtRepository::parseRecords(MYSQL_STMT *stmt) {
{
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = mysql_stmt_num_rows(stmt); const auto rowCount = mysql_stmt_num_rows(stmt);
std::cout << "number of results " << rowCount << std::endl; std::cout << "number of results " << rowCount << "\n";
std::vector<model::Cover> coverArts; std::vector<model::Cover> coverArts;
coverArts.reserve(rowCount); coverArts.reserve(rowCount);
const auto valAmt = 3; constexpr auto valAmt = 3;
unsigned long len[valAmt];
my_bool nullRes[valAmt];
for (auto status = 0; status == 0; status = mysql_stmt_next_result(stmt)) { for (auto status = 0; status == 0; status = mysql_stmt_next_result(stmt)) {
if (mysql_stmt_field_count(stmt) > 0) { if (mysql_stmt_field_count(stmt) > 0) {
model::Cover coverArt; model::Cover cover;
auto res = mysql_stmt_result_metadata(stmt); auto metaBuff = metadataBuffer();
auto fields = mysql_fetch_fields(res); auto bindedValues = valueBind(cover, metaBuff);
auto strLen = 1024; status = mysql_stmt_bind_result(stmt, bindedValues.get());
MYSQL_BIND val[valAmt]; std::cout << "fetching statement result\n";
memset(val, 0, sizeof(val));
char songTitle[strLen];
char imagePath[strLen];
val[0].buffer_type = MYSQL_TYPE_LONG;
val[0].buffer = (char*)&coverArt.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_STRING;
val[1].buffer = (char*)songTitle;
val[1].buffer_length = strLen;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
val[2].buffer_type = MYSQL_TYPE_STRING;
val[2].buffer = (char*)imagePath;
val[2].buffer_length = strLen;
val[2].length = &len[2];
val[2].is_null = &nullRes[2];
status = mysql_stmt_bind_result(stmt, val);
while (true) {
std::cout << "fetching statement result" << std::endl;
status = mysql_stmt_fetch(stmt); status = mysql_stmt_fetch(stmt);
if (status == 1 || status == MYSQL_NO_DATA) { if (status == 1 || status == MYSQL_NO_DATA) break;
break;
}
coverArt.songTitle = songTitle; cover.songTitle = std::get<0>(metaBuff);
coverArt.imagePath = imagePath; cover.imagePath = std::get<1>(metaBuff);
coverArts.push_back(cover);
coverArts.push_back(std::move(coverArt));
} }
} std::cout << "fetching next result\n";
std::cout << "fetching next result" << std::endl;
} }
return coverArts; return coverArts;
}
model::Cover CoverArtRepository::parseRecord(MYSQL_RES *results)
{
std::cout << "parsing record" << std::endl;
model::Cover cov;
auto fieldNum = mysql_num_fields(results);
MYSQL_ROW row = mysql_fetch_row(results);
for (auto i = 0; i != fieldNum; ++i) {
switch (i) {
case 0:
cov.id = std::stoi(row[i]);
break;
case 1:
cov.songTitle = row[i];
break;
case 2:
cov.imagePath = row[i];
break;
} }
std::shared_ptr<MYSQL_BIND> CoverArtRepository::valueBind(model::Cover& cover,
std::tuple<char*, char*>& metadata) {
constexpr auto valueCount = 3;
constexpr auto wordLen = 1024;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = reinterpret_cast<char*>(&cover.id);
values.get()[1].buffer_type = MYSQL_TYPE_STRING;
values.get()[1].buffer = reinterpret_cast<char*>(std::get<0>(metadata));
values.get()[1].buffer_length = wordLen;
values.get()[2].buffer_type = MYSQL_TYPE_STRING;
values.get()[2].buffer = reinterpret_cast<char*>(std::get<1>(metadata));
values.get()[2].buffer_length = wordLen;
return values;
} }
std::cout << "done parsing record" << std::endl;
return cov;
}
model::Cover CoverArtRepository::parseRecord(MYSQL_STMT *stmt) std::tuple<char*, char*> CoverArtRepository::metadataBuffer() {
{ constexpr auto wordLen = 1024;
std::cout << "parsing cover art record" << std::endl; char songTitle[wordLen];
char imagePath[wordLen];
return std::make_pair(songTitle, imagePath);
}
model::Cover CoverArtRepository::parseRecord(MYSQL_STMT *stmt) {
std::cout << "parsing cover art record\n";
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
model::Cover cover; model::Cover cover;
auto status = 0; auto metaBuff = metadataBuffer();
auto time = 0; auto bindedValues = valueBind(cover, metaBuff);
auto valAmt = 3; auto status = mysql_stmt_bind_result(stmt, bindedValues.get());
unsigned long len[valAmt];
my_bool nullRes[valAmt];
while (status == 0) {
if (mysql_stmt_field_count(stmt) > 0) {
auto res = mysql_stmt_result_metadata(stmt);
auto fields = mysql_fetch_fields(res);
auto strLen = 1024;
MYSQL_BIND val[valAmt];
memset(val, 0, sizeof(val));
char songTitle[strLen];
char imagePath[strLen];
val[0].buffer_type = MYSQL_TYPE_LONG;
val[0].buffer = (char*)&cover.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_STRING;
val[1].buffer = (char*)&songTitle;
val[1].buffer_length = strLen;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
val[2].buffer_type = MYSQL_TYPE_STRING;
val[2].buffer = (char*)&imagePath;
val[2].buffer_length = strLen;
val[2].length = &len[2];
val[2].is_null = &nullRes[2];
status = mysql_stmt_bind_result(stmt, val);
mysql_stmt_store_result(stmt);
status = mysql_stmt_fetch(stmt); status = mysql_stmt_fetch(stmt);
cover.songTitle = songTitle; cover.songTitle = std::get<0>(metaBuff);
cover.imagePath = imagePath; cover.imagePath = std::get<1>(metaBuff);
}
status = mysql_stmt_next_result(stmt); std::cout << "done parsing cover art record\n";
}
std::cout << "done parsing cover art record" << std::endl;
return cover; return cover;
} }
} }
+131 -138
View File
@@ -6,14 +6,10 @@
#include <cstring> #include <cstring>
namespace database { namespace database {
GenreRepository::GenreRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { }
GenreRepository::GenreRepository(const model::BinaryPath& bConf)
: BaseRepository(bConf)
{ }
std::vector<model::Genre> GenreRepository::retrieveRecords() std::vector<model::Genre> GenreRepository::retrieveRecords() {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
const std::string query = "SELECT * FROM Genre"; const std::string query = "SELECT * FROM Genre";
@@ -27,11 +23,11 @@ std::vector<model::Genre> GenreRepository::retrieveRecords()
mysql_close(conn); mysql_close(conn);
return genres; return genres;
} }
std::pair<model::Genre, int> GenreRepository::retrieveRecordWithSongCount(model::Genre& genre, type::GenreFilter filter = type::GenreFilter::id) std::pair<model::Genre, int> GenreRepository::retrieveRecordWithSongCount(
{ model::Genre& genre, type::GenreFilter filter = type::GenreFilter::id) {
std::cout << "retrieving genre record with song count" << std::endl; std::cout << "retrieving genre record with song count\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -68,29 +64,38 @@ std::pair<model::Genre, int> GenreRepository::retrieveRecordWithSongCount(model:
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "retrieved genre record with song count" << std::endl; std::cout << "retrieved genre record with song count\n";
return gnrWSC; return gnrWSC;
} }
model::Genre GenreRepository::retrieveRecord(model::Genre& genre, type::GenreFilter filter) model::Genre GenreRepository::retrieveRecord(model::Genre& genre, type::GenreFilter filter) {
{ std::cout << "retrieving genre record\n";
// TODO: change to prepared statement
std::cout << "retrieving genre record" << std::endl;
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn);
qry << "SELECT gnr.* FROM Genre gnr WHERE "; qry << "SELECT gnr.* FROM Genre gnr WHERE ";
std::unique_ptr<char*> param; MYSQL_BIND params[1];
std::memset(params, 0, sizeof(params));
auto categoryLength = genre.category.size();
switch (filter) { switch (filter) {
case type::GenreFilter::id: case type::GenreFilter::id:
qry << "gnr.GenreId = " << genre.id; qry << "gnr.GenreId = ?";
params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = reinterpret_cast<char*>(&genre.id);
params[0].length = 0;
params[0].is_null = 0;
break; break;
case type::GenreFilter::category: case type::GenreFilter::category:
param = std::make_unique<char*>(new char[genre.category.size()]); qry << "gnr.Category = ?";
mysql_real_escape_string(conn, *param, genre.category.c_str(), genre.category.size());
qry << "gnr.Category ='" << *param << "'"; params[0].buffer_type = MYSQL_TYPE_STRING;
params[0].buffer = const_cast<char*>(genre.category.c_str());
params[0].length = &categoryLength;
params[0].is_null = 0;
break; break;
default: default:
break; break;
@@ -99,19 +104,21 @@ model::Genre GenreRepository::retrieveRecord(model::Genre& genre, type::GenreFil
qry << " ORDER BY GenreId DESC LIMIT 1"; qry << " ORDER BY GenreId DESC LIMIT 1";
const auto query = qry.str(); const auto query = qry.str();
auto results = performMysqlQuery(conn, query); auto status = mysql_stmt_prepare(stmt, query.c_str(), query.size());
status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt);
genre = parseRecord(results); genre = parseRecord(stmt);
mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "retrieved record" << std::endl; std::cout << "retrieved record\n";
return genre; return genre;
} }
bool GenreRepository::doesGenreExist(const model::Genre& genre, type::GenreFilter filter) bool GenreRepository::doesGenreExist(const model::Genre& genre, type::GenreFilter filter) {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -150,7 +157,7 @@ bool GenreRepository::doesGenreExist(const model::Genre& genre, type::GenreFilte
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = mysql_stmt_num_rows(stmt); auto rowCount = mysql_stmt_num_rows(stmt);
@@ -159,11 +166,10 @@ bool GenreRepository::doesGenreExist(const model::Genre& genre, type::GenreFilte
mysql_close(conn); mysql_close(conn);
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
void GenreRepository::saveRecord(const model::Genre& genre) void GenreRepository::saveRecord(const model::Genre& genre) {
{ std::cout << "inserting genre record\n";
std::cout << "inserting genre record" << std::endl;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
MYSQL_STMT *stmt = mysql_stmt_init(conn); MYSQL_STMT *stmt = mysql_stmt_init(conn);
@@ -187,13 +193,12 @@ void GenreRepository::saveRecord(const model::Genre& genre)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "inserted record" << std::endl; std::cout << "inserted record\n";
} }
void GenreRepository::deleteRecord(const model::Genre& genre, type::GenreFilter filter = type::GenreFilter::id) void GenreRepository::deleteRecord(const model::Genre& genre,
{ type::GenreFilter filter = type::GenreFilter::id) {
// TODO: implement this std::cout << "deleting genre record\n";
std::cout << "deleting genre record" << std::endl;
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -225,138 +230,126 @@ void GenreRepository::deleteRecord(const model::Genre& genre, type::GenreFilter
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "deleted genre record" << std::endl; std::cout << "deleted genre record\n";
} }
std::vector<model::Genre> GenreRepository::parseRecords(MYSQL_STMT *stmt) std::vector<model::Genre> GenreRepository::parseRecords(MYSQL_STMT *stmt) {
{
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
std::vector<model::Genre> genres; std::vector<model::Genre> genres;
genres.reserve(mysql_stmt_num_rows(stmt)); genres.reserve(mysql_stmt_num_rows(stmt));
if (mysql_stmt_field_count(stmt) == 0) { constexpr auto valAmt = 2;
std::cout << "field count is 0" << std::endl;
return genres;
}
model::Genre gnr; for (auto status = 0; status == 0; status = mysql_stmt_next_result(stmt)) {
const auto valAmt = 2; if (mysql_stmt_field_count(stmt) > 0) {
unsigned long len[valAmt]; model::Genre genre;
my_bool nullRes[valAmt]; auto metaBuff = metadataBuffer();
auto bindedValues = valueBind(genre, metaBuff);
status = mysql_stmt_bind_result(stmt, bindedValues.get());
auto res = mysql_stmt_result_metadata(stmt); std::cout << "fetching statement result\n";
auto fields = mysql_fetch_fields(res);
const auto strLen = 1024;
char category[strLen];
MYSQL_BIND val[valAmt];
memset(val, 0, sizeof(val));
val[0].buffer_type = MYSQL_TYPE_LONG;
val[0].buffer = (char*)&gnr.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_STRING;
val[1].buffer = (char*)category;
val[1].buffer_length = strLen;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
for (auto status = mysql_stmt_bind_result(stmt, val); status == 0;) {
std::cout << "fetching statement result" << std::endl;
status = mysql_stmt_fetch(stmt); status = mysql_stmt_fetch(stmt);
if (status == 0) { if (status == 1 || status == MYSQL_NO_DATA) break;
gnr.category = category;
genres.push_back(std::move(gnr)); genre.category = std::get<0>(metaBuff);
genres.push_back(genre);
} }
std::cout << "fetching statement result\n";
} }
return genres; return genres;
} }
std::pair<model::Genre, int> GenreRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) std::pair<model::Genre, int> GenreRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) {
{ std::cout << "parsing genre record with song count\n";
std::cout << "parsing genre record with song count" << std::endl;
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
const auto rowCount = mysql_stmt_num_rows(stmt);
const auto strLen = 1024;
const auto valAmt = 3;
unsigned long len[valAmt];
my_bool nullRes[valAmt];
model::Genre genre; model::Genre genre;
int songCount = 0; int songCount = 0;
if (mysql_stmt_num_rows(stmt) == 0) { auto metaBuff = metadataBuffer();
std::cout << "no results" << std::endl; auto val = valueBindWithSongCount(genre, metaBuff, songCount);
if (rowCount == 0) {
std::cout << "no results\n";
return std::make_pair(genre, songCount); return std::make_pair(genre, songCount);
} }
MYSQL_BIND val[valAmt]; auto status = mysql_stmt_bind_result(stmt, val.get());
std::memset(val, 0, sizeof(val)); status = mysql_stmt_fetch(stmt);
char category[strLen] ; genre.category = std::get<0>(metaBuff);
val[0].buffer_type = MYSQL_TYPE_LONG; std::cout << "parsed genre record with song count\n";
val[0].buffer = (char*)&genre.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_STRING;
val[1].buffer = (char*)category;
val[1].buffer_length = strLen;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
val[2].buffer_type = MYSQL_TYPE_LONG;
val[2].buffer = (char*)&songCount;
val[2].length = &len[2];
val[2].is_null = &nullRes[2];
mysql_stmt_bind_result(stmt, val);
mysql_stmt_fetch(stmt);
genre.category = std::move(category);
std::cout << "parsed genre record with song count" << std::endl;
return std::make_pair(genre, songCount); return std::make_pair(genre, songCount);
}
model::Genre GenreRepository::parseRecord(MYSQL_RES* results)
{
std::cout << "parsing genre record" << std::endl;
model::Genre genre;
auto fieldNum = mysql_num_fields(results);
auto row = mysql_fetch_row(results);
for (auto i =0; i != fieldNum; ++i) {
const std::string field(mysql_fetch_field(results)->name);
if (field.compare("GenreId") == 0) {
genre.id = std::stoi(row[i]);
}
if (field.compare("Category") == 0) {
genre.category = row[i];
}
} }
std::cout << "parsed genre record" << std::endl;
return genre; std::shared_ptr<MYSQL_BIND> GenreRepository::valueBind(model::Genre& genre,
} std::tuple<char*>& metadata) {
model::Genre GenreRepository::parseRecord(MYSQL_STMT *stmt) constexpr auto valueCount = 2;
{ constexpr auto wordLen = 1024;
// TODO: implement this std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = reinterpret_cast<char*>(&genre.id);
values.get()[1].buffer_type = MYSQL_TYPE_STRING;
values.get()[1].buffer = reinterpret_cast<char*>(std::get<0>(metadata));
values.get()[1].buffer_length = wordLen;
return values;
}
std::shared_ptr<MYSQL_BIND> GenreRepository::valueBindWithSongCount(model::Genre& genre,
std::tuple<char*>& metadata, int& songCount) {
constexpr auto valueCount = 3;
constexpr auto wordLen = 1024;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = reinterpret_cast<char*>(&genre.id);
values.get()[1].buffer_type = MYSQL_TYPE_STRING;
values.get()[1].buffer = reinterpret_cast<char*>(std::get<0>(metadata));
values.get()[1].buffer_length = wordLen;
values.get()[2].buffer_type = MYSQL_TYPE_LONG;
values.get()[2].buffer = reinterpret_cast<char*>(&songCount);
return values;
}
std::tuple<char*> GenreRepository::metadataBuffer() {
constexpr auto wordLen = 1024;
char category[wordLen];
return std::make_tuple(category);
}
model::Genre GenreRepository::parseRecord(MYSQL_STMT *stmt) {
std::cout << "parsing genre record\n";
mysql_stmt_store_result(stmt);
model::Genre genre; model::Genre genre;
auto metaBuff = metadataBuffer();
auto bindedValues = valueBind(genre, metaBuff);
auto status = mysql_stmt_bind_result(stmt, bindedValues.get());
status = mysql_stmt_fetch(stmt);
genre.category = std::get<0>(metaBuff);
std::cout << "done parsing genre record\n";
return genre; return genre;
} }
} }
+36 -49
View File
@@ -8,13 +8,10 @@
#include "type/SongFilter.h" #include "type/SongFilter.h"
namespace database { namespace database {
SongRepository::SongRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { }
SongRepository::SongRepository(const model::BinaryPath& bConf) : BaseRepository(bConf)
{ }
std::vector<model::Song> SongRepository::retrieveRecords() std::vector<model::Song> SongRepository::retrieveRecords() {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
std::stringstream qry; std::stringstream qry;
@@ -31,11 +28,10 @@ std::vector<model::Song> SongRepository::retrieveRecords()
mysql_close(conn); mysql_close(conn);
return songs; return songs;
} }
model::Song SongRepository::retrieveRecord(const model::Song& song, type::SongFilter filter) model::Song SongRepository::retrieveRecord(const model::Song& song, type::SongFilter filter) {
{
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -101,22 +97,20 @@ model::Song SongRepository::retrieveRecord(const model::Song& song, type::SongFi
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
//song = parseRecord(stmt);
auto retrievedSong = parseRecord(stmt); auto retrievedSong = parseRecord(stmt);
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "done" << std::endl; std::cout << "done\n";
return retrievedSong; return retrievedSong;
} }
bool SongRepository::doesSongExist(const model::Song& song, type::SongFilter filter) bool SongRepository::doesSongExist(const model::Song& song, type::SongFilter filter) {
{ std::cout << "checking to see if song exists\n";
std::cout << "checking to see if song exists" << std::endl;
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -178,20 +172,19 @@ bool SongRepository::doesSongExist(const model::Song& song, type::SongFilter fil
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
::mysql_stmt_store_result(stmt); ::mysql_stmt_store_result(stmt);
auto rowCount = ::mysql_stmt_num_rows(stmt); auto rowCount = ::mysql_stmt_num_rows(stmt);
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "done" << std::endl; std::cout << "done\n";
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
bool SongRepository::deleteRecord(const model::Song& song) bool SongRepository::deleteRecord(const model::Song& song) {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto status = 0; auto status = 0;
@@ -202,11 +195,10 @@ bool SongRepository::deleteRecord(const model::Song& song)
mysql_close(conn); mysql_close(conn);
return (result == 0) ? true : false; return (result == 0) ? true : false;
} }
void SongRepository::saveRecord(const model::Song& song) void SongRepository::saveRecord(const model::Song& song) {
{ std::cout << "beginning to insert song record\n";
std::cout << "beginning to insert song record" << std::endl;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto status = 0; auto status = 0;
@@ -302,12 +294,11 @@ void SongRepository::saveRecord(const model::Song& song)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "done inserting song record" << std::endl; std::cout << "done inserting song record\n";
} }
void SongRepository::updateRecord(const model::Song& song) void SongRepository::updateRecord(const model::Song& song) {
{ std::cout << "executing query to update record\n";
std::cout << "executing query to update record" << std::endl;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -393,13 +384,12 @@ void SongRepository::updateRecord(const model::Song& song)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "updated song record" << std::endl; std::cout << "updated song record\n";
} }
std::shared_ptr<MYSQL_BIND> SongRepository::valueBind(model::Song& song, std::shared_ptr<MYSQL_BIND> SongRepository::valueBind(model::Song& song,
std::tuple<char*, char*, char*, char*, char*, char*>& metadata) std::tuple<char*, char*, char*, char*, char*, char*>& metadata) {
{
constexpr auto strLen = 1024; constexpr auto strLen = 1024;
constexpr auto valueCount = 16; constexpr auto valueCount = 16;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(valueCount, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(valueCount, sizeof(MYSQL_BIND)));
@@ -462,11 +452,10 @@ std::shared_ptr<MYSQL_BIND> SongRepository::valueBind(model::Song& song,
values.get()[15].buffer_length = strLen; values.get()[15].buffer_length = strLen;
return values; return values;
} }
std::tuple<char*, char*, char*, char*, char*, char*> SongRepository::metadataBuffer() std::tuple<char*, char*, char*, char*, char*, char*> SongRepository::metadataBuffer() {
{
constexpr auto length = 1024; constexpr auto length = 1024;
char title[length]; char title[length];
char artist[length]; char artist[length];
@@ -476,14 +465,13 @@ std::tuple<char*, char*, char*, char*, char*, char*> SongRepository::metadataBuf
char albumArtist[length]; char albumArtist[length];
return std::make_tuple(title, artist, album, genre, path, albumArtist); return std::make_tuple(title, artist, album, genre, path, albumArtist);
} }
std::vector<model::Song> SongRepository::parseRecords(MYSQL_STMT *stmt) std::vector<model::Song> SongRepository::parseRecords(MYSQL_STMT *stmt) {
{
::mysql_stmt_store_result(stmt); ::mysql_stmt_store_result(stmt);
auto c = ::mysql_stmt_num_rows(stmt); auto c = ::mysql_stmt_num_rows(stmt);
std::cout << "number of results " << c << std::endl; std::cout << "number of results " << c << "\n";
std::vector<model::Song> songs; std::vector<model::Song> songs;
songs.reserve(c); songs.reserve(c);
@@ -499,7 +487,7 @@ std::vector<model::Song> SongRepository::parseRecords(MYSQL_STMT *stmt)
status = ::mysql_stmt_bind_result(stmt, val.get()); status = ::mysql_stmt_bind_result(stmt, val.get());
while (1) { while (1) {
std::cout << "fetching statement result" << std::endl; std::cout << "fetching statement result\n";
status = ::mysql_stmt_fetch(stmt); status = ::mysql_stmt_fetch(stmt);
if (status == 1 || status == MYSQL_NO_DATA) { if (status == 1 || status == MYSQL_NO_DATA) {
@@ -516,18 +504,17 @@ std::vector<model::Song> SongRepository::parseRecords(MYSQL_STMT *stmt)
songs.push_back(song); songs.push_back(song);
} }
} }
std::cout << "fetching next result" << std::endl; std::cout << "fetching next result\n";
status = ::mysql_stmt_next_result(stmt); status = ::mysql_stmt_next_result(stmt);
} }
return songs; return songs;
} }
model::Song SongRepository::parseRecord(MYSQL_STMT *stmt) model::Song SongRepository::parseRecord(MYSQL_STMT *stmt) {
{
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
std::cout << "amount of rows: " << mysql_stmt_num_rows(stmt) << std::endl; std::cout << "amount of rows: " << mysql_stmt_num_rows(stmt) << "\n";
model::Song song; model::Song song;
auto metaBuff = metadataBuffer(); auto metaBuff = metadataBuffer();
auto bindedValues = valueBind(song, metaBuff); auto bindedValues = valueBind(song, metaBuff);
@@ -541,8 +528,8 @@ model::Song SongRepository::parseRecord(MYSQL_STMT *stmt)
song.songPath = std::get<4>(metaBuff); song.songPath = std::get<4>(metaBuff);
song.albumArtist = std::get<5>(metaBuff); song.albumArtist = std::get<5>(metaBuff);
std::cout << "done parsing record" << std::endl; std::cout << "done parsing record\n";
return song; return song;
} }
} }
+42 -51
View File
@@ -7,12 +7,11 @@
namespace database { namespace database {
UserRepository::UserRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { } UserRepository::UserRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { }
model::User UserRepository::retrieveUserRecord(model::User& user, model::User UserRepository::retrieveUserRecord(model::User& user,
type::UserFilter filter = type::UserFilter::username) type::UserFilter filter = type::UserFilter::username) {
{
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -58,10 +57,10 @@ model::User UserRepository::retrieveUserRecord(model::User& user,
mysql_close(conn); mysql_close(conn);
return user; return user;
} }
model::PassSec UserRepository::retrieverUserSaltRecord(model::PassSec& userSec, type::SaltFilter filter) model::PassSec UserRepository::retrieverUserSaltRecord(model::PassSec& userSec,
{ type::SaltFilter filter) {
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -97,11 +96,10 @@ model::PassSec UserRepository::retrieverUserSaltRecord(model::PassSec& userSec,
mysql_close(conn); mysql_close(conn);
return userSec; return userSec;
} }
bool UserRepository::doesUserRecordExist(const model::User& user, type::UserFilter filter) bool UserRepository::doesUserRecordExist(const model::User& user, type::UserFilter filter) {
{
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -139,10 +137,11 @@ bool UserRepository::doesUserRecordExist(const model::User& user, type::UserFilt
mysql_close(conn); mysql_close(conn);
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
void UserRepository::saveUserRecord(const model::User& user)
{
std::cout << "inserting user record" << std::endl; void UserRepository::saveUserRecord(const model::User& user) {
std::cout << "inserting user record\n";
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -151,7 +150,6 @@ void UserRepository::saveUserRecord(const model::User& user)
qry << "VALUES(?, ?, ?, ?, ?, ?)"; qry << "VALUES(?, ?, ?, ?, ?, ?)";
const auto query = qry.str(); const auto query = qry.str();
auto sizes = fetchUserLengths(user); auto sizes = fetchUserLengths(user);
auto params = insertUserValues(user, sizes); auto params = insertUserValues(user, sizes);
@@ -161,11 +159,11 @@ void UserRepository::saveUserRecord(const model::User& user)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
} }
void UserRepository::saveUserSalt(const model::PassSec& userSec) {
std::cout << "inserting user salt record\n";
void UserRepository::saveUserSalt(const model::PassSec& userSec)
{
std::cout << "inserting user salt record" << std::endl;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -183,12 +181,11 @@ void UserRepository::saveUserSalt(const model::PassSec& userSec)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
} }
std::shared_ptr<MYSQL_BIND> UserRepository::insertUserValues(const model::User& user, std::shared_ptr<MYSQL_BIND> UserRepository::insertUserValues(const model::User& user,
std::shared_ptr<UserRepository::UserLengths> lengths) std::shared_ptr<UserRepository::UserLengths> lengths) {
{
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(6, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(6, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_STRING; values.get()[0].buffer_type = MYSQL_TYPE_STRING;
@@ -222,11 +219,10 @@ std::shared_ptr<MYSQL_BIND> UserRepository::insertUserValues(const model::User&
values.get()[5].is_null = 0; values.get()[5].is_null = 0;
return values; return values;
} }
std::shared_ptr<MYSQL_BIND> UserRepository::insertSaltValues(const model::PassSec& passSec, std::shared_ptr<MYSQL_BIND> UserRepository::insertSaltValues(const model::PassSec& passSec,
std::shared_ptr<UserRepository::SaltLengths> lengths) std::shared_ptr<UserRepository::SaltLengths> lengths) {
{
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(6, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(6, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_STRING; values.get()[0].buffer_type = MYSQL_TYPE_STRING;
@@ -236,13 +232,11 @@ std::shared_ptr<MYSQL_BIND> UserRepository::insertSaltValues(const model::PassSe
values.get()[1].buffer_type = MYSQL_TYPE_LONG; values.get()[1].buffer_type = MYSQL_TYPE_LONG;
values.get()[1].buffer = (char*)&passSec.userId; values.get()[1].buffer = (char*)&passSec.userId;
return values; return values;
} }
std::shared_ptr<MYSQL_BIND> UserRepository::valueBind(model::User& user, std::shared_ptr<MYSQL_BIND> UserRepository::valueBind(model::User& user,
std::tuple<char*, char*, char*, char*, char*, char*>& us) std::tuple<char*, char*, char*, char*, char*, char*>& us) {
{
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(7, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(7, sizeof(MYSQL_BIND)));
constexpr auto strLen = 1024; constexpr auto strLen = 1024;
@@ -274,10 +268,10 @@ std::shared_ptr<MYSQL_BIND> UserRepository::valueBind(model::User& user,
values.get()[6].buffer_length = strLen; values.get()[6].buffer_length = strLen;
return values; return values;
} }
std::shared_ptr<MYSQL_BIND> UserRepository::saltValueBind(model::PassSec& userSalt, char *salt) std::shared_ptr<MYSQL_BIND> UserRepository::saltValueBind(model::PassSec& userSalt,
{ char *salt) {
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(3, sizeof(MYSQL_BIND))); std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*) std::calloc(3, sizeof(MYSQL_BIND)));
constexpr auto strLen = 1024; constexpr auto strLen = 1024;
@@ -292,10 +286,10 @@ std::shared_ptr<MYSQL_BIND> UserRepository::saltValueBind(model::PassSec& userSa
values.get()[2].buffer = (char*)&userSalt.userId; values.get()[2].buffer = (char*)&userSalt.userId;
return values; return values;
} }
std::shared_ptr<UserRepository::UserLengths> UserRepository::fetchUserLengths(const model::User& user) std::shared_ptr<UserRepository::UserLengths> UserRepository::fetchUserLengths(
{ const model::User& user) {
auto userLen = std::make_shared<UserLengths>(); auto userLen = std::make_shared<UserLengths>();
userLen->firstnameLength = user.firstname.size(); userLen->firstnameLength = user.firstname.size();
userLen->lastnameLength = user.lastname.size(); userLen->lastnameLength = user.lastname.size();
@@ -305,19 +299,18 @@ std::shared_ptr<UserRepository::UserLengths> UserRepository::fetchUserLengths(co
userLen->passwordLength = user.password.size(); userLen->passwordLength = user.password.size();
return userLen; return userLen;
} }
std::shared_ptr<UserRepository::SaltLengths> UserRepository::fetchSaltLengths(const model::PassSec& passSec) std::shared_ptr<UserRepository::SaltLengths> UserRepository::fetchSaltLengths(
{ const model::PassSec& passSec) {
auto saltLen = std::make_shared<SaltLengths>(); auto saltLen = std::make_shared<SaltLengths>();
saltLen->saltLength = passSec.salt.size(); saltLen->saltLength = passSec.salt.size();
return saltLen; return saltLen;
} }
std::tuple<char*, char*, char*, char*, char*, char*> UserRepository::fetchUV() std::tuple<char*, char*, char*, char*, char*, char*> UserRepository::fetchUV() {
{
char firstname[1024]; char firstname[1024];
char lastname[1024]; char lastname[1024];
char phone[1024]; char phone[1024];
@@ -326,11 +319,10 @@ std::tuple<char*, char*, char*, char*, char*, char*> UserRepository::fetchUV()
char password[1024]; char password[1024];
return std::make_tuple(firstname, lastname, phone, email, username, password); return std::make_tuple(firstname, lastname, phone, email, username, password);
} }
model::User UserRepository::parseRecord(MYSQL_STMT *stmt) model::User UserRepository::parseRecord(MYSQL_STMT *stmt) {
{
model::User user; model::User user;
auto usv = fetchUV(); auto usv = fetchUV();
@@ -346,10 +338,9 @@ model::User UserRepository::parseRecord(MYSQL_STMT *stmt)
user.password = std::get<5>(usv); user.password = std::get<5>(usv);
return user; return user;
} }
model::PassSec UserRepository::parseSaltRecord(MYSQL_STMT* stmt) model::PassSec UserRepository::parseSaltRecord(MYSQL_STMT* stmt) {
{
model::PassSec userSalt; model::PassSec userSalt;
char saltKey[1024]; char saltKey[1024];
@@ -360,5 +351,5 @@ model::PassSec UserRepository::parseSaltRecord(MYSQL_STMT* stmt)
userSalt.salt = saltKey; userSalt.salt = saltKey;
return userSalt; return userSalt;
} }
} }
+113 -112
View File
@@ -7,11 +7,10 @@
#include <cstring> #include <cstring>
namespace database { namespace database {
YearRepository::YearRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { } YearRepository::YearRepository(const model::BinaryPath& bConf) : BaseRepository(bConf) { }
std::vector<model::Year> YearRepository::retrieveRecords() std::vector<model::Year> YearRepository::retrieveRecords() {
{
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
const std::string query = "SELECT * FROM Year"; const std::string query = "SELECT * FROM Year";
@@ -25,11 +24,11 @@ std::vector<model::Year> YearRepository::retrieveRecords()
mysql_close(conn); mysql_close(conn);
return yearRecs; return yearRecs;
} }
std::pair<model::Year, int> YearRepository::retrieveRecordWithSongCount(model::Year& year, type::YearFilter filter = type::YearFilter::id) std::pair<model::Year, int> YearRepository::retrieveRecordWithSongCount(model::Year& year,
{ type::YearFilter filter) {
std::cout << "retrieving year record with song count" << std::endl; std::cout << "retrieving year record with song count\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -66,25 +65,37 @@ std::pair<model::Year, int> YearRepository::retrieveRecordWithSongCount(model::Y
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "retrieved year record with song count" << std::endl; std::cout << "retrieved year record with song count\n";
return yearWSC; return yearWSC;
} }
model::Year YearRepository::retrieveRecord(model::Year& year, type::YearFilter filter) model::Year YearRepository::retrieveRecord(model::Year& year, type::YearFilter filter) {
{ std::cout << "retrieving year record\n";
// TODO: switch to prepared statements
std::cout << "retrieving year record" << std::endl;
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn);
qry << "SELECT yr.* FROM Year yr WHERE "; qry << "SELECT yr.* FROM Year yr WHERE ";
MYSQL_BIND params[1];
std::memset(params, 0, sizeof(0));
switch (filter) { switch (filter) {
case type::YearFilter::id: case type::YearFilter::id:
qry << "yr.YearId = " << year.id; qry << "yr.YearId = ?";
params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = reinterpret_cast<char*>(&year.id);
params[0].length = 0;
params[0].is_null = 0;
break; break;
case type::YearFilter::year: case type::YearFilter::year:
qry << "yr.Year = " << year.year; qry << "yr.Year = ?";
params[0].buffer_type = MYSQL_TYPE_LONG;
params[0].buffer = reinterpret_cast<char*>(&year.year);
params[0].length = 0;
params[0].is_null = 0;
break; break;
default: default:
break; break;
@@ -93,19 +104,23 @@ model::Year YearRepository::retrieveRecord(model::Year& year, type::YearFilter f
qry << " ORDER BY yr.YearId DESC LIMIT 1"; qry << " ORDER BY yr.YearId DESC LIMIT 1";
const auto query = qry.str(); const auto query = qry.str();
auto results = performMysqlQuery(conn, query);
year = parseRecord(results); auto status = mysql_stmt_prepare(stmt, query.c_str(), query.size());
status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt);
year = parseRecord(stmt);
mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "retrieved record" << std::endl; std::cout << "retrieved record\n";
return year; return year;
} }
bool YearRepository::doesYearExist(const model::Year& year, type::YearFilter filter)
{ bool YearRepository::doesYearExist(const model::Year& year, type::YearFilter filter) {
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -143,7 +158,7 @@ bool YearRepository::doesYearExist(const model::Year& year, type::YearFilter fil
status = mysql_stmt_bind_param(stmt, params); status = mysql_stmt_bind_param(stmt, params);
status = mysql_stmt_execute(stmt); status = mysql_stmt_execute(stmt);
std::cout << "the query has been performed" << std::endl; std::cout << "the query has been performed\n";
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
auto rowCount = mysql_stmt_num_rows(stmt); auto rowCount = mysql_stmt_num_rows(stmt);
@@ -152,11 +167,11 @@ bool YearRepository::doesYearExist(const model::Year& year, type::YearFilter fil
mysql_close(conn); mysql_close(conn);
return (rowCount > 0) ? true : false; return (rowCount > 0) ? true : false;
} }
void YearRepository::saveRecord(const model::Year& year)
{ void YearRepository::saveRecord(const model::Year& year) {
std::cout << "saving year record" << std::endl; std::cout << "saving year record\n";
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
MYSQL_STMT *stmt = mysql_stmt_init(conn); MYSQL_STMT *stmt = mysql_stmt_init(conn);
@@ -179,12 +194,12 @@ void YearRepository::saveRecord(const model::Year& year)
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "saved record" << std::endl; std::cout << "saved record\n";
} }
void YearRepository::deleteYear(const model::Year& year, type::YearFilter filter = type::YearFilter::id) void YearRepository::deleteYear(const model::Year& year,
{ type::YearFilter filter) {
std::cout << "deleting year record" << std::endl; std::cout << "deleting year record\n";
std::stringstream qry; std::stringstream qry;
auto conn = setupMysqlConnection(); auto conn = setupMysqlConnection();
auto stmt = mysql_stmt_init(conn); auto stmt = mysql_stmt_init(conn);
@@ -216,126 +231,112 @@ void YearRepository::deleteYear(const model::Year& year, type::YearFilter filter
mysql_stmt_close(stmt); mysql_stmt_close(stmt);
mysql_close(conn); mysql_close(conn);
std::cout << "deleted year record" << std::endl; std::cout << "deleted year record\n";
} }
std::vector<model::Year> YearRepository::parseRecords(MYSQL_STMT *stmt)
{ std::vector<model::Year> YearRepository::parseRecords(MYSQL_STMT *stmt) {
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
const auto rowCount = mysql_stmt_num_rows(stmt);
std::vector<model::Year> yearRecs; std::vector<model::Year> yearRecs;
yearRecs.reserve(mysql_stmt_num_rows(stmt)); yearRecs.reserve(rowCount);
if (mysql_stmt_field_count(stmt) == 0) { if (mysql_stmt_field_count(stmt) == 0) {
std::cout << "field count is 0" << std::endl; std::cout << "field count is 0\n";
return yearRecs; return yearRecs;
} }
model::Year yearRec;
const auto valAmt = 2; const auto valAmt = 2;
unsigned long len[valAmt]; unsigned long len[valAmt];
my_bool nullRes[valAmt]; my_bool nullRes[valAmt];
auto res = mysql_stmt_result_metadata(stmt); for (auto status = 0; status == 0; status = mysql_stmt_next_result(stmt)) {
if (mysql_stmt_field_count(stmt) > 0) {
model::Year yearRec;
MYSQL_BIND val[valAmt]; std::cout << "fetching statement result\n";
memset(val, 0, sizeof(val)); auto bindedValues = valueBind(yearRec);
status = mysql_stmt_bind_result(stmt, bindedValues.get());
val[0].buffer_type = MYSQL_TYPE_LONG;
val[0].buffer = (char*)&yearRec.id;
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_LONG;
val[1].buffer = (char*)&yearRec.year;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
for (auto status = mysql_stmt_bind_result(stmt, val); status == 0;) {
std::cout << "fetching statement result" << std::endl;
status = mysql_stmt_fetch(stmt); status = mysql_stmt_fetch(stmt);
if (status == 0) { if (status == 1 || status == MYSQL_NO_DATA) break;
yearRecs.push_back(std::move(yearRec));
yearRecs.push_back(yearRec);
} }
std::cout << "fetching next result\n";
} }
return yearRecs; return yearRecs;
} }
std::pair<model::Year, int> YearRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) std::pair<model::Year, int> YearRepository::parseRecordWithSongCount(MYSQL_STMT *stmt) {
{ std::cout << "parsing year record\n";
std::cout << "parsing year record" << std::endl;
mysql_stmt_store_result(stmt); mysql_stmt_store_result(stmt);
constexpr auto valAmt = 3;
unsigned long len[valAmt];
my_bool nullRes[valAmt];
model::Year year; model::Year year;
int songCount = 0; int songCount = 0;
if (mysql_stmt_num_rows(stmt) == 0) { if (mysql_stmt_num_rows(stmt) == 0) {
std::cout << "no results" << std::endl; std::cout << "no results\n";
return std::make_pair(year, songCount); return std::make_pair(year, songCount);
} }
MYSQL_BIND val[valAmt]; auto val = valueBindWithSongCount(year, songCount);
std::memset(val, 0, sizeof(val));
val[0].buffer_type = MYSQL_TYPE_LONG; auto status = mysql_stmt_bind_result(stmt, val.get());
val[0].buffer = (char*)&year.id; status = mysql_stmt_fetch(stmt);
val[0].length = &len[0];
val[0].is_null = &nullRes[0];
val[1].buffer_type = MYSQL_TYPE_LONG; std::cout << "parsed year record from the database\n";
val[1].buffer = (char*)&year.year;
val[1].length = &len[1];
val[1].is_null = &nullRes[1];
val[2].buffer_type = MYSQL_TYPE_LONG;
val[2].buffer = (char*)&songCount;
val[2].length = &len[2];
val[2].is_null = &nullRes[2];
mysql_stmt_bind_result(stmt, val);
mysql_stmt_fetch(stmt);
std::cout << "parsed year record from the database" << std::endl;
return std::make_pair(year, songCount); return std::make_pair(year, songCount);
}
model::Year YearRepository::parseRecord(MYSQL_RES *results)
{
std::cout << "parsing year record" << std::endl;
model::Year year;
auto fieldNum = mysql_num_fields(results);
auto row = mysql_fetch_row(results);
for (auto i = 0; i != fieldNum; ++i) {
const std::string field(mysql_fetch_field(results)->name);
if (field.compare("YearId") == 0) {
year.id= std::stoi(row[i]);
}
if (field.compare("Year") == 0) {
year.year = std::stoi(row[i]);
}
} }
std::cout << "parse year record" << std::endl;
return year; std::shared_ptr<MYSQL_BIND> YearRepository::valueBind(model::Year& year) {
} constexpr auto valueCount = 2;
model::Year YearRepository::parseRecord(MYSQL_STMT *stmt) std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
{ std::calloc(valueCount, sizeof(MYSQL_BIND)));
// TODO: imeplement this
// I really thought that I had already done this values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = reinterpret_cast<char*>(&year.id);
values.get()[1].buffer_type = MYSQL_TYPE_LONG;
values.get()[1].buffer = reinterpret_cast<char*>(&year.year);
return values;
}
std::shared_ptr<MYSQL_BIND> YearRepository::valueBindWithSongCount(model::Year& year,
int& songCount) {
constexpr auto valueCount = 3;
std::shared_ptr<MYSQL_BIND> values((MYSQL_BIND*)
std::calloc(valueCount, sizeof(MYSQL_BIND)));
values.get()[0].buffer_type = MYSQL_TYPE_LONG;
values.get()[0].buffer = reinterpret_cast<char*>(&year.id);
values.get()[1].buffer_type = MYSQL_TYPE_LONG;
values.get()[1].buffer = reinterpret_cast<char*>(&year.year);
values.get()[2].buffer_type = MYSQL_TYPE_LONG;
values.get()[2].buffer = reinterpret_cast<char*>(&songCount);
return values;
}
model::Year YearRepository::parseRecord(MYSQL_STMT *stmt) {
std::cout << "parsing year record\n";
mysql_stmt_store_result(stmt);
model::Year year; model::Year year;
auto bindedValues = valueBind(year);
auto status = mysql_stmt_bind_result(stmt, bindedValues.get());
status = mysql_stmt_fetch(stmt);
std::cout << "done parsing year record\n";
return year; return year;
} }
} }
+23 -29
View File
@@ -7,19 +7,17 @@
#include "type/AlbumFilter.h" #include "type/AlbumFilter.h"
namespace manager { namespace manager {
AlbumManager::AlbumManager(const model::BinaryPath& bConf) : m_bConf(bConf) { } AlbumManager::AlbumManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
model::Album AlbumManager::retrieveAlbum(model::Album& album) model::Album AlbumManager::retrieveAlbum(model::Album& album) {
{
database::AlbumRepository albRepo(m_bConf); database::AlbumRepository albRepo(m_bConf);
album = std::move(albRepo.retrieveRecord(album, type::AlbumFilter::title)); album = std::move(albRepo.retrieveRecord(album, type::AlbumFilter::title));
return album; return album;
} }
model::Album AlbumManager::saveAlbum(const model::Song& song) model::Album AlbumManager::saveAlbum(const model::Song& song) {
{
model::Album album(song); model::Album album(song);
database::AlbumRepository albRepo(m_bConf); database::AlbumRepository albRepo(m_bConf);
@@ -27,52 +25,48 @@ model::Album AlbumManager::saveAlbum(const model::Song& song)
if (!albRepo.doesAlbumExists(album, type::AlbumFilter::title)) { if (!albRepo.doesAlbumExists(album, type::AlbumFilter::title)) {
albRepo.saveAlbum(album); albRepo.saveAlbum(album);
} else { } else {
std::cout << "album record already exists in the database" << std::endl; std::cout << "album record already exists in the database\n";
}
return album;
} }
return album; void AlbumManager::deleteAlbum(const model::Song& song) {
}
void AlbumManager::deleteAlbum(const model::Song& song)
{
model::Album album(song); model::Album album(song);
database::AlbumRepository albRepo(m_bConf); database::AlbumRepository albRepo(m_bConf);
auto albWSC = albRepo.retrieveRecordWithSongCount(album, type::AlbumFilter::id); auto albWSC = albRepo.retrieveRecordWithSongCount(album, type::AlbumFilter::id);
if (albWSC.second > 1) { if (albWSC.second > 1) {
std::cout << "album still contain songs related to it, will not delete" << std::endl; std::cout << "album still contain songs related to it, will not delete\n";
return; return;
} }
std::cout << "safe to delete the album record" << std::endl; std::cout << "safe to delete the album record\n";
albRepo.deleteAlbum(album, type::AlbumFilter::id); albRepo.deleteAlbum(album, type::AlbumFilter::id);
} }
void AlbumManager::updateAlbum(model::Song& updatedSong, void AlbumManager::updateAlbum(model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
model::Album album(updatedSong); model::Album album(updatedSong);
database::AlbumRepository albRepo(m_bConf); database::AlbumRepository albRepo(m_bConf);
if (!albRepo.doesAlbumExists(album, type::AlbumFilter::title)) { if (!albRepo.doesAlbumExists(album, type::AlbumFilter::title)) {
std::cout << "album record does not exist" << std::endl; std::cout << "album record does not exist\n";
albRepo.saveAlbum(album); albRepo.saveAlbum(album);
} else { } else {
std::cout << "album record already exists" << std::endl; std::cout << "album record already exists\n";
} }
album = albRepo.retrieveRecord(album, type::AlbumFilter::title); album = albRepo.retrieveRecord(album, type::AlbumFilter::title);
updatedSong.albumId = album.id; updatedSong.albumId = album.id;
} }
void AlbumManager::printAlbum(const model::Album& album) void AlbumManager::printAlbum(const model::Album& album) {
{ std::cout << "\nalbum record\n";
std::cout << "\nalbum record" << std::endl; std::cout << "id: " << album.id << "\n";
std::cout << "id: " << album.id << std::endl; std::cout << "title: " << album.title << "\n";
std::cout << "title: " << album.title << std::endl; std::cout << "year: " << album.year << "\n";
std::cout << "year: " << album.year << std::endl; }
}
} }
+23 -28
View File
@@ -7,22 +7,20 @@
namespace manager { namespace manager {
ArtistManager::ArtistManager(const model::BinaryPath& bConf) : m_bConf(bConf) { } ArtistManager::ArtistManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
model::Artist ArtistManager::retrieveArtist(model::Artist& artist) model::Artist ArtistManager::retrieveArtist(model::Artist& artist) {
{ std::cout << "retrieving artist record\n";
std::cout << "retrieving artist record" << std::endl;
database::ArtistRepository artRepo(m_bConf); database::ArtistRepository artRepo(m_bConf);
std::cout << "initialized artist repo" << std::endl; std::cout << "initialized artist repo\n";
std::cout << artist.artist << std::endl; std::cout << artist.artist << "\n";
artist = artRepo.retrieveRecord(artist, type::ArtistFilter::artist); artist = artRepo.retrieveRecord(artist, type::ArtistFilter::artist);
return artist; return artist;
} }
model::Artist ArtistManager::saveArtist(const model::Song& song) model::Artist ArtistManager::saveArtist(const model::Song& song) {
{
model::Artist artist; model::Artist artist;
artist.artist = song.artist; artist.artist = song.artist;
@@ -30,15 +28,14 @@ model::Artist ArtistManager::saveArtist(const model::Song& song)
if (!artRepo.doesArtistExist(artist, type::ArtistFilter::artist)) { if (!artRepo.doesArtistExist(artist, type::ArtistFilter::artist)) {
artRepo.saveRecord(artist); artRepo.saveRecord(artist);
} else { } else {
std::cout << "artist already exists" << std::endl; std::cout << "artist already exists\n";
} }
return artist; return artist;
} }
void ArtistManager::deleteArtist(const model::Song& song) void ArtistManager::deleteArtist(const model::Song& song) {
{
model::Artist artist(song); model::Artist artist(song);
database::ArtistRepository artRepo(m_bConf); database::ArtistRepository artRepo(m_bConf);
@@ -46,36 +43,34 @@ void ArtistManager::deleteArtist(const model::Song& song)
if (artWSC.second > 1) { if (artWSC.second > 1) {
std::cout << "artist still contain songs related to it"; std::cout << "artist still contain songs related to it";
std::cout << ", not delete" << std::endl; std::cout << ", not delete\n";
return; return;
} }
std::cout << "safe to delete the artist record" << std::endl; std::cout << "safe to delete the artist record\n";
artRepo.deleteArtist(artist, type::ArtistFilter::id); artRepo.deleteArtist(artist, type::ArtistFilter::id);
} }
void ArtistManager::updateArtist(model::Song& updatedSong, void ArtistManager::updateArtist(model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
model::Artist artist; model::Artist artist;
artist.artist = updatedSong.artist; artist.artist = updatedSong.artist;
database::ArtistRepository artRepo(m_bConf); database::ArtistRepository artRepo(m_bConf);
if (!artRepo.doesArtistExist(artist, type::ArtistFilter::artist)) { if (!artRepo.doesArtistExist(artist, type::ArtistFilter::artist)) {
std::cout << "artist record does not exist" << std::endl; std::cout << "artist record does not exist\n";
artRepo.saveRecord(artist); artRepo.saveRecord(artist);
} else { } else {
std::cout << "artist record already exists" << std::endl; std::cout << "artist record already exists\n";
} }
artist = artRepo.retrieveRecord(artist, type::ArtistFilter::artist); artist = artRepo.retrieveRecord(artist, type::ArtistFilter::artist);
updatedSong.artistId = artist.id; updatedSong.artistId = artist.id;
} }
void ArtistManager::printArtist(const model::Artist& artist) void ArtistManager::printArtist(const model::Artist& artist) {
{ std::cout << "\nartist record" << "\n";
std::cout << "\nartist record" << std::endl; std::cout << "id: " << artist.id << "\n";
std::cout << "id: " << artist.id << std::endl; std::cout << "artist: " << artist.artist << "\n";
std::cout << "artist: " << artist.artist << std::endl; }
}
} }
+19 -24
View File
@@ -12,11 +12,10 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace manager { namespace manager {
CoverArtManager::CoverArtManager(const model::BinaryPath& bConf) : m_bConf(bConf) { } CoverArtManager::CoverArtManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
model::Cover CoverArtManager::saveCover(const model::Song& song) model::Cover CoverArtManager::saveCover(const model::Song& song) {
{
auto pathConfigContent = DirectoryManager::pathConfigContent(m_bConf); auto pathConfigContent = DirectoryManager::pathConfigContent(m_bConf);
auto stockCoverPath = DirectoryManager::configPath(m_bConf); auto stockCoverPath = DirectoryManager::configPath(m_bConf);
stockCoverPath.append("/CoverArt.png"); stockCoverPath.append("/CoverArt.png");
@@ -35,20 +34,20 @@ model::Cover CoverArtManager::saveCover(const model::Song& song)
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
if (!covRepo.doesCoverArtExist(cov, type::CoverFilter::songTitle)) { if (!covRepo.doesCoverArtExist(cov, type::CoverFilter::songTitle)) {
std::cout << "saving image record to the database" << std::endl; std::cout << "saving image record to the database\n";
covRepo.saveRecord(cov); covRepo.saveRecord(cov);
} else { } else {
std::cout << "cover art record already exists" << std::endl; std::cout << "cover art record already exists\n";
} }
std::cout << "retrieving image record from database" << std::endl; std::cout << "retrieving image record from database\n";
cov = covRepo.retrieveRecord(cov, type::CoverFilter::songTitle); cov = covRepo.retrieveRecord(cov, type::CoverFilter::songTitle);
return cov; return cov;
} }
std::pair<bool, std::string> CoverArtManager::defaultCover( std::pair<bool, std::string> CoverArtManager::defaultCover(
const model::Cover& cover) { const model::Cover& cover) {
auto paths = DirectoryManager::pathConfigContent(m_bConf); auto paths = DirectoryManager::pathConfigContent(m_bConf);
@@ -64,11 +63,10 @@ std::pair<bool, std::string> CoverArtManager::defaultCover(
} else { } else {
return std::make_pair(false, coverArtPath); return std::make_pair(false, coverArtPath);
} }
} }
void CoverArtManager::deleteCover(const model::Song& song) void CoverArtManager::deleteCover(const model::Song& song) {
{
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
model::Cover cov(song.coverArtId); model::Cover cov(song.coverArtId);
@@ -79,19 +77,18 @@ void CoverArtManager::deleteCover(const model::Song& song)
auto result = defaultCover(cov); auto result = defaultCover(cov);
if (!result.first) { if (!result.first) {
fs::remove(cov.imagePath); fs::remove(cov.imagePath);
std::cout << "deleting cover art" << std::endl; std::cout << "deleting cover art\n";
const auto coverArtPath = result.second; const auto coverArtPath = result.second;
} else { } else {
std::cout << "song contains the stock cover art, will not delete" << std::endl; std::cout << "song contains the stock cover art, will not delete\n";
return; return;
} }
DirectoryManager::deleteDirectories(song, result.second); DirectoryManager::deleteDirectories(song, result.second);
} }
void CoverArtManager::updateCover(const model::Song& updatedSong, void CoverArtManager::updateCover(const model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
model::Cover cover(updatedSong.coverArtId); model::Cover cover(updatedSong.coverArtId);
cover = covRepo.retrieveRecord(cover, type::CoverFilter::id); cover = covRepo.retrieveRecord(cover, type::CoverFilter::id);
@@ -108,20 +105,18 @@ void CoverArtManager::updateCover(const model::Song& updatedSong,
fs::remove(cover.imagePath); fs::remove(cover.imagePath);
DirectoryManager::deleteDirectories(currSong, result.second); DirectoryManager::deleteDirectories(currSong, result.second);
} }
void CoverArtManager::updateCoverRecord(const model::Song& updatedSong) void CoverArtManager::updateCoverRecord(const model::Song& updatedSong) {
{
model::Cover updatedCover(updatedSong); model::Cover updatedCover(updatedSong);
auto updatedImagePath = createImagePath(updatedSong); auto updatedImagePath = createImagePath(updatedSong);
database::CoverArtRepository covRepo(m_bConf); database::CoverArtRepository covRepo(m_bConf);
covRepo.updateRecord(updatedCover); covRepo.updateRecord(updatedCover);
} }
std::string CoverArtManager::createImagePath(const model::Song& song) std::string CoverArtManager::createImagePath(const model::Song& song) {
{
auto imagePath = DirectoryManager::createDirectoryProcess( auto imagePath = DirectoryManager::createDirectoryProcess(
song, m_bConf, type::PathType::coverArt); song, m_bConf, type::PathType::coverArt);
@@ -136,5 +131,5 @@ std::string CoverArtManager::createImagePath(const model::Song& song)
imagePath.append(".png"); imagePath.append(".png");
return imagePath; return imagePath;
} }
} }
+48 -60
View File
@@ -8,91 +8,86 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace manager { namespace manager {
std::string DirectoryManager::createDirectoryProcess(model::Song song, const std::string& rootPath) std::string DirectoryManager::createDirectoryProcess(model::Song song,
{ const std::string& rootPath) {
auto currPath = fs::path(rootPath); auto currPath = fs::path(rootPath);
if (fs::exists(currPath)) { if (fs::exists(currPath)) {
std::cout << "path exists" << std::endl; std::cout << "path exists\n";
} else { } else {
std::cout << "creating path" << std::endl; std::cout << "creating path\n";
fs::create_directory(currPath); fs::create_directory(currPath);
} }
auto artPath = fs::path(currPath.string() + song.artist); auto artPath = fs::path(currPath.string() + song.artist);
if (fs::exists(artPath)) { if (fs::exists(artPath)) {
std::cout << "artist path exists" << std::endl; std::cout << "artist path exists\n";
} else { } else {
std::cout << "creating artist path" << std::endl; std::cout << "creating artist path\n";
fs::create_directory(artPath); fs::create_directory(artPath);
} }
auto albPath = fs::path(artPath.string() + "/" + song.album); auto albPath = fs::path(artPath.string() + "/" + song.album);
if (fs::exists(albPath)) { if (fs::exists(albPath)) {
std::cout << "album path exists" << std::endl; std::cout << "album path exists\n";
} else { } else {
std::cout << "creating album path" << std::endl; std::cout << "creating album path\n";
fs::create_directory(albPath); fs::create_directory(albPath);
} }
return albPath.string() + "/"; return albPath.string() + "/";
} }
std::string DirectoryManager::createDirectoryProcess(const model::Song& song, std::string DirectoryManager::createDirectoryProcess(const model::Song& song,
const model::BinaryPath& bConf, type::PathType pType) const model::BinaryPath& bConf, type::PathType pType) {
{
auto path = pathConfigContent(bConf)[retrievePathType(pType)]; auto path = pathConfigContent(bConf)[retrievePathType(pType)];
auto rootPath = path.get<std::string>(); auto rootPath = path.get<std::string>();
auto currPath = fs::path(rootPath); auto currPath = fs::path(rootPath);
if (fs::exists(currPath)) { if (fs::exists(currPath)) {
std::cout << "path exists" << std::endl; std::cout << "path exists\n";
} else { } else {
std::cout << "creating root music path" << std::endl; std::cout << "creating root music path\n";
fs::create_directory(currPath); fs::create_directory(currPath);
} }
auto artPath = fs::path(currPath.string() + song.albumArtist); auto artPath = fs::path(currPath.string() + song.albumArtist);
if (fs::exists(artPath)) { if (fs::exists(artPath)) {
std::cout << "artist path exists" << std::endl; std::cout << "artist path exists\n";
} else { } else {
std::cout << "creating artist path" << std::endl; std::cout << "creating artist path\n";
fs::create_directory(artPath); fs::create_directory(artPath);
} }
auto albPath = fs::path(artPath.string() + "/" + song.album); auto albPath = fs::path(artPath.string() + "/" + song.album);
if (fs::exists(albPath)) { if (fs::exists(albPath)) {
std::cout << "album path exists" << std::endl; std::cout << "album path exists\n";
} else { } else {
std::cout << "creating album path" << std::endl; std::cout << "creating album path\n";
fs::create_directory(albPath); fs::create_directory(albPath);
} }
return albPath.string() + "/"; return albPath.string() + "/";
} }
std::string DirectoryManager::configPath(std::string_view path) std::string DirectoryManager::configPath(std::string_view path) {
{
return fs::canonical(path).parent_path().string(); return fs::canonical(path).parent_path().string();
} }
std::string DirectoryManager::configPath(const model::BinaryPath& bConf) std::string DirectoryManager::configPath(const model::BinaryPath& bConf) {
{
return fs::canonical(bConf.path).parent_path().string(); return fs::canonical(bConf.path).parent_path().string();
} }
std::string DirectoryManager::contentOfPath(const std::string& path) std::string DirectoryManager::contentOfPath(const std::string& path) {
{
std::fstream a(path, std::ios::in); std::fstream a(path, std::ios::in);
std::stringstream s; std::stringstream s;
s << a.rdbuf(); s << a.rdbuf();
a.close(); a.close();
return s.str(); return s.str();
} }
std::string DirectoryManager::retrievePathType(type::PathType pType) std::string DirectoryManager::retrievePathType(type::PathType pType) {
{
std::string path; std::string path;
switch (pType) { switch (pType) {
case type::PathType::music: case type::PathType::music:
@@ -112,44 +107,40 @@ std::string DirectoryManager::retrievePathType(type::PathType pType)
} }
return path; return path;
} }
nlohmann::json DirectoryManager::credentialConfigContent(const model::BinaryPath& bConf) nlohmann::json DirectoryManager::credentialConfigContent(const model::BinaryPath& bConf) {
{
auto path = configPath(bConf); auto path = configPath(bConf);
path.append("/authcredentials.json"); path.append("/authcredentials.json");
return nlohmann::json::parse(contentOfPath(path)); return nlohmann::json::parse(contentOfPath(path));
} }
nlohmann::json DirectoryManager::databaseConfigContent(const model::BinaryPath& bConf) nlohmann::json DirectoryManager::databaseConfigContent(const model::BinaryPath& bConf) {
{
auto path = configPath(bConf); auto path = configPath(bConf);
path.append("/database.json"); path.append("/database.json");
return nlohmann::json::parse(contentOfPath(path)); return nlohmann::json::parse(contentOfPath(path));
} }
nlohmann::json DirectoryManager::pathConfigContent(const model::BinaryPath& bConf) nlohmann::json DirectoryManager::pathConfigContent(const model::BinaryPath& bConf) {
{
auto path = configPath(bConf); auto path = configPath(bConf);
path.append("/paths.json"); path.append("/paths.json");
return nlohmann::json::parse(contentOfPath(path)); return nlohmann::json::parse(contentOfPath(path));
} }
void DirectoryManager::deleteDirectories(model::Song song, const std::string& rootPath) void DirectoryManager::deleteDirectories(model::Song song, const std::string& rootPath) {
{ std::cout << "checking for empty directories to delete\n";
std::cout << "checking for empty directories to delete" << std::endl;
const std::string art(rootPath + std::string("/") + song.albumArtist); const std::string art(rootPath + std::string("/") + song.albumArtist);
const std::string alb(art + "/" + song.album); const std::string alb(art + "/" + song.album);
auto albPath = fs::path(alb); auto albPath = fs::path(alb);
if (!fs::exists(albPath)) { if (!fs::exists(albPath)) {
std::cout << "directory does not exists" << std::endl; std::cout << "directory does not exists\n";
} else if (fs::is_empty(albPath)) { } else if (fs::is_empty(albPath)) {
fs::remove(albPath); fs::remove(albPath);
} }
@@ -157,39 +148,36 @@ void DirectoryManager::deleteDirectories(model::Song song, const std::string& ro
auto artPath = fs::path(art); auto artPath = fs::path(art);
if (!fs::exists(artPath)) { if (!fs::exists(artPath)) {
std::cout << "directory does not exists" << std::endl; std::cout << "directory does not exists\n";
return; return;
} else if (fs::is_empty(artPath)) { } else if (fs::is_empty(artPath)) {
fs::remove(artPath); fs::remove(artPath);
} }
std::cout << "deleted empty directory or directories" << std::endl; std::cout << "deleted empty directory or directories\n";
} }
void DirectoryManager::deleteCoverArtFile(const std::string& covPath, void DirectoryManager::deleteCoverArtFile(const std::string& covPath,
const std::string& stockCoverPath) const std::string& stockCoverPath) {
{
if (covPath.compare(stockCoverPath) == 0) { if (covPath.compare(stockCoverPath) == 0) {
std::cout << "cover has stock cover art, will not deleted" << std::endl; std::cout << "cover has stock cover art, will not deleted\n";
} else { } else {
std::cout << "deleting song path" << std::endl; std::cout << "deleting song path\n";
auto cov = fs::path(covPath); auto cov = fs::path(covPath);
fs::remove(cov); fs::remove(cov);
} }
} }
void DirectoryManager::deleteSong(const model::Song song) void DirectoryManager::deleteSong(const model::Song song) {
{ std::cout << "deleting song\n";
std::cout << "deleting song" << std::endl;
auto songPath = fs::path(song.songPath); auto songPath = fs::path(song.songPath);
if (!fs::exists(songPath)) { if (!fs::exists(songPath)) {
std::cout << "song does not exists" << std::endl; std::cout << "song does not exists\n";
return; return;
} }
fs::remove(songPath); fs::remove(songPath);
std::cout << "deleted song" << std::endl; std::cout << "deleted song" << "\n";
} }
} }
+20 -25
View File
@@ -6,19 +6,17 @@
#include "type/GenreFilter.h" #include "type/GenreFilter.h"
namespace manager { namespace manager {
GenreManager::GenreManager(const model::BinaryPath& bConf) : m_bConf(bConf) { } GenreManager::GenreManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
model::Genre GenreManager::retrieveGenre(model::Genre& genre) model::Genre GenreManager::retrieveGenre(model::Genre& genre) {
{
database::GenreRepository gnrRepo(m_bConf); database::GenreRepository gnrRepo(m_bConf);
genre = gnrRepo.retrieveRecord(genre, type::GenreFilter::category); genre = gnrRepo.retrieveRecord(genre, type::GenreFilter::category);
return genre; return genre;
} }
model::Genre GenreManager::saveGenre(const model::Song& song) model::Genre GenreManager::saveGenre(const model::Song& song) {
{
model::Genre genre; model::Genre genre;
genre.category = song.genre; genre.category = song.genre;
@@ -26,15 +24,14 @@ model::Genre GenreManager::saveGenre(const model::Song& song)
if (!gnrRepo.doesGenreExist(genre, type::GenreFilter::category)) { if (!gnrRepo.doesGenreExist(genre, type::GenreFilter::category)) {
gnrRepo.saveRecord(genre); gnrRepo.saveRecord(genre);
} else { } else {
std::cout << "genre record already exists" << std::endl; std::cout << "genre record already exists\n";
} }
return genre; return genre;
} }
void GenreManager::deleteGenre(const model::Song& song) void GenreManager::deleteGenre(const model::Song& song) {
{
model::Genre genre(song); model::Genre genre(song);
database::GenreRepository gnrRepo(m_bConf); database::GenreRepository gnrRepo(m_bConf);
@@ -42,36 +39,34 @@ void GenreManager::deleteGenre(const model::Song& song)
if (gnrWSC.second > 1) { if (gnrWSC.second > 1) {
std::cout << "genre still contain songs related to it"; std::cout << "genre still contain songs related to it";
std::cout << ", will not delete" << std::endl; std::cout << ", will not delete\n";
return; return;
} }
std::cout << "safe to delete the genre record" << std::endl; std::cout << "safe to delete the genre record\n";
gnrRepo.deleteRecord(genre, type::GenreFilter::id); gnrRepo.deleteRecord(genre, type::GenreFilter::id);
} }
void GenreManager::updateGenre(model::Song& updatedSong, void GenreManager::updateGenre(model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
model::Genre genre; model::Genre genre;
genre.category = updatedSong.genre; genre.category = updatedSong.genre;
database::GenreRepository gnrRepo(m_bConf); database::GenreRepository gnrRepo(m_bConf);
if (!gnrRepo.doesGenreExist(genre, type::GenreFilter::category)) { if (!gnrRepo.doesGenreExist(genre, type::GenreFilter::category)) {
std::cout << "genre record does not exist" << std::endl; std::cout << "genre record does not exist\n";
gnrRepo.saveRecord(genre); gnrRepo.saveRecord(genre);
} else { } else {
std::cout << "genre record already exists" << std::endl; std::cout << "genre record already exists\n";
} }
genre = gnrRepo.retrieveRecord(genre, type::GenreFilter::category); genre = gnrRepo.retrieveRecord(genre, type::GenreFilter::category);
updatedSong.genreId = genre.id; updatedSong.genreId = genre.id;
} }
void GenreManager::printGenre(const model::Genre& genre) void GenreManager::printGenre(const model::Genre& genre) {
{ std::cout << "genre record\n";
std::cout << "genre record" << std::endl; std::cout << "id: " << genre.id << "\n";
std::cout << "id: " << genre.id << std::endl; std::cout << "category: " << genre.category << "\n";
std::cout << "category: " << genre.category << std::endl; }
}
} }
+75 -92
View File
@@ -22,12 +22,10 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace manager { namespace manager {
SongManager::SongManager(const model::BinaryPath& bConf) SongManager::SongManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
: m_bConf(bConf) { }
std::pair<bool, type::SongUpload> SongManager::saveSong(model::Song& song) std::pair<bool, type::SongUpload> SongManager::saveSong(model::Song& song) {
{
saveSongTemp(song); saveSongTemp(song);
utility::MetadataRetriever meta; utility::MetadataRetriever meta;
auto data = std::move(song.data); auto data = std::move(song.data);
@@ -49,12 +47,11 @@ std::pair<bool, type::SongUpload> SongManager::saveSong(model::Song& song)
song = songRepo.retrieveRecord(song, type::SongFilter::titleAndArtist); song = songRepo.retrieveRecord(song, type::SongFilter::titleAndArtist);
return std::make_pair(true, type::SongUpload::Successful); return std::make_pair(true, type::SongUpload::Successful);
} }
bool SongManager::didSongChange(const model::Song& updatedSong, bool SongManager::didSongChange(const model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
if (!updatedSong.title.empty()) { if (!updatedSong.title.empty()) {
return true; return true;
} }
@@ -72,11 +69,10 @@ bool SongManager::didSongChange(const model::Song& updatedSong,
} }
return false; return false;
} }
bool SongManager::requiresFilesystemChange(const model::Song& updatedSong, bool SongManager::requiresFilesystemChange(const model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
if (updatedSong.title.compare(currSong.title) != 0) { if (updatedSong.title.compare(currSong.title) != 0) {
return true; return true;
} }
@@ -88,14 +84,13 @@ bool SongManager::requiresFilesystemChange(const model::Song& updatedSong,
} }
return false; return false;
} }
bool SongManager::deleteSong(model::Song& song) bool SongManager::deleteSong(model::Song& song) {
{
database::SongRepository songRepo(m_bConf); database::SongRepository songRepo(m_bConf);
if (!songRepo.doesSongExist(song, type::SongFilter::id)) { if (!songRepo.doesSongExist(song, type::SongFilter::id)) {
std::cout << "song does not exist" << std::endl; std::cout << "song does not exist\n";
return false; return false;
} }
@@ -106,7 +101,7 @@ bool SongManager::deleteSong(model::Song& song)
auto deleted = songRepo.deleteRecord(song); auto deleted = songRepo.deleteRecord(song);
if (!deleted) { if (!deleted) {
std::cout << "song not deleted from databases" << std::endl; std::cout << "song not deleted from databases\n";
return deleted; return deleted;
} }
deleteMisc(song); deleteMisc(song);
@@ -114,16 +109,15 @@ bool SongManager::deleteSong(model::Song& song)
fs::remove(song.songPath); fs::remove(song.songPath);
DirectoryManager::deleteDirectories(song, paths["root_music_path"].get<std::string>()); DirectoryManager::deleteDirectories(song, paths["root_music_path"].get<std::string>());
return deleted; return deleted;
} }
bool SongManager::updateSong(model::Song& updatedSong) bool SongManager::updateSong(model::Song& updatedSong) {
{
database::SongRepository songRepo(m_bConf); database::SongRepository songRepo(m_bConf);
model::Song currSong(updatedSong.id); model::Song currSong(updatedSong.id);
currSong = songRepo.retrieveRecord(currSong, type::SongFilter::id); currSong = songRepo.retrieveRecord(currSong, type::SongFilter::id);
if (!didSongChange(updatedSong, currSong)) { if (!didSongChange(updatedSong, currSong)) {
std::cout << "no change to the song" << std::endl; std::cout << "no change to the song\n";
return false; return false;
} }
@@ -145,33 +139,31 @@ bool SongManager::updateSong(model::Song& updatedSong)
updateMisc(changes, updatedSong, currSong); updateMisc(changes, updatedSong, currSong);
return true; return true;
} }
void SongManager::printSong(const model::Song& song) void SongManager::printSong(const model::Song& song) {
{ std::cout << "\nsong" << "\n";
std::cout << "\nsong" << std::endl; std::cout << "title: " << song.title << "\n";
std::cout << "title: " << song.title << std::endl; std::cout << "artist: " << song.artist << "\n";
std::cout << "artist: " << song.artist << std::endl; std::cout << "album artist: " << song.albumArtist << "\n";
std::cout << "album artist: " << song.albumArtist << std::endl; std::cout << "album: " << song.album << "\n";
std::cout << "album: " << song.album << std::endl; std::cout << "genre: " << song.genre << "\n";
std::cout << "genre: " << song.genre << std::endl; std::cout << "duration: " << song.duration << "\n";
std::cout << "duration: " << song.duration << std::endl; std::cout << "year: " << song.year << "\n";
std::cout << "year: " << song.year << std::endl; std::cout << "track: " << song.track << "\n";
std::cout << "track: " << song.track << std::endl; std::cout << "disc: " << song.disc << "\n";
std::cout << "disc: " << song.disc << std::endl; std::cout << "song path: " << song.songPath << "\n";
std::cout << "song path: " << song.songPath << std::endl; std::cout << "cover art id: " << song.coverArtId << "\n";
std::cout << "cover art id: " << song.coverArtId << std::endl; std::cout << "album id: " << song.albumId << "\n";
std::cout << "album id: " << song.albumId << std::endl; std::cout << "artist id: " << song.artistId << "\n";
std::cout << "artist id: " << song.artistId << std::endl; std::cout << "genre id: " << song.genreId << "\n";
std::cout << "genre id: " << song.genreId << std::endl; std::cout << "year id: " << song.yearId << "\n";
std::cout << "year id: " << song.yearId << std::endl; }
}
std::map<type::SongChanged, bool> SongManager::changesInSong( std::map<type::SongChanged, bool> SongManager::changesInSong(
const model::Song& updatedSong, const model::Song& currSong) const model::Song& updatedSong, const model::Song& currSong) {
{
std::map<type::SongChanged, bool> songChanges; std::map<type::SongChanged, bool> songChanges;
std::string_view updatedTitle = updatedSong.title; std::string_view updatedTitle = updatedSong.title;
@@ -202,8 +194,7 @@ std::map<type::SongChanged, bool> SongManager::changesInSong(
} }
std::string SongManager::createSongPath(const model::Song& song) std::string SongManager::createSongPath(const model::Song& song) {
{
auto songPath = DirectoryManager::createDirectoryProcess( auto songPath = DirectoryManager::createDirectoryProcess(
song, m_bConf, type::PathType::music); song, m_bConf, type::PathType::music);
@@ -218,15 +209,14 @@ std::string SongManager::createSongPath(const model::Song& song)
songPath.append(".mp3"); songPath.append(".mp3");
return songPath; return songPath;
} }
// used to prevent empty values to appear in the updated song // used to prevent empty values to appear in the updated song
void SongManager::assignMiscFields( void SongManager::assignMiscFields(
std::map<type::SongChanged, bool>& songChanges, model::Song& updatedSong, std::map<type::SongChanged, bool>& songChanges, model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{ std::cout << "assigning miscellanes fields to updated song\n";
std::cout << "assigning miscellanes fields to updated song" << std::endl;
updatedSong.track = currSong.track; updatedSong.track = currSong.track;
for (auto scIter = songChanges.begin(); scIter != songChanges.end(); ++scIter) { for (auto scIter = songChanges.begin(); scIter != songChanges.end(); ++scIter) {
type::SongChanged key = scIter->first; type::SongChanged key = scIter->first;
@@ -236,45 +226,43 @@ void SongManager::assignMiscFields(
switch (key) { switch (key) {
case type::SongChanged::title: case type::SongChanged::title:
updatedSong.title = currSong.title; updatedSong.title = currSong.title;
std::cout << "title has not been changed" << std::endl; std::cout << "title has not been changed\n";
break; break;
case type::SongChanged::artist: case type::SongChanged::artist:
updatedSong.artist = currSong.artist; updatedSong.artist = currSong.artist;
std::cout << "artist has not been changed" << std::endl; std::cout << "artist has not been changed\n";
break; break;
case type::SongChanged::album: case type::SongChanged::album:
updatedSong.album = currSong.album; updatedSong.album = currSong.album;
std::cout << "album has not been changed" << std::endl; std::cout << "album has not been changed\n";
break; break;
case type::SongChanged::genre: case type::SongChanged::genre:
updatedSong.genre = currSong.genre; updatedSong.genre = currSong.genre;
std::cout << "genre has not been changed" << std::endl; std::cout << "genre has not been changed\n";
break; break;
case::type::SongChanged::year: case::type::SongChanged::year:
updatedSong.year = currSong.year; updatedSong.year = currSong.year;
std::cout << "year has not been changed" << std::endl; std::cout << "year has not been changed\n";
default: default:
break; break;
} }
} }
} }
} }
// used to dump miscellaneous id to the updated song // used to dump miscellaneous id to the updated song
void SongManager::assignMiscId(model::Song& updatedSong, void SongManager::assignMiscId(model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{ std::cout << "assigning miscellaneous Id's to updated song\n";
std::cout << "assigning miscellaneous Id's to updated song" << std::endl;
updatedSong.artistId = currSong.artistId; updatedSong.artistId = currSong.artistId;
updatedSong.albumId = currSong.albumId; updatedSong.albumId = currSong.albumId;
updatedSong.genreId = currSong.genreId; updatedSong.genreId = currSong.genreId;
updatedSong.yearId = currSong.yearId; updatedSong.yearId = currSong.yearId;
updatedSong.coverArtId = currSong.coverArtId; updatedSong.coverArtId = currSong.coverArtId;
} }
// saves song to a temporary path // saves song to a temporary path
void SongManager::saveSongTemp(model::Song& song) void SongManager::saveSongTemp(model::Song& song) {
{
auto config = DirectoryManager::pathConfigContent(m_bConf); auto config = DirectoryManager::pathConfigContent(m_bConf);
auto tmpSongPath = config["temp_root_path"].get<std::string>(); auto tmpSongPath = config["temp_root_path"].get<std::string>();
@@ -290,10 +278,9 @@ void SongManager::saveSongTemp(model::Song& song)
s.close(); s.close();
song.songPath = tmpSongPath; song.songPath = tmpSongPath;
} }
void SongManager::saveMisc(model::Song& song) void SongManager::saveMisc(model::Song& song) {
{
CoverArtManager covMgr(m_bConf); CoverArtManager covMgr(m_bConf);
auto pathConfigContent = DirectoryManager::pathConfigContent(m_bConf); auto pathConfigContent = DirectoryManager::pathConfigContent(m_bConf);
auto musicRootPath = pathConfigContent["root_music_path"].get<std::string>(); auto musicRootPath = pathConfigContent["root_music_path"].get<std::string>();
@@ -302,16 +289,16 @@ void SongManager::saveMisc(model::Song& song)
const auto songPath = createSongPath(song); const auto songPath = createSongPath(song);
if (fs::exists(songPath)) { if (fs::exists(songPath)) {
std::cout << "deleting old song with the same metadata" << std::endl; std::cout << "deleting old song with the same metadata\n";
fs::remove(songPath); fs::remove(songPath);
} }
std::cout << "copying song to the appropriate directory" << std::endl; std::cout << "copying song to the appropriate directory\n";
std::cout << song.songPath << std::endl; std::cout << song.songPath << std::endl;
std::cout << songPath << std::endl; std::cout << songPath << std::endl;
fs::copy(song.songPath, songPath); fs::copy(song.songPath, songPath);
fs::remove(song.songPath); fs::remove(song.songPath);
song.songPath = std::move(songPath); song.songPath = std::move(songPath);
std::cout << "copied song to the appropriate directory" << std::endl; std::cout << "copied song to the appropriate directory\n";
AlbumManager albMgr(m_bConf); AlbumManager albMgr(m_bConf);
auto album = albMgr.saveAlbum(song); auto album = albMgr.saveAlbum(song);
@@ -339,11 +326,10 @@ void SongManager::saveMisc(model::Song& song)
song.genreId = genre.id; song.genreId = genre.id;
song.yearId = year.id; song.yearId = year.id;
std::cout << "done with miscellaneous database records" << std::endl; std::cout << "done with miscellaneous database records\n";
} }
void SongManager::deleteMisc(const model::Song& song) void SongManager::deleteMisc(const model::Song& song) {
{
CoverArtManager covMgr(m_bConf); CoverArtManager covMgr(m_bConf);
covMgr.deleteCover(song); covMgr.deleteCover(song);
@@ -358,11 +344,10 @@ void SongManager::deleteMisc(const model::Song& song)
YearManager yrMgr(m_bConf); YearManager yrMgr(m_bConf);
yrMgr.deleteYear(song); yrMgr.deleteYear(song);
} }
// deletes miscellanes records // deletes miscellanes records
void SongManager::deleteMiscExceptCoverArt(const model::Song& song) void SongManager::deleteMiscExceptCoverArt(const model::Song& song) {
{
AlbumManager albMgr(m_bConf); AlbumManager albMgr(m_bConf);
albMgr.deleteAlbum(song); albMgr.deleteAlbum(song);
@@ -374,12 +359,11 @@ void SongManager::deleteMiscExceptCoverArt(const model::Song& song)
YearManager yrMgr(m_bConf); YearManager yrMgr(m_bConf);
yrMgr.deleteYear(song); yrMgr.deleteYear(song);
} }
void SongManager::updateMisc( void SongManager::updateMisc(
const std::map<type::SongChanged, bool>& songChanges, const std::map<type::SongChanged, bool>& songChanges,
model::Song& updatedSong, const model::Song& currSong) model::Song& updatedSong, const model::Song& currSong) {
{
auto titleChange = songChanges.at(type::SongChanged::title); auto titleChange = songChanges.at(type::SongChanged::title);
auto artistChange = songChanges.at(type::SongChanged::artist); auto artistChange = songChanges.at(type::SongChanged::artist);
auto albumChange = songChanges.at(type::SongChanged::album); auto albumChange = songChanges.at(type::SongChanged::album);
@@ -413,16 +397,15 @@ void SongManager::updateMisc(
songRepo.updateRecord(updatedSong); songRepo.updateRecord(updatedSong);
deleteMiscExceptCoverArt(currSong); deleteMiscExceptCoverArt(currSong);
} }
void SongManager::modifySongOnFilesystem(model::Song& updatedSong, void SongManager::modifySongOnFilesystem(model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{ std::cout << "preparing to modify song\n";
std::cout << "preparing to modify song" << std::endl;
auto songPath = createSongPath(updatedSong); auto songPath = createSongPath(updatedSong);
updatedSong.songPath = std::move(songPath); updatedSong.songPath = std::move(songPath);
std::cout << "new path " << updatedSong.songPath << std::endl; std::cout << "new path " << updatedSong.songPath << "\n";
fs::copy(currSong.songPath, updatedSong.songPath); fs::copy(currSong.songPath, updatedSong.songPath);
fs::remove(currSong.songPath); fs::remove(currSong.songPath);
@@ -435,5 +418,5 @@ void SongManager::modifySongOnFilesystem(model::Song& updatedSong,
CoverArtManager covMgr(m_bConf); CoverArtManager covMgr(m_bConf);
covMgr.updateCover(updatedSong, currSong); covMgr.updateCover(updatedSong, currSong);
} }
} }
+23 -33
View File
@@ -14,8 +14,7 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace manager { namespace manager {
model::Token TokenManager::retrieveToken(const model::BinaryPath& bConf) model::Token TokenManager::retrieveToken(const model::BinaryPath& bConf) {
{
auto cred = parseAuthCredentials(bConf); auto cred = parseAuthCredentials(bConf);
auto reqObj = createTokenBody(cred); auto reqObj = createTokenBody(cred);
@@ -31,15 +30,14 @@ model::Token TokenManager::retrieveToken(const model::BinaryPath& bConf)
postRes["expires_in"].get<int>()); postRes["expires_in"].get<int>());
return lr; return lr;
} }
bool TokenManager::isTokenValid(std::string& auth, type::Scope scope) bool TokenManager::isTokenValid(std::string& auth, type::Scope scope) {
{
auto authPair = fetchAuthHeader(auth); auto authPair = fetchAuthHeader(auth);
if (!std::get<0>(authPair)) { if (!std::get<0>(authPair)) {
std::cout << "no Bearer found" << std::endl; std::cout << "no Bearer found\n";
return std::get<0>(authPair); return std::get<0>(authPair);
} }
@@ -78,10 +76,9 @@ bool TokenManager::isTokenValid(std::string& auth, type::Scope scope)
} }
return false; return false;
} }
bool TokenManager::testAuth(const model::BinaryPath& bConf) bool TokenManager::testAuth(const model::BinaryPath& bConf) {
{
auto cred = parseAuthCredentials(bConf); auto cred = parseAuthCredentials(bConf);
auto reqObj = createTokenBody(cred); auto reqObj = createTokenBody(cred);
@@ -92,21 +89,19 @@ bool TokenManager::testAuth(const model::BinaryPath& bConf)
auto response = sendRequest(uri, reqObj); auto response = sendRequest(uri, reqObj);
return (response.status_code == 200) ? true : false; return (response.status_code == 200) ? true : false;
} }
cpr::Response TokenManager::sendRequest(std::string_view uri, nlohmann::json& obj) cpr::Response TokenManager::sendRequest(std::string_view uri, nlohmann::json& obj) {
{
auto resp = cpr::Post(cpr::Url{uri}, cpr::Body{obj.dump()}, auto resp = cpr::Post(cpr::Url{uri}, cpr::Body{obj.dump()},
cpr::Header{{"Content-type", "application/json"}, cpr::Header{{"Content-type", "application/json"},
{"Connection", "keep-alive"}}); {"Connection", "keep-alive"}});
return resp; return resp;
} }
nlohmann::json TokenManager::createTokenBody(const model::AuthCredentials& auth) nlohmann::json TokenManager::createTokenBody(const model::AuthCredentials& auth) {
{
nlohmann::json obj; nlohmann::json obj;
obj["client_id"] = auth.clientId; obj["client_id"] = auth.clientId;
obj["client_secret"] = auth.clientSecret; obj["client_secret"] = auth.clientSecret;
@@ -114,11 +109,10 @@ nlohmann::json TokenManager::createTokenBody(const model::AuthCredentials& auth)
obj["grant_type"] = "client_credentials"; obj["grant_type"] = "client_credentials";
return obj; return obj;
} }
model::AuthCredentials TokenManager::parseAuthCredentials(const model::BinaryPath& bConf) model::AuthCredentials TokenManager::parseAuthCredentials(const model::BinaryPath& bConf) {
{
auto con = DirectoryManager::credentialConfigContent(bConf); auto con = DirectoryManager::credentialConfigContent(bConf);
model::AuthCredentials auth; model::AuthCredentials auth;
@@ -130,16 +124,15 @@ model::AuthCredentials TokenManager::parseAuthCredentials(const model::BinaryPat
auth.endpoint = "oauth/token"; auth.endpoint = "oauth/token";
return auth; return auth;
} }
std::vector<std::string> TokenManager::extractScopes(const jwt::decoded_jwt&& decoded) std::vector<std::string> TokenManager::extractScopes(const jwt::decoded_jwt&& decoded) {
{
std::vector<std::string> scopes; std::vector<std::string> scopes;
for (auto& d : decoded.get_payload_claims()) { for (auto& d : decoded.get_payload_claims()) {
if (d.first.compare("scope") == 0) { if (d.first.compare("scope") == 0) {
std::cout << "found scope" << std::endl; std::cout << "found scope\n";
std::string allScopes(d.second.to_json().get<std::string>()); std::string allScopes(d.second.to_json().get<std::string>());
std::istringstream iss(allScopes); std::istringstream iss(allScopes);
@@ -149,10 +142,9 @@ std::vector<std::string> TokenManager::extractScopes(const jwt::decoded_jwt&& de
} }
return scopes; return scopes;
} }
std::pair<bool, std::vector<std::string>> TokenManager::fetchAuthHeader(const std::string& auth) std::pair<bool, std::vector<std::string>> TokenManager::fetchAuthHeader(const std::string& auth) {
{
std::istringstream iss(auth); std::istringstream iss(auth);
std::vector<std::string> authHeader{std::istream_iterator<std::string>(iss), std::vector<std::string> authHeader{std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>() std::istream_iterator<std::string>()
@@ -161,22 +153,20 @@ std::pair<bool, std::vector<std::string>> TokenManager::fetchAuthHeader(const st
bool foundBearer = false; bool foundBearer = false;
if (std::any_of(authHeader.begin(), authHeader.end(), if (std::any_of(authHeader.begin(), authHeader.end(),
[&](std::string_view word) { [&](std::string_view word) {
return (word.compare("Bearer") == 0); return (word.compare("Bearer") == 0); })) {
})) { std::cout << "Bearer found\n";
std::cout << "Bearer found" << std::endl;
foundBearer = true; foundBearer = true;
} }
return std::make_pair(foundBearer, authHeader); return std::make_pair(foundBearer, authHeader);
} }
bool TokenManager::tokenSupportsScope(const std::vector<std::string>& scopes, bool TokenManager::tokenSupportsScope(const std::vector<std::string>& scopes,
const std::string&& scope) const std::string&& scope) {
{
return std::any_of(scopes.begin(), scopes.end(), return std::any_of(scopes.begin(), scopes.end(),
[&](std::string_view foundScope) { [&](std::string_view foundScope) {
return (foundScope.compare(scope) == 0); return (foundScope.compare(scope) == 0);
}); });
} }
} }
+18 -18
View File
@@ -7,10 +7,10 @@
#include "utility/PasswordEncryption.h" #include "utility/PasswordEncryption.h"
namespace manager { namespace manager {
UserManager::UserManager(const model::BinaryPath& bConf) : m_bConf(bConf) { } UserManager::UserManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
model::RegisterResult UserManager::registerUser(model::User& user) { model::RegisterResult UserManager::registerUser(model::User& user) {
model::RegisterResult result; model::RegisterResult result;
result.username = user.username; result.username = user.username;
printUser(user); printUser(user);
@@ -25,7 +25,7 @@ model::RegisterResult UserManager::registerUser(model::User& user) {
model::User usr; model::User usr;
usr.username = user.username; usr.username = user.username;
std::cout << usr.username << std::endl; std::cout << usr.username << "\n";
usr = usrRepo.retrieveUserRecord(usr, type::UserFilter::username); usr = usrRepo.retrieveUserRecord(usr, type::UserFilter::username);
hashed.hashPassword = usr.password; hashed.hashPassword = usr.password;
hashed.userId = usr.id; hashed.userId = usr.id;
@@ -36,16 +36,16 @@ model::RegisterResult UserManager::registerUser(model::User& user) {
printUser(usr); printUser(usr);
return result; return result;
} }
bool UserManager::doesUserExist(const model::User& user) { bool UserManager::doesUserExist(const model::User& user) {
database::UserRepository userRepo(m_bConf); database::UserRepository userRepo(m_bConf);
return userRepo.doesUserRecordExist(user, type::UserFilter::username); return userRepo.doesUserRecordExist(user, type::UserFilter::username);
} }
bool UserManager::validatePassword(const model::User& user) { bool UserManager::validatePassword(const model::User& user) {
database::UserRepository userRepo(m_bConf); database::UserRepository userRepo(m_bConf);
model::User usr; model::User usr;
usr.username = user.username; usr.username = user.username;
@@ -59,18 +59,18 @@ bool UserManager::validatePassword(const model::User& user) {
utility::PasswordEncryption passEnc; utility::PasswordEncryption passEnc;
return passEnc.isPasswordValid(user, userSec); return passEnc.isPasswordValid(user, userSec);
} }
void UserManager::printUser(const model::User& user) { void UserManager::printUser(const model::User& user) {
std::cout << "\nuser info" << std::endl; std::cout << "\nuser info\n";
std::cout << "id: " << user.id << std::endl; std::cout << "id: " << user.id << "\n";
std::cout << "firstname: " << user.firstname << std::endl; std::cout << "firstname: " << user.firstname << "\n";
std::cout << "lastname: " << user.lastname << std::endl; std::cout << "lastname: " << user.lastname << "\n";
std::cout << "phone: " << user.phone << std::endl; std::cout << "phone: " << user.phone << "\n";
std::cout << "email: " << user.email << std::endl; std::cout << "email: " << user.email << "\n";
std::cout << "username: " << user.username << std::endl; std::cout << "username: " << user.username << "\n";
std::cout << "password: " << user.password<< std::endl; std::cout << "password: " << user.password<< "\n";
} }
} }
+20 -26
View File
@@ -6,20 +6,17 @@
#include "type/YearFilter.h" #include "type/YearFilter.h"
namespace manager { namespace manager {
YearManager::YearManager(const model::BinaryPath& bConf) YearManager::YearManager(const model::BinaryPath& bConf) : m_bConf(bConf) { }
: m_bConf(bConf) { }
model::Year YearManager::retrieveYear(model::Year& year) model::Year YearManager::retrieveYear(model::Year& year) {
{
database::YearRepository yearRepo(m_bConf); database::YearRepository yearRepo(m_bConf);
year = yearRepo.retrieveRecord(year, type::YearFilter::year); year = yearRepo.retrieveRecord(year, type::YearFilter::year);
return year; return year;
} }
model::Year YearManager::saveYear(const model::Song& song) model::Year YearManager::saveYear(const model::Song& song) {
{
model::Year year; model::Year year;
year.year = song.year; year.year = song.year;
@@ -27,14 +24,13 @@ model::Year YearManager::saveYear(const model::Song& song)
if (!yearRepo.doesYearExist(year, type::YearFilter::year)) { if (!yearRepo.doesYearExist(year, type::YearFilter::year)) {
yearRepo.saveRecord(year); yearRepo.saveRecord(year);
} else { } else {
std::cout << "year record already exists in the database" << std::endl; std::cout << "year record already exists in the database\n";
} }
return year; return year;
} }
void YearManager::deleteYear(const model::Song& song) void YearManager::deleteYear(const model::Song& song) {
{
model::Year year(song); model::Year year(song);
database::YearRepository yrRepo(m_bConf); database::YearRepository yrRepo(m_bConf);
@@ -42,36 +38,34 @@ void YearManager::deleteYear(const model::Song& song)
if (yrWSC.second > 1) { if (yrWSC.second > 1) {
std::cout << "year still contain songs related to it"; std::cout << "year still contain songs related to it";
std::cout << ", will not delete" << std::endl; std::cout << ", will not delete\n";
return; return;
} }
std::cout << "safe to delete the year record" << std::endl; std::cout << "safe to delete the year record\n";
yrRepo.deleteYear(year, type::YearFilter::id); yrRepo.deleteYear(year, type::YearFilter::id);
} }
void YearManager::updateYear(model::Song& updatedSong, void YearManager::updateYear(model::Song& updatedSong,
const model::Song& currSong) const model::Song& currSong) {
{
model::Year year; model::Year year;
year.year = updatedSong.year; year.year = updatedSong.year;
database::YearRepository albRepo(m_bConf); database::YearRepository albRepo(m_bConf);
if (!albRepo.doesYearExist(year, type::YearFilter::year)) { if (!albRepo.doesYearExist(year, type::YearFilter::year)) {
std::cout << "year record does not exist" << std::endl; std::cout << "year record does not exist\n";
albRepo.saveRecord(year); albRepo.saveRecord(year);
} else { } else {
std::cout << "year record already exists" << std::endl; std::cout << "year record already exists\n";
} }
year = albRepo.retrieveRecord(year, type::YearFilter::year); year = albRepo.retrieveRecord(year, type::YearFilter::year);
updatedSong.yearId = year.id; updatedSong.yearId = year.id;
} }
void YearManager::printYear(const model::Year& year) void YearManager::printYear(const model::Year& year) {
{ std::cout << "\nyear record\n";
std::cout << "\nyear record" << std::endl; std::cout << "id: " << year.id << "\n";
std::cout << "id: " << year.id << std::endl; std::cout << "year: " << year.year << "\n";
std::cout << "year: " << year.year << std::endl; }
}
} }
+3 -6
View File
@@ -1,12 +1,9 @@
#include "utility/ImageFile.h" #include "utility/ImageFile.h"
namespace utility { namespace utility {
ImageFile::ImageFile(const char *file) : TagLib::File(file) ImageFile::ImageFile(const char *file) : TagLib::File(file) { }
{
}
TagLib::ByteVector ImageFile::data() TagLib::ByteVector ImageFile::data() {
{
return readBlock(length()); return readBlock(length());
} }
} }
+23 -30
View File
@@ -19,8 +19,7 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace utility { namespace utility {
model::Song MetadataRetriever::retrieveMetadata(model::Song& song) model::Song MetadataRetriever::retrieveMetadata(model::Song& song) {
{
TagLib::MPEG::File sameFile(song.songPath.c_str()); TagLib::MPEG::File sameFile(song.songPath.c_str());
auto tag = sameFile.ID3v2Tag(); auto tag = sameFile.ID3v2Tag();
song.title = tag->title().toCString(); song.title = tag->title().toCString();
@@ -58,13 +57,11 @@ model::Song MetadataRetriever::retrieveMetadata(model::Song& song)
song.albumArtist = albumArtistFrame.front()->toString().toCString(); song.albumArtist = albumArtistFrame.front()->toString().toCString();
} }
return song; return song;
} }
model::Cover MetadataRetriever::updateCoverArt(const model::Song& song, model::Cover& cov, model::Cover MetadataRetriever::updateCoverArt(const model::Song& song, model::Cover& cov,
const std::string& stockCoverPath) const std::string& stockCoverPath) {
{
TagLib::MPEG::File sngF(song.songPath.c_str()); TagLib::MPEG::File sngF(song.songPath.c_str());
auto tag = sngF.ID3v2Tag(); auto tag = sngF.ID3v2Tag();
auto frameList = tag->frameListMap()["APIC"]; auto frameList = tag->frameListMap()["APIC"];
@@ -73,7 +70,7 @@ model::Cover MetadataRetriever::updateCoverArt(const model::Song& song, model::C
cov.imagePath.append("CoverArt.png"); cov.imagePath.append("CoverArt.png");
if (!fs::exists(cov.imagePath)) { if (!fs::exists(cov.imagePath)) {
std::cout << "copying stock cover path" << std::endl; std::cout << "copying stock cover path\n";
fs::copy(stockCoverPath, cov.imagePath); fs::copy(stockCoverPath, cov.imagePath);
} }
@@ -101,17 +98,16 @@ model::Cover MetadataRetriever::updateCoverArt(const model::Song& song, model::C
std::ios::binary); std::ios::binary);
imgSave.write(frame->picture().data(), frame->picture().size()); imgSave.write(frame->picture().data(), frame->picture().size());
imgSave.close(); imgSave.close();
std::cout << "saved to " << cov.imagePath << std::endl; std::cout << "saved to " << cov.imagePath << "\n";
} }
return cov; return cov;
} }
// tags song with the stock cover art // tags song with the stock cover art
model::Cover MetadataRetriever::applyStockCoverArt( model::Cover MetadataRetriever::applyStockCoverArt(
const model::Song& song, model::Cover& cov, const model::Song& song, model::Cover& cov,
const std::string& stockCoverPath) const std::string& stockCoverPath) {
{
TagLib::MPEG::File songFile(song.songPath.c_str()); TagLib::MPEG::File songFile(song.songPath.c_str());
auto tag = songFile.ID3v2Tag(); auto tag = songFile.ID3v2Tag();
@@ -125,18 +121,17 @@ model::Cover MetadataRetriever::applyStockCoverArt(
tag->addFrame(pic); tag->addFrame(pic);
songFile.save(); songFile.save();
std::cout << "applied stock cover art" << std::endl; std::cout << "applied stock cover art\n";
delete pic; delete pic;
return cov; return cov;
} }
// extracts cover art from the song and save it to the // extracts cover art from the song and save it to the
// appropriate directory // appropriate directory
model::Cover MetadataRetriever::applyCoverArt(const model::Song& song, model::Cover MetadataRetriever::applyCoverArt(const model::Song& song,
model::Cover& cov) model::Cover& cov) {
{
TagLib::MPEG::File songFile(song.songPath.c_str()); TagLib::MPEG::File songFile(song.songPath.c_str());
auto tag = songFile.ID3v2Tag(); auto tag = songFile.ID3v2Tag();
auto frameList = tag->frameListMap()["APIC"]; auto frameList = tag->frameListMap()["APIC"];
@@ -149,25 +144,23 @@ model::Cover MetadataRetriever::applyCoverArt(const model::Song& song,
imgSave.write(frame->picture().data(), frame->picture().size()); imgSave.write(frame->picture().data(), frame->picture().size());
imgSave.close(); imgSave.close();
std::cout << "saved to " << cov.imagePath << std::endl; std::cout << "saved to " << cov.imagePath << "\n";
return cov; return cov;
} }
bool MetadataRetriever::songContainsCoverArt(const model::Song& song) bool MetadataRetriever::songContainsCoverArt(const model::Song& song) {
{
TagLib::MPEG::File songFile(song.songPath.c_str()); TagLib::MPEG::File songFile(song.songPath.c_str());
auto tag = songFile.ID3v2Tag(); auto tag = songFile.ID3v2Tag();
auto frameList = tag->frameListMap()["APIC"]; auto frameList = tag->frameListMap()["APIC"];
return !frameList.isEmpty(); return !frameList.isEmpty();
} }
void MetadataRetriever::updateMetadata(model::Song& sngUpdated, const model::Song& sngOld) void MetadataRetriever::updateMetadata(model::Song& sngUpdated, const model::Song& sngOld) {
{ std::cout << "updating metadata\n";
std::cout<<"updating metadata"<<std::endl;
TagLib::MPEG::File file(sngOld.songPath.c_str()); TagLib::MPEG::File file(sngOld.songPath.c_str());
auto tag = file.ID3v2Tag(); auto tag = file.ID3v2Tag();
@@ -204,5 +197,5 @@ void MetadataRetriever::updateMetadata(model::Song& sngUpdated, const model::Son
// TODO: functionality to update the track number and disc number // TODO: functionality to update the track number and disc number
file.save(); file.save();
} }
} }
+6 -12
View File
@@ -7,8 +7,7 @@
namespace utility { namespace utility {
model::PassSec PasswordEncryption::hashPassword(const model::User& user) model::PassSec PasswordEncryption::hashPassword(const model::User& user) {
{
model::PassSec passSec; model::PassSec passSec;
std::unique_ptr<char[]> salt(new char[BCRYPT_HASHSIZE]); std::unique_ptr<char[]> salt(new char[BCRYPT_HASHSIZE]);
@@ -26,23 +25,18 @@ model::PassSec PasswordEncryption::hashPassword(const model::User& user)
std::cout << "salt: " << passSec.salt << std::endl; std::cout << "salt: " << passSec.salt << std::endl;
return passSec; return passSec;
} }
bool PasswordEncryption::isPasswordValid(const model::User& user, const model::PassSec& userSalt) bool PasswordEncryption::isPasswordValid(const model::User& user,
{ const model::PassSec& userSalt) {
std::unique_ptr<char[]> passwordHashed(new char[BCRYPT_HASHSIZE]); std::unique_ptr<char[]> passwordHashed(new char[BCRYPT_HASHSIZE]);
bcrypt_hashpw(user.password.c_str(), userSalt.salt.c_str(), passwordHashed.get()); bcrypt_hashpw(user.password.c_str(), userSalt.salt.c_str(), passwordHashed.get());
return (userSalt.hashPassword.compare(passwordHashed.get()) == 0) ? true : false; return (userSalt.hashPassword.compare(passwordHashed.get()) == 0) ? true : false;
} }
int PasswordEncryption::saltSize() constexpr int PasswordEncryption::saltSize() noexcept { return 10000; }
{
constexpr auto size = 10000;
return size;
}
} }
+29 -44
View File
@@ -11,16 +11,13 @@
namespace fs = std::filesystem; namespace fs = std::filesystem;
namespace verify { namespace verify {
bool Initialization::skipVerification(const std::string& argument) {
bool Initialization::skipVerification(const std::string& argument)
{
return argument.compare("--noverify") == 0; return argument.compare("--noverify") == 0;
} }
// verifies if the configuration settings are valid // verifies if the configuration settings are valid
void Initialization::checkIcarus(const model::BinaryPath& bConf) void Initialization::checkIcarus(const model::BinaryPath& bConf) {
{
auto auth = confirmConfigAuth(bConf); auto auth = confirmConfigAuth(bConf);
auto database = confirmConfigDatabase(bConf); auto database = confirmConfigDatabase(bConf);
auto path = confirmConfigPaths(bConf); auto path = confirmConfigPaths(bConf);
@@ -29,85 +26,73 @@ void Initialization::checkIcarus(const model::BinaryPath& bConf)
failedConfirmation(); failedConfirmation();
} }
std::cout << "icarus check passed" << std::endl; std::cout << "icarus check passed\n";
} }
// verifies that the authorization settings are not the default values // verifies that the authorization settings are not the default values
bool Initialization::confirmConfigAuth(const model::BinaryPath& bConf) bool Initialization::confirmConfigAuth(const model::BinaryPath& bConf) {
{
manager::TokenManager tokMgr; manager::TokenManager tokMgr;
return tokMgr.testAuth(bConf); return tokMgr.testAuth(bConf);
} }
// verifies if database connectivity can be established // verifies if database connectivity can be established
bool Initialization::confirmConfigDatabase(const model::BinaryPath& bConf) bool Initialization::confirmConfigDatabase(const model::BinaryPath& bConf) {
{
database::BaseRepository baseRepo(bConf); database::BaseRepository baseRepo(bConf);
return baseRepo.testConnection(); return baseRepo.testConnection();
} }
// verifies if the paths found in the config files exists // verifies if the paths found in the config files exists
bool Initialization::confirmConfigPaths(const model::BinaryPath& bConf) bool Initialization::confirmConfigPaths(const model::BinaryPath& bConf) {
{ using manager::DirectoryManager;
auto pathConfig = manager::DirectoryManager::pathConfigContent(bConf); auto pathConfig = DirectoryManager::pathConfigContent(bConf);
const auto rootMusicPath = const auto rootMusicPath =
pathConfig pathConfig
[manager:: [DirectoryManager::retrievePathType
DirectoryManager::
retrievePathType
(type::PathType::music)].get<std::string>(); (type::PathType::music)].get<std::string>();
const auto archiveRootPath = const auto archiveRootPath =
pathConfig pathConfig
[manager:: [DirectoryManager::retrievePathType
DirectoryManager::
retrievePathType
(type::PathType::archive)].get<std::string>(); (type::PathType::archive)].get<std::string>();
const auto tempRootPath = const auto tempRootPath =
pathConfig pathConfig
[manager:: [DirectoryManager::retrievePathType
DirectoryManager::
retrievePathType
(type::PathType::temp)].get<std::string>(); (type::PathType::temp)].get<std::string>();
const auto coverRootPath = const auto coverRootPath =
pathConfig pathConfig
[manager:: [DirectoryManager::retrievePathType
DirectoryManager::
retrievePathType
(type::PathType::coverArt)].get<std::string>(); (type::PathType::coverArt)].get<std::string>();
if (!fs::exists(rootMusicPath)) { if (!fs::exists(rootMusicPath)) {
std::cout << "root music path is not properly configured" << std::endl; std::cout << "root music path is not properly configured\n";
return false; return false;
} }
if (!fs::exists(archiveRootPath)) { if (!fs::exists(archiveRootPath)) {
std::cout << "archive root path is not properly configured" << std::endl; std::cout << "archive root path is not properly configured\n";
return false; return false;
} }
if (!fs::exists(tempRootPath)) { if (!fs::exists(tempRootPath)) {
std::cout << "temp root path is not properly configured" << std::endl; std::cout << "temp root path is not properly configured\n";
return false; return false;
} }
if (!fs::exists(coverRootPath)) { if (!fs::exists(coverRootPath)) {
std::cout << "cover art root path is not properly configured" << std::endl; std::cout << "cover art root path is not properly configured\n";
return false; return false;
} }
return true; return true;
} }
// confirmation failed // confirmation failed
void Initialization::failedConfirmation() void Initialization::failedConfirmation() {
{ std::cout << "configuration confirmation failed. check your settings\n";
std::cout << "configuration confirmation failed. check your settings" << std::endl;
std::exit(-1); std::exit(-1);
} }
} }