mirror of
https://gitlab.com/comunic/comunicmessages
synced 2024-10-23 07:03:23 +00:00
71 lines
2.4 KiB
C++
71 lines
2.4 KiB
C++
|
#include <QUrlQuery>
|
||
|
#include <QJsonDocument>
|
||
|
|
||
|
#include "apihelper.h"
|
||
|
#include "../config.h"
|
||
|
|
||
|
APIHelper::APIHelper(QObject *parent) : QObject(parent)
|
||
|
{
|
||
|
|
||
|
//Make errors
|
||
|
QObject::connect(&mNetworkManager, &QNetworkAccessManager::sslErrors, this, &APIHelper::sslErrors);
|
||
|
}
|
||
|
|
||
|
void APIHelper::execute(APIRequest *request)
|
||
|
{
|
||
|
//Determine full request URL
|
||
|
QString requestURL = API_URL + request->URI();
|
||
|
|
||
|
//Add API credentials to parameters
|
||
|
request->addString("serviceName", API_SERVICE_NAME);
|
||
|
request->addString("serviceToken", API_SERVICE_TOKEN);
|
||
|
|
||
|
//Prepare request
|
||
|
//See this SO question to learn more : https://stackoverflow.com/questions/2599423
|
||
|
QUrlQuery queryData;
|
||
|
for(APIRequestParameter param : request->arguments())
|
||
|
queryData.addQueryItem(param.name(), param.value());
|
||
|
|
||
|
//Send request
|
||
|
QNetworkRequest networkRequest((QUrl(requestURL)));
|
||
|
networkRequest.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
|
||
|
QNetworkReply *reply = mNetworkManager.post(networkRequest, queryData.toString(QUrl::FullyEncoded).toUtf8());
|
||
|
|
||
|
//Make connections
|
||
|
connect(reply, &QNetworkReply::finished, this, &APIHelper::finished);
|
||
|
connect(reply, static_cast<void (QNetworkReply::*)(QNetworkReply::NetworkError)>(&QNetworkReply::error), this, &APIHelper::error);
|
||
|
|
||
|
//Add the request to the list
|
||
|
request->setNetworkReply(reply);
|
||
|
mRequestsList.append(request);
|
||
|
}
|
||
|
|
||
|
void APIHelper::finished()
|
||
|
{
|
||
|
if(qobject_cast<QNetworkReply *>(sender())->attribute(QNetworkRequest::HttpStatusCodeAttribute) != 200)
|
||
|
return;
|
||
|
|
||
|
//Get the API request related to this
|
||
|
APIRequest *request = mRequestsList.findForReply(qobject_cast<QNetworkReply *>(sender()), true);
|
||
|
|
||
|
//Process and return response
|
||
|
emit request->success(QJsonDocument::fromJson(request->networkReply()->readAll()));
|
||
|
}
|
||
|
|
||
|
void APIHelper::error()
|
||
|
{
|
||
|
//Get the API request related to this
|
||
|
APIRequest *request = mRequestsList.findForReply(qobject_cast<QNetworkReply *>(sender()), true);
|
||
|
|
||
|
//Try to determine error code
|
||
|
int response_code = request->networkReply()->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();
|
||
|
qWarning("An error occurred in an API request! (code: %d)", response_code);
|
||
|
|
||
|
emit request->error(response_code);
|
||
|
}
|
||
|
|
||
|
void APIHelper::sslErrors()
|
||
|
{
|
||
|
qWarning("APIHelper: the SSL/TLS session encountered an error!");
|
||
|
}
|