[LMSAPI] Removed unused LMS API

This commit is contained in:
epoupon
2015-09-24 13:12:09 +02:00
parent 65006d5730
commit 40c6e80c2c
29 changed files with 7 additions and 3528 deletions
+1 -47
View File
@@ -59,52 +59,6 @@ lms_SOURCES += \
$(srcdir)/ui/video/VideoParametersDialog.cpp
endif
if LMSAPI
lms_SOURCES += \
$(srcdir)/lms-api/server/Connection.cpp \
$(srcdir)/lms-api/server/ConnectionManager.cpp \
$(srcdir)/lms-api/server/AudioCollectionRequestHandler.cpp \
$(srcdir)/lms-api/server/AuthRequestHandler.cpp \
$(srcdir)/lms-api/server/MediaRequestHandler.cpp \
$(srcdir)/lms-api/server/RequestHandler.cpp \
$(srcdir)/lms-api/server/Server.cpp \
$(srcdir)/service/LmsAPIServerService.cpp
nodist_lms_SOURCES = \
$(builddir)/auth.pb.cc \
$(builddir)/auth.pb.h \
$(builddir)/collection.pb.cc \
$(builddir)/collection.pb.h \
$(builddir)/media.pb.cc \
$(builddir)/media.pb.h \
$(builddir)/messages.pb.cc \
$(builddir)/messages.pb.h
BUILT_SOURCES = \
$(builddir)/auth.pb.cc \
$(builddir)/auth.pb.h \
$(builddir)/collection.pb.cc \
$(builddir)/collection.pb.h \
$(builddir)/media.pb.cc \
$(builddir)/media.pb.h \
$(builddir)/messages.pb.cc \
$(builddir)/messages.pb.h
MOSTLYCLEANFILES = \
$(builddir)/auth.pb.cc \
$(builddir)/auth.pb.h \
$(builddir)/collection.pb.cc \
$(builddir)/collection.pb.h \
$(builddir)/media.pb.cc \
$(builddir)/media.pb.h \
$(builddir)/messages.pb.cc \
$(builddir)/messages.pb.h
%.pb.cc %.pb.h: $(top_srcdir)/lms-api/proto/%.proto
$(PROTOC) --proto_path=$(top_srcdir)/lms-api/proto/ --cpp_out=$(builddir)/ $^
endif
lms_CXXFLAGS=-std=c++11 -Wall -I$(top_srcdir)/third-party -I$(srcdir)/ui -I$(srcdir)/lms-api $(MAGICKXX_CFLAGS)
lms_CXXFLAGS=-std=c++11 -Wall -I$(top_srcdir)/third-party -I$(srcdir)/ui $(MAGICKXX_CFLAGS)
lms_LDADD=$(MAGICKXX_LIBS)
-98
View File
@@ -1,98 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <sstream>
#include "ConfigReader.hpp"
namespace {
}
ConfigReader::ConfigReader()
: _config (nullptr)
{
}
ConfigReader&
ConfigReader::instance()
{
static ConfigReader instance;
return instance;
}
void
ConfigReader::setFile(boost::filesystem::path p)
{
if (_config != nullptr)
delete _config;
_config = new libconfig::Config();
_config->readFile(p.string().c_str());
}
std::string
ConfigReader::getString(std::string setting, std::string def)
{
try {
return _config->lookup(setting);
}
catch (std::exception &e)
{
return def;
}
}
unsigned long
ConfigReader::getULong(std::string setting, unsigned long def)
{
try {
return static_cast<unsigned int>(_config->lookup(setting));
}
catch (...)
{
return def;
}
}
long
ConfigReader::getLong(std::string setting, long def)
{
try {
return _config->lookup(setting);
}
catch (...)
{
return def;
}
}
bool
ConfigReader::getBool(std::string setting, bool def)
{
try {
return _config->lookup(setting);
}
catch (...)
{
return def;
}
}
-50
View File
@@ -1,50 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef CONFIG_READER_HPP
#define CONFIG_READER_HPP
#include <boost/filesystem.hpp>
#include <libconfig.h++>
class ConfigReader
{
public:
ConfigReader(const ConfigReader&) = delete;
ConfigReader& operator=(const ConfigReader&) = delete;
static ConfigReader& instance();
void setFile(boost::filesystem::path p);
/* Default values are returned in case of setting not found */
std::string getString(std::string setting, std::string def = "");
unsigned long getULong(std::string setting, unsigned long def = 0);
long getLong(std::string setting, long def = 0);
bool getBool(std::string setting, bool def = false);
private:
ConfigReader();
libconfig::Config *_config;
};
#endif
-1
View File
@@ -18,7 +18,6 @@
*/
#include "logger/Logger.hpp"
#include "config/ConfigReader.hpp"
#include "av/AvInfo.hpp"
#include "CoverArtGrabber.hpp"
-105
View File
@@ -1,105 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REMOTE_HEADER_HPP
#define REMOTE_HEADER_HPP
#include <iomanip>
namespace LmsAPI
{
class Header
{
public:
static const std::size_t size = 8; // HeaderSize
static const std::size_t max_data_size = 65536*64 - size;
Header() : _dataSize(0) {}
void setDataSize(std::size_t size) { _dataSize = size; }
std::size_t getDataSize(void) const {return _dataSize;}
bool from_istream(std::istream &is)
{
std::array<unsigned char, size> buffer;
bool res = is.read(reinterpret_cast<char*>(buffer.data()), buffer.size());
if (res && is.gcount() == buffer.size())
return from_buffer(buffer);
else
return false;
}
bool from_buffer(const std::array<unsigned char, size>& buffer)
{
if (decode32(&buffer[0]) != _magic)
{
return false;
}
else
{
_dataSize = decode32(&buffer[4]);
return _dataSize <= max_data_size;
}
}
/* void to_ostream(std::ostream& os)
{
}*/
void to_buffer(std::array<unsigned char, size>& buffer) const
{
encode32(_magic, &buffer[0]);
encode32(_dataSize, &buffer[4]);
}
private:
static uint32_t decode32(const unsigned char* data)
{
return (static_cast<uint32_t>(data[0]) << 24)
+ (static_cast<uint32_t>(data[1]) << 16)
+ (static_cast<uint32_t>(data[2]) << 8)
+ (static_cast<uint32_t>(data[3]));
}
static void encode32(uint32_t value, unsigned char* data)
{
data[0] = (value >> 24) & 0xFF;
data[1] = (value >> 16) & 0xFF;
data[2] = (value >> 8) & 0xFF;
data[3] = (value) & 0xFF;
}
static const uint32_t _magic = 0xdeadbeef;
uint32_t _dataSize;
};
} // namespace LmsAPI
#endif
@@ -1,393 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm> // std::min
#include <boost/locale.hpp>
#include <boost/uuid/sha1.hpp>
#include "logger/Logger.hpp"
#include "AudioCollectionRequestHandler.hpp"
#include "database/Types.hpp"
#include "cover/CoverArtGrabber.hpp"
namespace LmsAPI {
namespace Server {
using namespace Database;
static SearchFilter SearchFilterFromRequest(const AudioCollectionRequest_SearchFilter& request)
{
SearchFilter filter;
for (int id = 0; id < request.artist_id_size(); ++id)
filter.idMatch[SearchFilter::Field::Artist].push_back( request.artist_id(id) );
for (int id = 0; id < request.genre_id_size(); ++id)
filter.idMatch[SearchFilter::Field::Genre].push_back( request.genre_id(id) );
for (int id = 0; id < request.release_id_size(); ++id)
filter.idMatch[SearchFilter::Field::Release].push_back( request.release_id(id) );
for (int id = 0; id < request.track_id_size(); ++id)
filter.idMatch[SearchFilter::Field::Track].push_back( request.track_id(id) );
return filter;
}
AudioCollectionRequestHandler::AudioCollectionRequestHandler(Handler& db)
: _db(db)
{}
bool
AudioCollectionRequestHandler::process(const AudioCollectionRequest& request, AudioCollectionResponse& response)
{
bool res = false;
switch (request.type())
{
case AudioCollectionRequest::TypeGetRevision:
// No payload
res = processGetRevision(*response.mutable_revision());
if (res)
response.set_type(AudioCollectionResponse::TypeRevision);
break;
case AudioCollectionRequest::TypeGetGenreList:
if (request.has_get_genres())
{
res = processGetGenres(request.get_genres(), *response.mutable_genre_list());
if (res)
response.set_type(AudioCollectionResponse::TypeArtistList);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad AudioCollectionRequest::TypeGetGenreList";
break;
case AudioCollectionRequest::TypeGetArtistList:
if (request.has_get_artists())
{
res = processGetArtists(request.get_artists(), *response.mutable_artist_list());
if (res)
response.set_type(AudioCollectionResponse::TypeArtistList);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad AudioCollectionRequest::TypeGetArtistList message!";
break;
case AudioCollectionRequest::TypeGetReleaseList:
if (request.has_get_releases())
{
res = processGetReleases(request.get_releases(), *response.mutable_release_list());
if (res)
response.set_type(AudioCollectionResponse::TypeReleaseList);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad AudioCollectionRequest::TypeGetReleaseList message!";
break;
case AudioCollectionRequest::TypeGetTrackList:
if (request.has_get_tracks())
{
res = processGetTracks(request.get_tracks(), *response.mutable_track_list());
if (res)
response.set_type(AudioCollectionResponse::TypeTrackList);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad AudioCollectionRequest::TypeGetTrackList message!";
break;
case AudioCollectionRequest::TypeGetCoverArt:
if (request.has_get_cover_art())
res = processGetCoverArt(request.get_cover_art(), response);
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad AudioCollectionRequest::TypeGetCoverArt message!";
break;
default:
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Unhandled AudioCollectionRequest_Type = " << request.type();
}
return res;
}
bool
AudioCollectionRequestHandler::processGetGenres(const AudioCollectionRequest::GetGenreList& request, AudioCollectionResponse::GenreList& response)
{
// sanity checks
if (!request.has_batch_parameter())
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "No batch parameters found!";
return false;
}
std::size_t size = request.batch_parameter().size();
if (!size)
size = _maxListArtists;
size = std::min(size, _maxListArtists);
// Get filters
SearchFilter filter;
if (request.has_search_filter())
filter = SearchFilterFromRequest(request.search_filter());
Wt::Dbo::Transaction transaction( _db.getSession() );
std::vector<Genre::pointer> genres = Genre::getByFilter( _db.getSession(), filter, request.batch_parameter().offset(), static_cast<int>(size));
for (Genre::pointer genre : genres)
{
AudioCollectionResponse_Genre* addGenre = response.add_genres();
addGenre->set_id(genre.id());
addGenre->set_name( std::string( boost::locale::conv::to_utf<char>(genre->getName(), "UTF-8") ) );
}
return true;
}
bool
AudioCollectionRequestHandler::processGetArtists(const AudioCollectionRequest::GetArtistList& request, AudioCollectionResponse::ArtistList& response)
{
// sanity checks
if (!request.has_batch_parameter())
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "No batch parameters found!";
return false;
}
std::size_t size = request.batch_parameter().size();
if (!size)
size = _maxListArtists;
size = std::min(size, _maxListArtists);
// Get filters
SearchFilter filter;
if (request.has_search_filter())
filter = SearchFilterFromRequest(request.search_filter());
// Now fetch requested data...
Wt::Dbo::Transaction transaction( _db.getSession() );
std::vector<Artist::pointer> artists
= Artist::getByFilter(_db.getSession(), filter,
request.batch_parameter().offset(), static_cast<int>(size) );
for (Artist::pointer artist : artists)
{
AudioCollectionResponse_Artist *addArtist = response.add_artists();
addArtist->set_id(artist.id());
addArtist->set_name( std::string( boost::locale::conv::to_utf<char>(artist->getName(), "UTF-8") ) );
if (!artist->getMBID().empty())
addArtist->set_mbid(artist->getMBID());
}
return true;
}
bool
AudioCollectionRequestHandler::processGetReleases(const AudioCollectionRequest::GetReleaseList& request, AudioCollectionResponse::ReleaseList& response)
{
// sanity checks
if (!request.has_batch_parameter())
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "No batch parameters found!";
return false;
}
std::size_t size = request.batch_parameter().size();
if (!size)
size = _maxListReleases;
size = std::min(size, _maxListReleases);
// Get filters
SearchFilter filter;
if (request.has_search_filter())
filter = SearchFilterFromRequest(request.search_filter());
Wt::Dbo::Transaction transaction( _db.getSession() );
std::vector<Release::pointer> releases
= Release::getByFilter( _db.getSession(), filter,
request.batch_parameter().offset(), static_cast<int>(size));
for (Release::pointer release : releases)
{
AudioCollectionResponse_Release *addRelease = response.add_releases();
addRelease->set_id(release.id());
addRelease->set_name( std::string( boost::locale::conv::to_utf<char>(release->getName(), "UTF-8")));
if (!release->getMBID().empty())
addRelease->set_mbid(release->getMBID());
}
return true;
}
bool
AudioCollectionRequestHandler::processGetTracks(const AudioCollectionRequest::GetTrackList& request, AudioCollectionResponse::TrackList& response)
{
// sanity checks
if (!request.has_batch_parameter())
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "No batch parameters found!";
return false;
}
std::size_t size = request.batch_parameter().size();
if (!size)
size = _maxListTracks;
size = std::min(size, _maxListTracks);
// Get filters
SearchFilter filter;
if (request.has_search_filter())
filter = SearchFilterFromRequest(request.search_filter());
Wt::Dbo::Transaction transaction( _db.getSession() );
std::vector<Track::pointer> tracks
= Track::getByFilter( _db.getSession(), filter,
request.batch_parameter().offset(), static_cast<int>(size));
for (Track::pointer track : tracks)
{
AudioCollectionResponse_Track* newTrack = response.add_tracks();
newTrack->set_id(track.id());
newTrack->set_disc_number( track->getDiscNumber() );
newTrack->set_track_number( track->getTrackNumber() );
newTrack->set_artist_id( track->getArtist().id() );
newTrack->set_release_id( track->getRelease().id() );
newTrack->set_name( std::string( boost::locale::conv::to_utf<char>(track->getName(), "UTF-8") ) );
newTrack->set_duration_secs( track->getDuration().total_seconds() );
// Only send the year part of the release times
if (!track->getDate().is_special())
newTrack->set_release_date( std::to_string(track->getDate().date().year()) );
if (!track->getOriginalDate().is_special())
newTrack->set_original_release_date( std::to_string(track->getOriginalDate().date().year()) );
if (!track->getMBID().empty())
newTrack->set_mbid(track->getMBID());
for (Genre::pointer genre : track->getGenres())
newTrack->add_genre_id( genre.id() );
}
return true;
}
bool
AudioCollectionRequestHandler::processGetCoverArt(const AudioCollectionRequest::GetCoverArt& request, AudioCollectionResponse& response)
{
bool res = false;
response.set_type(AudioCollectionResponse::TypeCoverArt);
std::vector<CoverArt::CoverArt> coverArts;
switch(request.type())
{
case AudioCollectionRequest::GetCoverArt::TypeGetCoverArtRelease:
if (request.has_release_id())
{
coverArts = CoverArt::Grabber::instance().getFromRelease( _db.getSession(), request.release_id());
res = true;
}
break;
case AudioCollectionRequest::GetCoverArt::TypeGetCoverArtTrack:
if (request.has_track_id())
{
coverArts = CoverArt::Grabber::instance().getFromTrack(_db.getSession(), request.track_id());
res = true;
}
break;
}
for (CoverArt::CoverArt& coverArt : coverArts)
{
AudioCollectionResponse_CoverArt* cover_art = response.add_cover_art();
if (request.has_size())
{
std::size_t size = request.size();
if (size > _maxCoverArtSize || size == 0)
size = _maxCoverArtSize;
if (size < _minCoverArtSize)
size = _minCoverArtSize;
coverArt.scale(size);
}
cover_art->set_mime_type(coverArt.getMimeType());
cover_art->set_data( std::string( coverArt.getData().begin(), coverArt.getData().end()) );
}
return res;
}
bool
AudioCollectionRequestHandler::processGetRevision(AudioCollectionResponse::Revision& response)
{
bool res = false;
Wt::Dbo::Transaction transaction( _db.getSession() );
MediaDirectorySettings::pointer settings = MediaDirectorySettings::get( _db.getSession() );
std::string hashStr = boost::posix_time::to_iso_string(settings->getLastUpdated());
boost::uuids::detail::sha1 s;
for (const char c : hashStr)
s.process_byte(c);
unsigned int digest[5];
s.get_digest(digest);
std::ostringstream oss;
for (std::size_t i = 0; i < 5; ++i)
oss << std::hex << std::setfill('0') << std::setw(4) << digest[i];
response.set_rev(oss.str());
res = true;
return res;
}
} // namespace LmsAPI
} // namespace Server
@@ -1,61 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REMOTE_AUDIO_COLLECTION_REQUEST_HANDLER
#define REMOTE_AUDIO_COLLECTION_REQUEST_HANDLER
#include "database/DatabaseHandler.hpp"
#include "messages.pb.h"
namespace LmsAPI {
namespace Server {
class AudioCollectionRequestHandler
{
public:
AudioCollectionRequestHandler(Database::Handler& db);
bool process(const AudioCollectionRequest& request, AudioCollectionResponse& response);
private:
bool processGetRevision(AudioCollectionResponse::Revision& response);
bool processGetArtists(const AudioCollectionRequest::GetArtistList& request, AudioCollectionResponse::ArtistList& response);
bool processGetGenres(const AudioCollectionRequest::GetGenreList& request, AudioCollectionResponse::GenreList& response);
bool processGetReleases(const AudioCollectionRequest::GetReleaseList& request, AudioCollectionResponse::ReleaseList& response);
bool processGetTracks(const AudioCollectionRequest::GetTrackList& request, AudioCollectionResponse::TrackList& response);
bool processGetCoverArt(const AudioCollectionRequest::GetCoverArt& request, AudioCollectionResponse& response);
Database::Handler& _db;
static const std::size_t _maxListArtists = 256;
static const std::size_t _maxListGenres = 256;
static const std::size_t _maxListReleases = 128;
static const std::size_t _maxListTracks = 128;
static const std::size_t _minCoverArtSize = 64; // in pixels, square
static const std::size_t _maxCoverArtSize = 512; // in pixels, square
};
} // namespace LmsAPI
} // namespace Server
#endif
-105
View File
@@ -1,105 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Wt/Auth/Identity>
#include "logger/Logger.hpp"
#include "AuthRequestHandler.hpp"
namespace LmsAPI {
namespace Server {
AuthRequestHandler::AuthRequestHandler(Database::Handler& db)
: _db(db)
{
}
bool
AuthRequestHandler::process(const AuthRequest& request, AuthResponse& response)
{
bool res = false;
switch (request.type())
{
case AuthRequest::TypePassword:
if (request.has_password())
{
res = processPassword(request.password(), *response.mutable_password_result());
if (res)
response.set_type(AuthResponse::TypePasswordResult);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad AuthRequest::TypePassword";
break;
}
return res;
}
bool
AuthRequestHandler::processPassword(const AuthRequest::Password& request, AuthResponse::PasswordResult& response)
{
bool res = false;
// Get the user
const Wt::Auth::User& user = _db.getUserDatabase().findWithIdentity(Wt::Auth::Identity::LoginName, request.user_login());
if (user.isValid())
{
// Now attempt to log the user in
Wt::Auth::PasswordResult result = _db.getPasswordService().verifyPassword(user, request.user_password());
switch( result )
{
case Wt::Auth::PasswordInvalid:
response.set_type(AuthResponse::PasswordResult::TypePasswordInvalid);
LMS_LOG(MOD_REMOTE, SEV_NOTICE) << "User '" << request.user_login() << "': invalid password";
res = true;
break;
case Wt::Auth::LoginThrottling:
response.set_type(AuthResponse::PasswordResult::TypeLoginThrottling);
response.set_delay(_db.getPasswordService().delayForNextAttempt(user));
res = true;
break;
case Wt::Auth::PasswordValid:
response.set_type(AuthResponse::PasswordResult::TypePasswordValid);
// Log the user in
_db.getLogin().login( user );
LMS_LOG(MOD_REMOTE, SEV_NOTICE) << "User '" << request.user_login() << "' successfully logged in";
res = true;
break;
default:
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Cannot handle password result!";
break;
}
}
else
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Invalid user '" << request.user_login();
response.set_type(AuthResponse::PasswordResult::TypePasswordInvalid);
}
return res;
}
} // namespace Server
} // namespace LmsAPI
-47
View File
@@ -1,47 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LMSAPI_AUTH_REQUEST_HANDLER
#define LMSAPI_AUTH_REQUEST_HANDLER
#include "database/DatabaseHandler.hpp"
#include "messages.pb.h"
namespace LmsAPI {
namespace Server {
class AuthRequestHandler
{
public:
AuthRequestHandler(Database::Handler& db);
bool process(const AuthRequest& request, AuthResponse& response);
private:
bool processPassword(const AuthRequest::Password& request, AuthResponse::PasswordResult& response);
Database::Handler& _db;
};
} // namespace Server
} // namespace LmsAPI
#endif
-250
View File
@@ -1,250 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utility>
#include <vector>
#include <boost/bind.hpp>
#include <boost/foreach.hpp>
#include "logger/Logger.hpp"
#include "messages.pb.h"
#include "RequestHandler.hpp"
#include "ConnectionManager.hpp"
#include "Connection.hpp"
namespace LmsAPI {
namespace Server {
Connection::Connection(boost::asio::io_service& ioService,
boost::asio::ssl::context& context,
ConnectionManager& manager,
Wt::Dbo::SqlConnectionPool& connectionPool)
: _closing(false),
_socket(ioService, context),
_connectionManager(manager),
_requestHandler(connectionPool)
{
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Server::Connection::Connection, Creating connection";
}
void
Connection::start()
{
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Starting connection...";
_socket.async_handshake(boost::asio::ssl::stream_base::server,
boost::bind(&Connection::handleHandshake, this,
boost::asio::placeholders::error));
}
void
Connection::handleHandshake(const boost::system::error_code& error)
{
if (!error)
{
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Handshake successfully performed... Now reading messages";
readMsg();
}
else if (error != boost::asio::error::operation_aborted)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Connection::handleHandshake: " << error.message();
_connectionManager.stop(shared_from_this());
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Handshake error: " << error.message();
}
void
Connection::readMsg()
{
// Read a header first
boost::asio::streambuf::mutable_buffers_type bufs = _inputStreamBuf.prepare(LmsAPI::Header::size);
boost::asio::async_read(_socket,
bufs,
boost::asio::transfer_exactly(LmsAPI::Header::size),
boost::bind(&Connection::handleReadHeader, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
void
Connection::stop()
{
if (!_closing)
{
boost::system::error_code ec;
_closing = true;
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Server::Connection::stop, Stopping connection " << this;
_socket.shutdown(ec);
if (ec)
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Error while shutting down connection " << this << ": " << ec.message();
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Server::Connection::stop, connection stopped " << this;
}
else
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Stop: close already in progress...";
}
void
Connection::handleReadHeader(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if (!error)
{
if (bytes_transferred != LmsAPI::Header::size)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "bytes_transferred (" << bytes_transferred << ") != LmsAPI::Header::size!";
_connectionManager.stop(shared_from_this());
return;
}
_inputStreamBuf.commit(bytes_transferred);
std::istream is(&_inputStreamBuf);
LmsAPI::Header header;
if (!header.from_istream(is))
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Cannot read header from buffer!";
_connectionManager.stop(shared_from_this());
return;
}
// Now read the real message payload
boost::asio::streambuf::mutable_buffers_type bufs = _inputStreamBuf.prepare(header.getDataSize());
boost::asio::async_read(_socket,
bufs,
boost::asio::transfer_exactly(header.getDataSize()),
boost::bind(&Connection::handleReadMsg, shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
}
else if (error != boost::asio::error::operation_aborted)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Connection::handleReadHeader: " << error.message();
_connectionManager.stop(shared_from_this());
}
}
void
Connection::handleReadMsg(const boost::system::error_code& error, std::size_t bytes_transferred)
{
if (!error)
{
_inputStreamBuf.commit(bytes_transferred);
std::istream is(&_inputStreamBuf);
std::ostream os(&_outputStreamBuf);
LmsAPI::ServerMessage response;
LmsAPI::ClientMessage request;
if (!request.ParseFromIstream(&is))
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Parse request failed!";
_connectionManager.stop(shared_from_this());
return;
}
if (!_requestHandler.process(request, response))
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Process request failed!";
_connectionManager.stop(shared_from_this());
return;
}
{
boost::system::error_code ec;
if (!response.SerializeToOstream(&os))
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Cannot serialize to ostream!";
_connectionManager.stop(shared_from_this());
return;
}
if (_outputStreamBuf.size() >= LmsAPI::Header::max_data_size)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "output message is too big! " << _outputStreamBuf.size() << " > " << LmsAPI::Header::max_data_size;
_connectionManager.stop(shared_from_this());
return;
}
std::array<unsigned char, LmsAPI::Header::size> headerBuffer;
{
LmsAPI::Header header;
header.setDataSize(_outputStreamBuf.size());
header.to_buffer(headerBuffer);
}
std::size_t n = boost::asio::write(_socket,
boost::asio::buffer(headerBuffer),
boost::asio::transfer_exactly(LmsAPI::Header::size),
ec);
if (ec)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "cannot write header: " << error.message();
_connectionManager.stop(shared_from_this());
}
else
{
assert(n == LmsAPI::Header::size);
}
// Now send serialized payload
n = boost::asio::write(_socket,
_outputStreamBuf.data(),
boost::asio::transfer_exactly(_outputStreamBuf.size()),
ec);
if (ec)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "cannot write msg: " << error.message();
_connectionManager.stop(shared_from_this());
}
else
{
assert(n == _outputStreamBuf.size());
_outputStreamBuf.consume(n);
}
}
// All good here, read another message
readMsg();
}
else if (error != boost::asio::error::operation_aborted)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Connection::handleRead: " << error.message();
_connectionManager.stop(shared_from_this());
}
}
} // namespace Server
} // namespace LmsAPI
-98
View File
@@ -1,98 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LMSAPI_CONNECTION_HPP
#define LMSAPI_CONNECTION_HPP
#include <array>
#include <memory>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include "RequestHandler.hpp"
#include "messages/Header.hpp"
namespace LmsAPI {
namespace Server {
class ConnectionManager;
/// Represents a single connection from a client.
class Connection : public std::enable_shared_from_this<Connection>
{
public:
typedef boost::asio::ssl::stream<boost::asio::ip::tcp::socket> ssl_socket;
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
typedef std::shared_ptr<Connection> pointer;
/// Construct a connection with the given io_service.
explicit Connection(boost::asio::io_service& ioService, boost::asio::ssl::context& context,
ConnectionManager& manager,
Wt::Dbo::SqlConnectionPool& connectionPool);
ssl_socket::lowest_layer_type& getSocket() {return _socket.lowest_layer();}
/// Start the first asynchronous operation for the connection.
void start();
/// Stop all asynchronous operations associated with the connection.
void stop();
private:
bool _closing;
/// Read a new message on the the connection
void readMsg();
/// Handle completion of ssl handshake
void handleHandshake(const boost::system::error_code& error);
/// Handle completion of a read operation.
void handleReadHeader(const boost::system::error_code& e,
std::size_t bytes_transferred);
void handleReadMsg(const boost::system::error_code& e,
std::size_t bytes_transferred);
/// Socket for the connection.
ssl_socket _socket;
/// The manager for this connection.
ConnectionManager& _connectionManager;
/// The handler used to process the incoming requests.
RequestHandler _requestHandler;
boost::asio::streambuf _inputStreamBuf;
boost::asio::streambuf _outputStreamBuf;
};
} // namespace Server
} // namespace LmsAPI
#endif
-62
View File
@@ -1,62 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <algorithm>
#include <boost/foreach.hpp>
#include "ConnectionManager.hpp"
namespace LmsAPI {
namespace Server {
ConnectionManager::ConnectionManager()
{
}
void
ConnectionManager::start(Connection::pointer c)
{
_connections.insert(c);
c->start();
}
void
ConnectionManager::stop(Connection::pointer c)
{
_connections.erase(c);
c->stop();
}
void
ConnectionManager::stopAll()
{
BOOST_FOREACH(Connection::pointer c, _connections)
{
c->stop();
}
_connections.clear();
}
} // namespace Server
} // namespace LmsAPI
-58
View File
@@ -1,58 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REMOTE_CONNECTION_MANAGER_HPP
#define REMOTE_CONNECTION_MANAGER_HPP
#include <set>
#include "Connection.hpp"
namespace LmsAPI {
namespace Server {
/// Manages open connections so that they may be cleanly stopped when the server
/// needs to shut down.
class ConnectionManager
{
public:
ConnectionManager(const ConnectionManager&) = delete;
ConnectionManager& operator=(const ConnectionManager&) = delete;
ConnectionManager();
/// Add the specified connection to the manager and start it.
void start(Connection::pointer c);
/// Stop the specified connection.
void stop(Connection::pointer c);
/// Stop all connections.
void stopAll();
private:
/// The managed connections.
std::set<Connection::pointer> _connections;
};
} // namespace Server
} // namespace LmsAPI
#endif
-217
View File
@@ -1,217 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "logger/Logger.hpp"
#include "MediaRequestHandler.hpp"
#include "database/Types.hpp"
namespace LmsAPI {
namespace Server {
MediaRequestHandler::MediaRequestHandler(Database::Handler& db)
: _db(db)
{}
bool
MediaRequestHandler::process(const MediaRequest& request, MediaResponse& response)
{
bool res = false;
switch (request.type())
{
case MediaRequest::TypeMediaPrepare:
if (request.has_prepare())
{
if (request.prepare().has_audio())
res = processAudioPrepare(request.prepare().audio(), *response.mutable_prepare_result());
else if (request.prepare().has_video())
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Video prepare not supported!";
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad MediaRequest::TypeMediaPrepare!";
if (res)
response.set_type(MediaResponse::TypePrepareResult);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad MediaRequest::TypeMediaPrepare!";
break;
case MediaRequest::TypeMediaGetPart:
if (request.has_get_part())
{
res = processGetPart(request.get_part(), *response.mutable_part_result());
if (res)
response.set_type(MediaResponse::TypePartResult);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad MediaRequest::TypeMediaGet!";
break;
case MediaRequest::TypeMediaTerminate:
if (request.has_terminate())
{
res = processTerminate(request.terminate(), *response.mutable_terminate_result());
if (res)
response.set_type(MediaResponse::TypePartResult);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad MediaRequest::TypeMediaTerminate!";
break;
default:
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Unhandled MediaRequest type = " << request.type();
}
return res;
}
bool
MediaRequestHandler::processAudioPrepare(const MediaRequest::Prepare::Audio& request, MediaResponse::PrepareResult& response)
{
std::size_t bitrate;
Transcode::Format::Encoding format;
switch( request.codec_type())
{
case MediaRequest::Prepare::AudioCodecTypeOGA: format = Transcode::Format::OGA; break;
default:
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Unhandled codec type = " << request.codec_type();
return false;
}
switch( request.bitrate() )
{
case MediaRequest::Prepare::AudioBitrate_32_kbps: bitrate = 32000; break;
case MediaRequest::Prepare::AudioBitrate_64_kbps: bitrate = 64000; break;
case MediaRequest::Prepare::AudioBitrate_96_kbps: bitrate = 96000; break;
case MediaRequest::Prepare::AudioBitrate_128_kbps: bitrate = 128000; break;
case MediaRequest::Prepare::AudioBitrate_192_kbps: bitrate = 192000; break;
case MediaRequest::Prepare::AudioBitrate_256_kbps: bitrate = 256000; break;
default:
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Unhandled bitrate type = " << request.bitrate();
return false;
}
// TODO use user's bitrate limits!
// TODO limit transcoder number by user?
if (_transcoders.size() + 1 > _maxTranscoders)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Transcoder limit reached!" << std::endl;
// Just answer an empty response, dont delete existing trasncode jobs
return true;
}
try
{
Wt::Dbo::Transaction transaction( _db.getSession());
Database::Track::pointer track = Database::Track::getById( _db.getSession(), request.track_id() );
if (!track)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Requested track does not exist" << std::endl;
// Track does no longer exist, just answer an empty response
return true;
}
Transcode::InputMediaFile inputFile(track->getPath());
Transcode::Parameters parameters(inputFile, Transcode::Format::get( format ));
parameters.setBitrate( Transcode::Stream::Audio, bitrate);
std::shared_ptr<Transcode::AvConvTranscoder> transcoder = std::make_shared<Transcode::AvConvTranscoder>( parameters );
// now get a unique id (relative to this connection!)
uint32_t handle = _curHandle++;
assert(_transcoders.find(handle) == _transcoders.end());
_transcoders[handle] = transcoder;
response.set_handle(handle);
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "Set up new transcode, handle = " << handle;
}
catch(std::exception& e)
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Caught exception: " << e.what();
return false;
}
return true;
}
bool
MediaRequestHandler::processGetPart(const MediaRequest::GetPart& request, MediaResponse::PartResult& response)
{
std::size_t dataSize = request.requested_data_size();
std::vector<unsigned char> data;
if (dataSize > _maxPartSize)
dataSize = _maxPartSize;
TranscoderMap::iterator itTranscoder = _transcoders.find(request.handle());
if (itTranscoder == _transcoders.end())
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "No transcoder found for handle " << request.handle();
return true;
}
std::shared_ptr<Transcode::AvConvTranscoder> transcoder = itTranscoder->second;
if (!transcoder->isComplete())
{
data.reserve(dataSize);
transcoder->process(data, dataSize);
}
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "MediaRequestHandler::processGetPart, handle = " << request.handle() << ", isComplete = " << std::boolalpha << transcoder->isComplete() << ", size = " << data.size();
std::copy(data.begin(), data.end(), std::back_inserter(*response.mutable_data()));
return true;
}
bool
MediaRequestHandler::processTerminate(const MediaRequest::Terminate& request, MediaResponse::TerminateResult& response)
{
LMS_LOG(MOD_REMOTE, SEV_DEBUG) << "MediaRequestHandler: resetting transcoder for handle " << request.handle();
if (_transcoders.find(request.handle()) == _transcoders.end())
{
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "No transcoder found for handle " << request.handle();
return true;
}
else
{
_transcoders.erase(request.handle());
}
return true;
}
} // namespace LmsAPI
} // namespace Server
@@ -1,65 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REMOTE_MEDIA_REQUEST_HANDLER
#define REMOTE_MEDIA_REQUEST_HANDLER
#include <map>
#include <memory>
#include "database/DatabaseHandler.hpp"
#include "transcode/AvConvTranscoder.hpp"
#include "media.pb.h"
namespace LmsAPI {
namespace Server {
class MediaRequestHandler
{
public:
MediaRequestHandler(Database::Handler& db);
bool process(const MediaRequest& request, MediaResponse& response);
private:
bool processAudioPrepare(const MediaRequest::Prepare::Audio& request, MediaResponse::PrepareResult& response);
bool processGetPart(const MediaRequest::GetPart& request, MediaResponse::PartResult& response);
bool processTerminate(const MediaRequest::Terminate& request, MediaResponse::TerminateResult& response);
// bool processVideoPrepare(const AudioCollectionRequest::GetGenreList& request, AudioCollectionResponse::GenreList& response);
typedef std::map<uint32_t, std::shared_ptr<Transcode::AvConvTranscoder> > TranscoderMap;
TranscoderMap _transcoders;
Database::Handler& _db;
uint32_t _curHandle = 0;
static const std::size_t _maxPartSize = 65536 - 128;
static const std::size_t _maxTranscoders = 1;
};
} // namespace Server
} // namespace LmsAPI
#endif
-101
View File
@@ -1,101 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include "logger/Logger.hpp"
#include "RequestHandler.hpp"
namespace LmsAPI {
namespace Server {
RequestHandler::RequestHandler(Wt::Dbo::SqlConnectionPool &connectionPool)
: _db( connectionPool ),
_authRequestHandler(_db),
_audioCollectionRequestHandler(_db),
_mediaRequestHandler(_db)
{
}
RequestHandler::~RequestHandler()
{
// TODO manually log out user if needed?
_db.getLogin().logout();
}
bool
RequestHandler::process(const ClientMessage& request, ServerMessage& response)
{
bool res = false;
switch(request.type())
{
case ClientMessage::AuthRequest:
if (request.has_auth_request())
{
res = _authRequestHandler.process(request.auth_request(), *response.mutable_auth_response());
if (res)
response.set_type(ServerMessage::AuthResponse);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad ClientMessage::AuthRequest !";
break;
case ClientMessage::AudioCollectionRequest:
// Not allowed if the user is not logged in
if (_db.getLogin().loggedIn())
{
if (request.has_audio_collection_request())
{
res = _audioCollectionRequestHandler.process(request.audio_collection_request(), *response.mutable_audio_collection_response());
if (res)
response.set_type( ServerMessage::AudioCollectionResponse);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Bad ClientMessage::AudioCollectionRequest message!";
}
break;
case ClientMessage::MediaRequest:
// Not allowed if the user is not logged in
if (_db.getLogin().loggedIn())
{
if (request.has_media_request())
{
res = _mediaRequestHandler.process(request.media_request(), *response.mutable_media_response());
if (res)
response.set_type( ServerMessage::MediaResponse);
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Malformed ClientMessage::MediaRequest message!";
}
break;
default:
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "Unhandled message type = " << request.type();
}
return res;
}
} // namespace Server
} // namespace LmsAPI
-58
View File
@@ -1,58 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REMOTE_REQUEST_HANDLER
#define REMOTE_REQUEST_HANDLER
#include <Wt/Dbo/SqlConnectionPool>
#include "messages.pb.h"
#include "database/DatabaseHandler.hpp"
#include "AuthRequestHandler.hpp"
#include "AudioCollectionRequestHandler.hpp"
#include "MediaRequestHandler.hpp"
namespace LmsAPI {
namespace Server {
class RequestHandler
{
public:
RequestHandler(Wt::Dbo::SqlConnectionPool& connectionPool);
~RequestHandler();
bool process(const ClientMessage& request, ServerMessage& response);
private:
Database::Handler _db;
AuthRequestHandler _authRequestHandler;
AudioCollectionRequestHandler _audioCollectionRequestHandler;
MediaRequestHandler _mediaRequestHandler;
};
} // namespace Server
} // namespace LmsAPI
#endif
-112
View File
@@ -1,112 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#include <utility>
#include <boost/asio/placeholders.hpp>
#include <boost/bind.hpp>
#include "logger/Logger.hpp"
#include "Server.hpp"
namespace LmsAPI {
namespace Server {
Server::Server(const endpoint_type& bindEndpoint,
boost::filesystem::path certPath,
boost::filesystem::path privKeyPath,
boost::filesystem::path dhPath,
Wt::Dbo::SqlConnectionPool& connectionPool)
:
_acceptor(_ioService, bindEndpoint, true /*SO_REUSEADDR*/),
_connectionManager(),
_context(boost::asio::ssl::context::tlsv1_server),
_connectionPool(connectionPool)
{
_ioService.setThreadCount(1); // TODO parametrize
_context.set_options( boost::asio::ssl::context::default_workarounds // TODO check this thing
| boost::asio::ssl::context::single_dh_use
| boost::asio::ssl::context::no_sslv2
| boost::asio::ssl::context::no_sslv3
);
// context_.set_password_callback(boost::bind(&server::get_password, this));
_context.use_certificate_chain_file(certPath.string());
_context.use_private_key_file(privKeyPath.string(), boost::asio::ssl::context::pem);
_context.use_tmp_dh_file(dhPath.string());
}
void
Server::start()
{
// While the server is running, there is always at least one
// asynchronous operation outstanding: the asynchronous accept call waiting
// for new incoming connections.
asyncAccept();
_ioService.start();
}
void
Server::asyncAccept()
{
std::shared_ptr<Connection> newConnection = std::make_shared<Connection>(_ioService, _context, _connectionManager, _connectionPool);
_acceptor.async_accept(newConnection->getSocket(),
boost::bind(&Server::handleAccept, this, newConnection, boost::asio::placeholders::error));
}
void
Server::handleAccept(std::shared_ptr<Connection> newConnection, boost::system::error_code ec)
{
// Check whether the server was stopped before this
// completion handler had a chance to run.
if (!_acceptor.is_open())
{
return;
}
if (!ec)
{
_connectionManager.start(newConnection);
// Accept another connection
// TODO: add some limit?
asyncAccept();
}
else
LMS_LOG(MOD_REMOTE, SEV_ERROR) << "handleAccept: " << ec.message();
}
void
Server::stop()
{
// The server is stopped by cancelling all outstanding asynchronous
// operations.
_acceptor.close();
_connectionManager.stopAll();
_ioService.stop();
}
} // namespace Server
} // namespace LmsAPI
-82
View File
@@ -1,82 +0,0 @@
/*
* Copyright (C) 2013 Emeric Poupon
*
* This file is part of LMS.
*
* LMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* LMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with LMS. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef REMOTE_SERVER_HPP
#define REMOTE_SERVER_HPP
#include <Wt/WIOService>
#include <Wt/Dbo/SqlConnectionPool>
#include <boost/asio.hpp>
#include <boost/asio/ssl.hpp>
#include <boost/filesystem.hpp>
#include "Connection.hpp"
#include "ConnectionManager.hpp"
#include "RequestHandler.hpp"
namespace LmsAPI {
namespace Server {
class Server
{
public:
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
typedef boost::asio::ip::tcp::endpoint endpoint_type;
// Serve up data from the given database
Server(const endpoint_type& bindEndpoint,
boost::filesystem::path certPath,
boost::filesystem::path privKeyPath,
boost::filesystem::path dhPath,
Wt::Dbo::SqlConnectionPool& connectionPool);
// Run the server's io_service loop.
void start();
void stop();
private:
/// Perform an asynchronous accept operation.
void asyncAccept();
void handleAccept(std::shared_ptr<Connection> newConnection, boost::system::error_code ec);
Wt::WIOService _ioService;
/// Acceptor used to listen for incoming connections.
boost::asio::ip::tcp::acceptor _acceptor;
/// The connection manager which owns all live connections.
ConnectionManager _connectionManager;
boost::asio::ssl::context _context;
/// The database to be used for requests
Wt::Dbo::SqlConnectionPool& _connectionPool;
};
} // namespace Server
} // namespace LmsAPI
#endif
-2
View File
@@ -19,8 +19,6 @@
#include <boost/thread.hpp>
#include "config/ConfigReader.hpp"
#include "DatabaseUpdateService.hpp"
namespace Service {