mirror-chatterino2/src/util/networkrequest.hpp

476 lines
15 KiB
C++
Raw Normal View History

2018-01-19 22:45:33 +01:00
#pragma once
#include "application.hpp"
2018-01-19 22:45:33 +01:00
#include "singletons/pathmanager.hpp"
#include "util/networkmanager.hpp"
#include "util/networkrequester.hpp"
#include "util/networkworker.hpp"
#include <rapidjson/document.h>
#include <rapidjson/error/en.h>
2018-01-19 22:45:33 +01:00
#include <QCryptographicHash>
#include <QFile>
namespace chatterino {
namespace util {
static QJsonObject parseJSONFromData(const QByteArray &data)
{
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
if (jsonDoc.isNull()) {
return QJsonObject();
}
return jsonDoc.object();
}
static rapidjson::Document parseJSONFromData2(const QByteArray &data)
{
rapidjson::Document ret(rapidjson::kNullType);
rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) {
debug::Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset());
return ret;
}
return ret;
}
static rapidjson::Document parseJSONFromReply2(QNetworkReply *reply)
{
rapidjson::Document ret(rapidjson::kNullType);
if (reply->error() != QNetworkReply::NetworkError::NoError) {
return ret;
}
QByteArray data = reply->readAll();
rapidjson::ParseResult result = ret.Parse(data.data(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) {
debug::Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset());
return ret;
}
return ret;
}
class NetworkRequest
{
public:
enum RequestType {
2018-05-12 19:50:22 +02:00
GetRequest,
PostRequest,
PutRequest,
DeleteRequest,
};
private:
2018-01-19 22:45:33 +01:00
struct Data {
QNetworkRequest request;
const QObject *caller = nullptr;
std::function<void(QNetworkReply *)> onReplyCreated;
int timeoutMS = -1;
bool useQuickLoadCache = false;
std::function<bool(int)> onError;
std::function<bool(const rapidjson::Document &)> onSuccess;
NetworkRequest::RequestType requestType;
QByteArray payload;
2018-01-19 22:45:33 +01:00
QString getHash()
{
if (this->hash.isEmpty()) {
QByteArray bytes;
bytes.append(this->request.url().toString());
for (const auto &header : this->request.rawHeaderList()) {
bytes.append(header);
}
QByteArray hashBytes(QCryptographicHash::hash(bytes, QCryptographicHash::Sha256));
this->hash = hashBytes.toHex();
}
return this->hash;
}
void writeToCache(const QByteArray &bytes);
private:
QString hash;
} data;
public:
NetworkRequest() = delete;
explicit NetworkRequest(const char *url);
explicit NetworkRequest(const std::string &url);
explicit NetworkRequest(const QString &url);
void setRequestType(RequestType newRequestType)
{
this->data.requestType = newRequestType;
}
template <typename Func>
void onError(Func cb)
{
this->data.onError = cb;
}
template <typename Func>
void onSuccess(Func cb)
{
this->data.onSuccess = cb;
}
void setPayload(const QByteArray &payload)
{
this->data.payload = payload;
}
2018-01-19 22:45:33 +01:00
void setUseQuickLoadCache(bool value);
void setCaller(const QObject *_caller)
{
this->data.caller = _caller;
}
void setOnReplyCreated(std::function<void(QNetworkReply *)> f)
{
this->data.onReplyCreated = f;
}
void setRawHeader(const char *headerName, const char *value)
{
this->data.request.setRawHeader(headerName, value);
}
void setRawHeader(const char *headerName, const QByteArray &value)
2018-01-19 22:45:33 +01:00
{
this->data.request.setRawHeader(headerName, value);
}
void setRawHeader(const char *headerName, const QString &value)
{
this->data.request.setRawHeader(headerName, value.toUtf8());
}
2018-01-19 22:45:33 +01:00
void setTimeout(int ms)
{
this->data.timeoutMS = ms;
}
void makeAuthorizedV5(const QString &clientID, const QString &oauthToken)
{
this->setRawHeader("Client-ID", clientID);
this->setRawHeader("Accept", "application/vnd.twitchtv.v5+json");
this->setRawHeader("Authorization", "OAuth " + oauthToken);
}
2018-01-19 22:45:33 +01:00
template <typename FinishedCallback>
void get(FinishedCallback onFinished)
{
if (this->data.useQuickLoadCache) {
auto app = getApp();
2018-01-19 22:45:33 +01:00
2018-06-21 13:02:34 +02:00
QFile cachedFile(app->paths->cacheDirectory + "/" + this->data.getHash());
2018-01-19 22:45:33 +01:00
if (cachedFile.exists()) {
if (cachedFile.open(QIODevice::ReadOnly)) {
QByteArray bytes = cachedFile.readAll();
// qDebug() << "Loaded cached resource" << this->data.request.url();
2018-01-19 23:41:02 +01:00
bool success = onFinished(bytes);
2018-01-19 22:45:33 +01:00
cachedFile.close();
if (!success) {
// The images were not successfully loaded from the file
// XXX: Invalidate the cache file so we don't attempt to load it again next
// time
}
2018-01-19 22:45:33 +01:00
}
}
}
QTimer *timer = nullptr;
if (this->data.timeoutMS > 0) {
timer = new QTimer;
}
NetworkRequester requester;
NetworkWorker *worker = new NetworkWorker;
worker->moveToThread(&NetworkManager::workerThread);
if (this->data.caller != nullptr) {
QObject::connect(worker, &NetworkWorker::doneUrl, this->data.caller,
2018-06-07 17:43:21 +02:00
[ onFinished, data = this->data ](auto reply) mutable {
2018-01-19 22:45:33 +01:00
if (reply->error() != QNetworkReply::NetworkError::NoError) {
// TODO: We might want to call an onError callback here
return;
}
QByteArray readBytes = reply->readAll();
QByteArray bytes;
bytes.setRawData(readBytes.data(), readBytes.size());
2018-01-19 22:45:33 +01:00
data.writeToCache(bytes);
2018-01-19 23:41:02 +01:00
onFinished(bytes);
2018-01-19 22:45:33 +01:00
reply->deleteLater();
});
}
if (timer != nullptr) {
timer->start(this->data.timeoutMS);
}
QObject::connect(
&requester, &NetworkRequester::requestUrl, worker,
2018-06-07 17:43:21 +02:00
[ timer, data = std::move(this->data), worker, onFinished{std::move(onFinished)} ]() {
2018-01-19 22:45:33 +01:00
QNetworkReply *reply = NetworkManager::NaM.get(data.request);
if (timer != nullptr) {
QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {
debug::Log("Aborted!");
reply->abort();
timer->deleteLater();
});
}
if (data.onReplyCreated) {
data.onReplyCreated(reply);
}
2018-06-07 17:43:21 +02:00
QObject::connect(reply, &QNetworkReply::finished, worker, [
data = std::move(data), worker, reply, onFinished = std::move(onFinished)
]() mutable {
if (data.caller == nullptr) {
QByteArray bytes = reply->readAll();
data.writeToCache(bytes);
onFinished(bytes);
reply->deleteLater();
} else {
emit worker->doneUrl(reply);
}
2018-06-07 17:43:21 +02:00
delete worker;
});
2018-01-19 22:45:33 +01:00
});
emit requester.requestUrl();
}
template <typename FinishedCallback>
void getJSON(FinishedCallback onFinished)
{
2018-06-07 17:43:21 +02:00
this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes)->bool {
2018-01-19 22:45:33 +01:00
auto object = parseJSONFromData(bytes);
onFinished(object);
// XXX: Maybe return onFinished? For now I don't want to force onFinished to have a
// return value
return true;
2018-01-19 22:45:33 +01:00
});
}
template <typename FinishedCallback>
void getJSON2(FinishedCallback onFinished)
{
2018-06-07 17:43:21 +02:00
this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes)->bool {
2018-01-19 22:45:33 +01:00
auto object = parseJSONFromData2(bytes);
onFinished(object);
// XXX: Maybe return onFinished? For now I don't want to force onFinished to have a
// return value
return true;
2018-01-19 22:45:33 +01:00
});
}
void execute()
{
switch (this->data.requestType) {
2018-05-12 19:50:22 +02:00
case GetRequest: {
2018-05-12 19:50:22 +02:00
debug::Log("Call GET request!");
this->executeGet();
} break;
2018-05-12 19:50:22 +02:00
case PutRequest: {
debug::Log("Call PUT request!");
this->executePut();
} break;
2018-05-12 19:50:22 +02:00
case DeleteRequest: {
debug::Log("Call DELETE request!");
this->executeDelete();
} break;
default: {
debug::Log("Unhandled request type {}", (int)this->data.requestType);
} break;
}
2018-05-16 15:42:45 +02:00
}
private:
void useCache()
{
if (this->data.useQuickLoadCache) {
auto app = getApp();
2018-06-21 13:02:34 +02:00
QFile cachedFile(app->paths->cacheDirectory + "/" + this->data.getHash());
if (cachedFile.exists()) {
if (cachedFile.open(QIODevice::ReadOnly)) {
QByteArray bytes = cachedFile.readAll();
// qDebug() << "Loaded cached resource" << this->data.request.url();
auto document = parseJSONFromData2(bytes);
bool success = false;
if (!document.IsNull()) {
success = this->data.onSuccess(document);
}
cachedFile.close();
if (!success) {
// The images were not successfully loaded from the file
// XXX: Invalidate the cache file so we don't attempt to load it again next
// time
}
}
}
}
}
void doRequest()
{
QTimer *timer = nullptr;
if (this->data.timeoutMS > 0) {
timer = new QTimer;
}
NetworkRequester requester;
NetworkWorker *worker = new NetworkWorker;
worker->moveToThread(&NetworkManager::workerThread);
if (this->data.caller != nullptr) {
2018-06-07 17:43:21 +02:00
QObject::connect(worker, &NetworkWorker::doneUrl,
this->data.caller, [data = this->data](auto reply) mutable {
if (reply->error() != QNetworkReply::NetworkError::NoError) {
2018-05-14 15:12:09 +02:00
if (data.onError) {
data.onError(reply->error());
}
return;
}
QByteArray readBytes = reply->readAll();
QByteArray bytes;
bytes.setRawData(readBytes.data(), readBytes.size());
data.writeToCache(bytes);
data.onSuccess(parseJSONFromData2(bytes));
reply->deleteLater();
});
2018-05-16 15:42:45 +02:00
}
if (timer != nullptr) {
timer->start(this->data.timeoutMS);
}
2018-05-16 15:42:45 +02:00
QObject::connect(&requester, &NetworkRequester::requestUrl, worker,
2018-06-07 17:43:21 +02:00
[ timer, data = std::move(this->data), worker ]() {
2018-05-16 15:42:45 +02:00
QNetworkReply *reply = nullptr;
switch (data.requestType) {
case GetRequest: {
reply = NetworkManager::NaM.get(data.request);
} break;
case PutRequest: {
reply = NetworkManager::NaM.put(data.request, data.payload);
} break;
case DeleteRequest: {
reply = NetworkManager::NaM.deleteResource(data.request);
} break;
}
if (reply == nullptr) {
debug::Log("Unhandled request type {}", (int)data.requestType);
return;
}
if (timer != nullptr) {
QObject::connect(timer, &QTimer::timeout, worker,
[reply, timer, data]() {
debug::Log("Aborted!");
reply->abort();
timer->deleteLater();
data.onError(-2);
});
}
if (data.onReplyCreated) {
data.onReplyCreated(reply);
}
QObject::connect(reply, &QNetworkReply::finished, worker,
2018-06-07 17:43:21 +02:00
[ data = std::move(data), worker, reply ]() mutable {
2018-05-16 15:42:45 +02:00
if (data.caller == nullptr) {
QByteArray bytes = reply->readAll();
data.writeToCache(bytes);
if (data.onSuccess) {
data.onSuccess(parseJSONFromData2(bytes));
} else {
qWarning() << "data.onSuccess not found";
}
2018-05-16 15:42:45 +02:00
reply->deleteLater();
} else {
emit worker->doneUrl(reply);
}
delete worker;
});
});
emit requester.requestUrl();
2018-05-16 15:42:45 +02:00
}
void executeGet()
{
this->useCache();
this->doRequest();
}
void executePut()
{
this->doRequest();
}
void executeDelete()
{
this->doRequest();
}
2018-05-16 15:42:45 +02:00
};
2018-01-19 22:45:33 +01:00
} // namespace util
} // namespace chatterino