diff --git a/App/Server/OpenAPIGenerator.cpp b/App/Server/OpenAPIGenerator.cpp index 88d4bb57..c7b76e28 100644 --- a/App/Server/OpenAPIGenerator.cpp +++ b/App/Server/OpenAPIGenerator.cpp @@ -31,10 +31,11 @@ using namespace DBM; QJsonObject OpenAPIGenerator::CachedJson; -QJsonObject initializeObject() +QJsonObject initializeObject(const QString &_host = "127.0.0.1", const quint16 _port = 80) { - if(ServerConfigs::BaseOpenAPIObjectFile.value().size()){ + if (ServerConfigs::BaseOpenAPIObjectFile.value().size()) + { QFile File(ServerConfigs::BaseOpenAPIObjectFile.value()); File.open(QIODevice::ReadOnly); if (File.isReadable() == false) @@ -43,7 +44,9 @@ QJsonObject initializeObject() if(JsonDoc.isNull() || JsonDoc.isObject() == false) throw exTargomanAPI("Invalid json reading from: <" + ServerConfigs::BaseOpenAPIObjectFile.value() + ">"); return JsonDoc.object(); - }else{ + } + else + { return QJsonObject({ { "swagger","2.0" }, { "info",QJsonObject({ @@ -52,7 +55,7 @@ QJsonObject initializeObject() { "description", "" }, { "contact", QJsonObject({{"email", "sample@example.com"}}) } }) }, - { "host", QString("127.0.0.1:%1").arg(ServerConfigs::ListenPort.value()) }, + { "host", QString("%1:%2").arg(_host).arg(_port) }, { "securityDefinitions", QJsonObject({ { "Bearer", QJsonObject({ { "type", "apiKey" }, @@ -74,14 +77,20 @@ QJsonObject initializeObject() } } -QJsonObject OpenAPIGenerator::retrieveJson() +QJsonObject OpenAPIGenerator::retrieveJson(const QString &_host, const quint16 _port) { if (OpenAPIGenerator::CachedJson.isEmpty() == false) - return OpenAPIGenerator::CachedJson; - /**/ - OpenAPIGenerator::CachedJson = initializeObject(); + { + QJsonObject Return = OpenAPIGenerator::CachedJson; + + Return["host"] = QString("%1:%2").arg(_host).arg(_port); + + return Return; + } + + OpenAPIGenerator::CachedJson = initializeObject(_host, _port); - if(OpenAPIGenerator::CachedJson.value("info").isObject() == false) + if (OpenAPIGenerator::CachedJson.value("info").isObject() == false) throw exHTTPInternalServerError("Invalid OpenAPI base json"); QJsonObject PathsObject; diff --git a/App/Server/OpenAPIGenerator.h b/App/Server/OpenAPIGenerator.h index 817815a1..7f02b295 100644 --- a/App/Server/OpenAPIGenerator.h +++ b/App/Server/OpenAPIGenerator.h @@ -18,28 +18,25 @@ ******************************************************************************/ /** * @author S.Mehran M.Ziabary + * @author Kambiz Zandi */ - #ifndef TARGOMAN_API_SERVER_OPENAPIGENERATOR_H #define TARGOMAN_API_SERVER_OPENAPIGENERATOR_H #include "RESTAPIRegistry.h" -namespace Targoman { -namespace API { -namespace Server { +namespace Targoman::API::Server { class OpenAPIGenerator { public: - static QJsonObject retrieveJson(); + static QJsonObject retrieveJson(const QString& _host = "127.0.0.1", const quint16 _port = 80); private: static QJsonObject CachedJson; }; -} -} -} +} //namespace Targoman::API::Server + #endif // TARGOMAN_API_SERVER_OPENAPIGENERATOR_H diff --git a/App/Server/RESTServer.cpp b/App/Server/RESTServer.cpp index f1e6bd10..8bcbeeec 100644 --- a/App/Server/RESTServer.cpp +++ b/App/Server/RESTServer.cpp @@ -39,7 +39,6 @@ #include "APICache.hpp" namespace Targoman::API { - namespace Server { using namespace Targoman::Common; @@ -51,68 +50,74 @@ static WebSocketServer gWSServer; #endif static clsUpdateAndPruneThread *gStatUpdateThread; -void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) { - if(this->IsStarted) - throw exTargomanInitialization("QRESTServer can be started one time only"); +void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) +{ + if (this->IsStarted) + throw exTargomanInitialization("RESTServer can be run single instance only"); this->fnIPInBlackList = _fnIPInBlackList; QString BasePath = ServerConfigs::BasePath.value(); - if(BasePath.endsWith('/') == false) - BasePath+='/'; + if (BasePath.endsWith('/') == false) + BasePath += '/'; - if(BasePath.startsWith('/') == false) - BasePath='/'+BasePath; + if (BasePath.startsWith('/') == false) + BasePath = '/' + BasePath; - if(ServerConfigs::CacheConnector.value().size() && QUrl::fromUserInput(ServerConfigs::CacheConnector.value()).isValid() == false) + if (ServerConfigs::CacheConnector.value().size() && QUrl::fromUserInput(ServerConfigs::CacheConnector.value()).isValid() == false) throw exRESTRegistry("Invalid connector url specified for central cache"); #ifdef TARGOMAN_API_REDIS_PROTOCOL - if(ServerConfigs::CacheConnector.value().startsWith(TARGOMAN_M2STR(QHTTP_REDIS_PROTOCOL))) + if (ServerConfigs::CacheConnector.value().startsWith(TARGOMAN_M2STR(QHTTP_REDIS_PROTOCOL))) CentralCache::setup(new clsRedisConnector(ServerConfigs::CacheConnector.value())); #endif - if(ServerConfigs::CacheConnector.value().size() && CentralCache::isValid() == false) + if (ServerConfigs::CacheConnector.value().size() && CentralCache::isValid() == false) throw exRESTRegistry("Unsupported cache connector protocol."); ServerConfigs::BasePathWithVersion = BasePath + ServerConfigs::Version.value(); - if(ServerConfigs::BasePathWithVersion.endsWith('/') == false) + if (ServerConfigs::BasePathWithVersion.endsWith('/') == false) ServerConfigs::BasePathWithVersion += '/'; this->IsStarted = true; - if(ServerConfigs::StatisticsInterval.value()){ + if (ServerConfigs::StatisticsInterval.value()) + { gStatUpdateThread = new clsUpdateAndPruneThread(); connect(gStatUpdateThread, &clsUpdateAndPruneThread::finished, gStatUpdateThread, &QObject::deleteLater); gStatUpdateThread->start(); } - - QObject::connect(&gHTTPServer, &QHttpServer::newConnection, [this](QHttpConnection* _con){ + QObject::connect(&gHTTPServer, &QHttpServer::newConnection, [this](QHttpConnection* _con) + { if (!this->validateConnection(_con->tcpSocket()->peerAddress(), _con->tcpSocket()->peerPort())) _con->killConnection(); }); QHostAddress ListenAddress = ServerConfigs::JustLocal.value() ? QHostAddress::LocalHost : QHostAddress::Any; - gHTTPServer.listen(ListenAddress, ServerConfigs::ListenPort.value(), [&, BasePath](QHttpRequest* _req, QHttpResponse* _res){ + gHTTPServer.listen(ListenAddress, ServerConfigs::ListenPort.value(), [&, BasePath](QHttpRequest* _req, QHttpResponse* _res) + { clsRequestHandler* RequestHandler = new clsRequestHandler(_req, _res); - try{ + try + { QString Path = _req->url().adjusted(QUrl::NormalizePathSegments | QUrl::RemoveAuthority ).path(QUrl::PrettyDecoded); - if(Path != _req->url().path()) + if (Path != _req->url().path()) return RequestHandler->redirect(Path, false); - if(ServerConfigs::PublicPath.value().size() && QFile::exists(ServerConfigs::PublicPath.value() + Path)) + if (ServerConfigs::PublicPath.value().size() && QFile::exists(ServerConfigs::PublicPath.value() + Path)) return RequestHandler->sendFile(ServerConfigs::PublicPath.value(), Path); - if(Path.startsWith(BasePath) == false) + if (Path.startsWith(BasePath) == false) return RequestHandler->sendError(qhttp::ESTATUS_NOT_FOUND, "Path not found: '" + Path + "'", true); - if(Path.startsWith(ServerConfigs::BasePathWithVersion) == false) + + if (Path.startsWith(ServerConfigs::BasePathWithVersion) == false) return RequestHandler->sendError(qhttp::ESTATUS_NOT_ACCEPTABLE, "Invalid Version or version not specified", true); - if(Path == ServerConfigs::BasePathWithVersion ) + + if (Path == ServerConfigs::BasePathWithVersion ) return RequestHandler->sendError(qhttp::ESTATUS_NOT_ACCEPTABLE, "No API call provided", true); TargomanLogInfo(7, @@ -127,14 +132,19 @@ void RESTServer::start(fnIsInBlackList_t _fnIPInBlackList) { "?"<< _req->url().query()); RequestHandler->process(Path.mid(ServerConfigs::BasePathWithVersion.size() - 1)); - }catch(exTargomanBase& ex){ + } + catch(exTargomanBase& ex) + { RequestHandler->sendError(static_cast(ex.httpCode()), ex.what(), ex.httpCode() >= 500); } }); - if(gHTTPServer.isListening()){ + if (gHTTPServer.isListening()) + { TargomanLogInfo(1, "REST Server is listening on "<IsStarted = false; - if(gStatUpdateThread) + if (gStatUpdateThread) gStatUpdateThread->quit(); } @@ -186,12 +196,14 @@ bool RESTServer::validateConnection(const QHostAddress& _peerAddress, quint16 _p { enuIPBlackListStatus::Type IPBlackListStatus = enuIPBlackListStatus::Unknown; - if(this->fnIPInBlackList && - (IPBlackListStatus = this->fnIPInBlackList(_peerAddress)) != enuIPBlackListStatus::Ok){ + if (this->fnIPInBlackList && + (IPBlackListStatus = this->fnIPInBlackList(_peerAddress)) != enuIPBlackListStatus::Ok) + { TargomanLogWarn(1,"Connection from " + _peerAddress.toString() + " was closed by security provider due to: "+enuIPBlackListStatus::toStr(IPBlackListStatus)); gServerStats.Blocked.inc(); return false; } + gServerStats.Connections.inc(); TargomanLogInfo(7, "New connection accepted from: "<<_peerAddress.toString()<<":"<<_peerPort); diff --git a/App/Server/appTargomanAPI.cpp b/App/Server/appTargomanAPI.cpp index 58f67a62..e823a64a 100644 --- a/App/Server/appTargomanAPI.cpp +++ b/App/Server/appTargomanAPI.cpp @@ -54,7 +54,8 @@ appTargomanAPI::appTargomanAPI(QObject *parent) : QObject(parent) void appTargomanAPI::slotExecute() { - try { + try + { // Load modules QMap RequiredDBs; @@ -62,8 +63,10 @@ void appTargomanAPI::slotExecute() if (LoadedModules.isEmpty()) throw exTargomanAPI("No module was loaded. Maybe you forgot to specify --plugins"); - foreach (auto Plugin, LoadedModules) { + foreach (auto Plugin, LoadedModules) + { intfPureModule* Module = qobject_cast(Plugin.Instance); + if (!Module) throw exInvalidAPIModule(QString("Seems that this an incorrect module: %1").arg(Plugin.File)); @@ -73,6 +76,7 @@ void appTargomanAPI::slotExecute() RESTAPIRegistry::registerRESTAPI(ModuleMethod.Module, ModuleMethod.Method); auto DBInfo = Module->requiredDB(); + if (DBInfo.Schema.size()) RequiredDBs.insert(Module->moduleBaseName(), DBInfo); @@ -91,12 +95,12 @@ void appTargomanAPI::slotExecute() && ServerConfigs::MasterDB::Schema.value().size()) { intfPureModule::stuDBInfo MasterDBInfo = { - ServerConfigs::MasterDB::Schema.value(), - ServerConfigs::MasterDB::Port.value(), - ServerConfigs::MasterDB::Host.value(), - ServerConfigs::MasterDB::User.value(), - ServerConfigs::MasterDB::Pass.value() - }; + ServerConfigs::MasterDB::Schema.value(), + ServerConfigs::MasterDB::Port.value(), + ServerConfigs::MasterDB::Host.value(), + ServerConfigs::MasterDB::User.value(), + ServerConfigs::MasterDB::Pass.value() + }; ConnectionStrings.insert(MasterDBInfo.toConnStr(/*true*/)); DBManager::clsDAC::setConnectionString(MasterDBInfo.toConnStr()); @@ -130,7 +134,8 @@ void appTargomanAPI::slotExecute() TargomanInfo(5, "\n" + RESTAPIRegistry::registeredAPIs("", true, true).join("\n")); } - catch(Targoman::Common::exTargomanBase& e) { + catch(Targoman::Common::exTargomanBase& e) + { TargomanLogError(e.what()); QCoreApplication::exit(-1); } diff --git a/App/Server/appTargomanAPI.h b/App/Server/appTargomanAPI.h index 0371b15c..fcf67a4c 100644 --- a/App/Server/appTargomanAPI.h +++ b/App/Server/appTargomanAPI.h @@ -18,28 +18,27 @@ ******************************************************************************/ /** * @author S. Mehran M. Ziabary + * @author Kambiz Zandi */ + #ifndef TARGOMAN_API_SERVER_APPTARGOMANAPI_H #define TARGOMAN_API_SERVER_APPTARGOMANAPI_H #include -namespace Targoman { -namespace API { -namespace Server { +namespace Targoman::API::Server { class appTargomanAPI : public QObject { Q_OBJECT + public: explicit appTargomanAPI(QObject *parent = nullptr); public slots: void slotExecute(); - }; -} -} -} +} //namespace Targoman::API::Server + #endif // TARGOMAN_API_SERVER_APPTARGOMANAPI_H diff --git a/App/Server/clsRequestHandler.cpp b/App/Server/clsRequestHandler.cpp index 2893c985..2e863896 100644 --- a/App/Server/clsRequestHandler.cpp +++ b/App/Server/clsRequestHandler.cpp @@ -39,9 +39,7 @@ #include "APICache.hpp" #include "OpenAPIGenerator.h" -namespace Targoman { -namespace API { -namespace Server { +namespace Targoman::API::Server { using namespace qhttp::server; using namespace Targoman::Common; @@ -52,12 +50,13 @@ clsRequestHandler::clsRequestHandler(QHttpRequest *_req, QHttpResponse *_res, QO Response(_res) {} -void clsRequestHandler::process(const QString& _api) { - this->Request->onData([this](QByteArray _data ){ - try { - TargomanLogInfo(7, - "posted data: " << - _data); +void clsRequestHandler::process(const QString& _api) +{ + this->Request->onData([this](QByteArray _data ) + { + try + { + TargomanLogInfo(7, "posted data: " << _data); QByteArray ContentType= this->Request->headers().value("content-type"); @@ -77,7 +76,8 @@ void clsRequestHandler::process(const QString& _api) { if (ContentLength > ServerConfigs::MaxUploadSize.value()) throw exHTTPPayloadTooLarge(QString("Content-Size is too large: %d").arg(ContentLength)); - switch(this->Request->method()) { + switch(this->Request->method()) + { case qhttp::EHTTP_POST: case qhttp::EHTTP_PUT: case qhttp::EHTTP_PATCH: @@ -90,37 +90,48 @@ void clsRequestHandler::process(const QString& _api) { static constexpr char APPLICATION_FORM_HEADER[] = "application/x-www-form-urlencoded"; static constexpr char MULTIPART_BOUNDARY_HEADER[] = "multipart/form-data; boundary="; - switch (ContentType.at(0)) { - case 'a': { + switch (ContentType.at(0)) + { + case 'a': + { if (ContentType != APPLICATION_JSON_HEADER && ContentType != APPLICATION_FORM_HEADER) throw exHTTPBadRequest(("unsupported Content-Type: " + ContentType).constData()); - if (_data.size() == ContentLength) { + if (_data.size() == ContentLength) + { this->RemainingData = _data; } - else if (this->RemainingData.size()) { + else if (this->RemainingData.size()) + { this->RemainingData += _data; if(this->RemainingData.size() < ContentLength) return; } - else { + else + { this->RemainingData = _data; return; } this->RemainingData = this->RemainingData.trimmed(); - if (this->RemainingData.startsWith('{') || this->RemainingData.startsWith('[')) { + if (this->RemainingData.startsWith('{') || this->RemainingData.startsWith('[')) + { if (this->RemainingData.startsWith('{') == false || this->RemainingData.endsWith('}') == false) throw exHTTPBadRequest("Invalid JSON Object"); + QJsonParseError Error; QJsonDocument JSON = QJsonDocument::fromJson(this->RemainingData, &Error); + if (JSON.isNull() || JSON.isObject() == false) throw exHTTPBadRequest(QString("Invalid JSON Object: %1").arg(Error.errorString())); + QJsonObject JSONObject = JSON.object(); + for (auto JSONObjectIter = JSONObject.begin(); JSONObjectIter != JSONObject.end(); - ++JSONObjectIter) { + ++JSONObjectIter) + { if (JSONObjectIter.value().isBool()) this->Request->addUserDefinedData(JSONObjectIter.key(), JSONObjectIter.value().toBool() ? "1" : "0"); else if (JSONObjectIter.value().isNull()) @@ -135,10 +146,12 @@ void clsRequestHandler::process(const QString& _api) { this->Request->addUserDefinedData(JSONObjectIter.key(), JSONObjectIter.value().toString()); } } - else { + else + { QList Params = this->RemainingData.split('&'); - static auto decodePercentEncoding = [](QByteArray& _value) { + static auto decodePercentEncoding = [](QByteArray& _value) + { _value = _value.replace("+"," "); QUrl URL = QUrl::fromPercentEncoding("http://127.0.0.1/?key=" + _value); _value=URL.query(QUrl::FullyDecoded).toUtf8(); @@ -146,7 +159,8 @@ void clsRequestHandler::process(const QString& _api) { return _value; }; - foreach (auto Param, Params) { + foreach (auto Param, Params) + { QList ParamParts = Param.split('='); if(ParamParts.size() != 2) throw exHTTPBadRequest("Invalid Param: " + Param); @@ -155,8 +169,10 @@ void clsRequestHandler::process(const QString& _api) { } break; } - case 'm': { - if (this->MultipartFormDataHandler.isNull()) { + case 'm': + { + if (this->MultipartFormDataHandler.isNull()) + { if (ContentType.startsWith(MULTIPART_BOUNDARY_HEADER) == false) throw exHTTPBadRequest(("unsupported Content-Type: " + ContentType + " must be " + MULTIPART_BOUNDARY_HEADER).constData()); @@ -168,8 +184,10 @@ void clsRequestHandler::process(const QString& _api) { } qlonglong Fed = 0; - while (!this->MultipartFormDataHandler->stopped() && _data.size() > Fed) { - do { + while (!this->MultipartFormDataHandler->stopped() && _data.size() > Fed) + { + do + { qulonglong Ret = this->MultipartFormDataHandler->feed(_data.mid(static_cast(Fed)).constData(), _data.size() - Fed); Fed += Ret; } while (Fed < _data.size() && !this->MultipartFormDataHandler->stopped()); @@ -183,44 +201,56 @@ void clsRequestHandler::process(const QString& _api) { } TargomanLogInfo(7, "request user defined values: "); - foreach (auto val, this->Request->userDefinedValues()) { + foreach (auto val, this->Request->userDefinedValues()) + { TargomanLogInfo(7, val.first << " : " << val.second); } } - catch(exTargomanBase& ex) { + catch(exTargomanBase& ex) + { this->sendError(static_cast(ex.httpCode()), ex.what(), ex.httpCode() >= 500); } - catch(exQFVRequiredParam &ex) { + catch(exQFVRequiredParam &ex) + { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), false); } - catch(exQFVInvalidValue &ex) { + catch(exQFVInvalidValue &ex) + { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), false); } - catch(std::exception &ex) { + catch(std::exception &ex) + { this->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, ex.what(), true); } }); - this->Request->onEnd([this, _api]() { - try { + this->Request->onEnd([this, _api]() + { + try + { if (this->Request->method() == qhttp::EHTTP_OPTIONS) this->sendCORSOptions(); else this->findAndCallAPI (_api); } - catch(exTargomanBase& ex) { + catch(exTargomanBase& ex) + { this->sendError(static_cast(ex.httpCode()), ex.what(), ex.httpCode() >= 500); } - catch(exQFVRequiredParam &ex) { + catch(exQFVRequiredParam &ex) + { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), false); } - catch(exQFVInvalidValue &ex) { + catch(exQFVInvalidValue &ex) + { this->sendError(qhttp::ESTATUS_BAD_REQUEST, ex.what(), false); } - catch(std::exception &ex) { + catch(std::exception &ex) + { this->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, ex.what(), true); } - catch(...) { + catch(...) + { this->sendError(qhttp::ESTATUS_INTERNAL_SERVER_ERROR, "", true); } }); @@ -340,12 +370,43 @@ clsRequestHandler::stuResult clsRequestHandler::run(clsAPIObject* _apiObject, QS } } +QString clsRequestHandler::host() const +{ + const qhttp::THeaderHash headers = this->Request->headers(); + + if (headers.has("host") == false) + return "127.0.0.1"; + + QString Host = headers["host"]; + + int idx; + if ((idx = Host.indexOf(":")) >= 0) + Host = Host.left(idx); + + return Host; +} +quint16 clsRequestHandler::port() const +{ + const qhttp::THeaderHash headers = this->Request->headers(); + + if (headers.has("host") == false) + return ServerConfigs::ListenPort.value(); + + QString Host = headers["host"]; + + int idx; + if ((idx = Host.indexOf(":")) < 0) + return 80; + + return Host.mid(idx+1).toUInt(); +} + bool clsRequestHandler::callStaticAPI(QString _api) { if (_api == "/openAPI.json") { gServerStats.Success.inc(); - this->sendResponseBase(qhttp::ESTATUS_OK, OpenAPIGenerator::retrieveJson()); + this->sendResponseBase(qhttp::ESTATUS_OK, OpenAPIGenerator::retrieveJson(this->host(), this->port())); return true; } @@ -765,6 +826,4 @@ void clsUpdateAndPruneThread::run() this->exec(); } -} -} -} +} //namespace Targoman::API::Server diff --git a/App/Server/clsRequestHandler.h b/App/Server/clsRequestHandler.h index 197ec633..923cc75b 100644 --- a/App/Server/clsRequestHandler.h +++ b/App/Server/clsRequestHandler.h @@ -18,9 +18,9 @@ ******************************************************************************/ /** * @author S.Mehran M.Ziabary + * @author Kambiz Zandi */ - #ifndef TARGOMAN_API_SERVER_CLSREQUESTHANDLER_H #define TARGOMAN_API_SERVER_CLSREQUESTHANDLER_H @@ -32,24 +32,26 @@ #include "ServerConfigs.h" #include "RESTAPIRegistry.h" -namespace Targoman { -namespace API { -namespace Server { +namespace Targoman::API::Server { class clsRequestHandler; -class clsUpdateAndPruneThread : public QThread{ +class clsUpdateAndPruneThread : public QThread +{ Q_OBJECT + private: void run() Q_DECL_FINAL; }; -class clsMultipartFormDataRequestHandler : public MultipartReader{ +class clsMultipartFormDataRequestHandler : public MultipartReader +{ public: clsMultipartFormDataRequestHandler(clsRequestHandler* _parent, const QByteArray& _marker) : MultipartReader(_marker.toStdString()), pRequestHandler(_parent), - LastWrittenBytes(0){ + LastWrittenBytes(0) + { this->onPartBegin = clsMultipartFormDataRequestHandler::onMultiPartBegin; this->onPartData = clsMultipartFormDataRequestHandler::onMultiPartData; this->onPartEnd = clsMultipartFormDataRequestHandler::onMultiPartEnd; @@ -57,7 +59,8 @@ class clsMultipartFormDataRequestHandler : public MultipartReader{ this->userData = reinterpret_cast(this); } - size_t feed(const char *_buffer, long long _len){ + size_t feed(const char *_buffer, long long _len) + { return static_cast(MultipartReader::feed(_buffer, _len)); } @@ -86,7 +89,8 @@ class clsMultipartFormDataRequestHandler : public MultipartReader{ class clsRequestHandler : public QObject { Q_OBJECT - struct stuResult { + struct stuResult + { qhttp::TStatusCode StatusCode; QVariant Result; stuResult(const QVariant& _result = {}, qhttp::TStatusCode _code = qhttp::ESTATUS_OK) : @@ -100,8 +104,10 @@ class clsRequestHandler : public QObject qhttp::server::QHttpResponse* _res, QObject *_parent = nullptr); void process(const QString& _api); + private: bool callStaticAPI(QString _api); + public: void findAndCallAPI(QString _api); void sendError(qhttp::TStatusCode _code, @@ -112,6 +118,9 @@ class clsRequestHandler : public QObject void sendCORSOptions(); void redirect(const QString _path, bool _appendBase = true, bool _permananet = true); + QString host() const; + quint16 port() const; + private: void sendResponseBase(qhttp::TStatusCode _code, QJsonObject _dataObject, bool _closeConnection = false); stuResult run(clsAPIObject* _apiObject, QStringList& _queries, const QString& _pksByPath); @@ -133,10 +142,6 @@ private slots: friend class clsMultipartFormDataRequestHandler; }; -} -} -} +} //namespace Targoman::API::Server #endif // TARGOMAN_API_SERVER_CLSREQUESTHANDLER_H - - diff --git a/App/Server/main.cpp b/App/Server/main.cpp index 7863152f..c53e6e9d 100644 --- a/App/Server/main.cpp +++ b/App/Server/main.cpp @@ -18,6 +18,7 @@ ******************************************************************************/ /** * @author S.Mehran M.Ziabary + * @author Kambiz Zandi */ #include @@ -40,7 +41,6 @@ using namespace Targoman::API::Server; int main(int _argc, char *_argv[]) { /* - static const QVariant QNull = QVariant(QVariant::Line); static const QVariant QInvalid = QVariant(QVariant::Invalid); static const QVariant QRequired = QVariant(QVariant::RectF); @@ -60,7 +60,9 @@ int main(int _argc, char *_argv[]) compare(QAuto); exit(0);*/ - try{ + + try + { QCoreApplication App(_argc, _argv); #pragma GCC diagnostic push @@ -74,14 +76,18 @@ int main(int _argc, char *_argv[]) QTimer::singleShot(10, new appTargomanAPI, SLOT(slotExecute())); return App.exec(); - }catch(exTargomanBase& ex){ + } + catch(exTargomanBase& ex) + { TargomanError(ex.what()); - }catch (std::exception& ex){ + } + catch (std::exception& ex) + { TargomanError(ex.what()); - }catch(...){ + } + catch(...) + { TargomanError("FATAL Unrecognized exception"); } return -1; } - -