Refactor NetworkRequest class
Add followUser and unfollowUser methods to TwitchAccount
This commit is contained in:
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
|
||||
#include <functional>
|
||||
|
||||
class QNetworkReply;
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
class NetworkResult;
|
||||
|
||||
using NetworkSuccessCallback = std::function<bool(NetworkResult)>;
|
||||
using NetworkErrorCallback = std::function<bool(int)>;
|
||||
using NetworkReplyCreatedCallback = std::function<void(QNetworkReply *)>;
|
||||
|
||||
enum class NetworkRequestType {
|
||||
Get,
|
||||
Post,
|
||||
Put,
|
||||
Delete,
|
||||
};
|
||||
|
||||
} // namespace chatterino
|
||||
@@ -0,0 +1,45 @@
|
||||
#include "common/NetworkData.hpp"
|
||||
|
||||
#include "Application.hpp"
|
||||
#include "singletons/Paths.hpp"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QFile>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
QString NetworkData::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 NetworkData::writeToCache(const QByteArray &bytes)
|
||||
{
|
||||
if (this->useQuickLoadCache_) {
|
||||
auto app = getApp();
|
||||
|
||||
QFile cachedFile(app->paths->cacheDirectory + "/" + this->getHash());
|
||||
|
||||
if (cachedFile.open(QIODevice::WriteOnly)) {
|
||||
cachedFile.write(bytes);
|
||||
|
||||
cachedFile.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace chatterino
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include "common/NetworkCommon.hpp"
|
||||
|
||||
#include <QNetworkRequest>
|
||||
|
||||
#include <functional>
|
||||
|
||||
class QNetworkReply;
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
class NetworkResult;
|
||||
|
||||
struct NetworkData {
|
||||
QNetworkRequest request_;
|
||||
const QObject *caller_ = nullptr;
|
||||
bool useQuickLoadCache_{};
|
||||
|
||||
NetworkReplyCreatedCallback onReplyCreated_;
|
||||
NetworkErrorCallback onError_;
|
||||
NetworkSuccessCallback onSuccess_;
|
||||
|
||||
NetworkRequestType requestType_ = NetworkRequestType::Get;
|
||||
|
||||
QByteArray payload_;
|
||||
|
||||
QString getHash();
|
||||
|
||||
void writeToCache(const QByteArray &bytes);
|
||||
|
||||
private:
|
||||
QString hash_;
|
||||
};
|
||||
|
||||
} // namespace chatterino
|
||||
+153
-153
@@ -1,62 +1,78 @@
|
||||
#include "common/NetworkRequest.hpp"
|
||||
|
||||
#include "Application.hpp"
|
||||
#include "common/NetworkManager.hpp"
|
||||
#include "providers/twitch/TwitchCommon.hpp"
|
||||
#include "singletons/Paths.hpp"
|
||||
|
||||
#include <QFile>
|
||||
|
||||
#include <cassert>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
NetworkRequest::NetworkRequest(const char *url)
|
||||
NetworkRequest::NetworkRequest(const std::string &url, NetworkRequestType requestType)
|
||||
: timer(new NetworkTimer)
|
||||
{
|
||||
this->data.request.setUrl(QUrl(url));
|
||||
this->data.request_.setUrl(QUrl(QString::fromStdString(url)));
|
||||
this->data.requestType_ = requestType;
|
||||
}
|
||||
|
||||
NetworkRequest::NetworkRequest(const std::string &url)
|
||||
NetworkRequest::NetworkRequest(QUrl url, NetworkRequestType requestType)
|
||||
: timer(new NetworkTimer)
|
||||
{
|
||||
this->data.request.setUrl(QUrl(QString::fromStdString(url)));
|
||||
this->data.request_.setUrl(url);
|
||||
this->data.requestType_ = requestType;
|
||||
}
|
||||
|
||||
NetworkRequest::NetworkRequest(const QString &url)
|
||||
NetworkRequest::~NetworkRequest()
|
||||
{
|
||||
this->data.request.setUrl(QUrl(url));
|
||||
assert(this->executed_);
|
||||
}
|
||||
|
||||
NetworkRequest::NetworkRequest(QUrl url)
|
||||
void NetworkRequest::setRequestType(NetworkRequestType newRequestType)
|
||||
{
|
||||
this->data.request.setUrl(url);
|
||||
}
|
||||
|
||||
void NetworkRequest::setRequestType(RequestType newRequestType)
|
||||
{
|
||||
this->data.requestType = newRequestType;
|
||||
this->data.requestType_ = newRequestType;
|
||||
}
|
||||
|
||||
void NetworkRequest::setCaller(const QObject *caller)
|
||||
{
|
||||
this->data.caller = caller;
|
||||
this->data.caller_ = caller;
|
||||
}
|
||||
|
||||
void NetworkRequest::setOnReplyCreated(std::function<void(QNetworkReply *)> f)
|
||||
void NetworkRequest::onReplyCreated(NetworkReplyCreatedCallback cb)
|
||||
{
|
||||
this->data.onReplyCreated = f;
|
||||
this->data.onReplyCreated_ = cb;
|
||||
}
|
||||
|
||||
void NetworkRequest::onError(NetworkErrorCallback cb)
|
||||
{
|
||||
this->data.onError_ = cb;
|
||||
}
|
||||
|
||||
void NetworkRequest::onSuccess(NetworkSuccessCallback cb)
|
||||
{
|
||||
this->data.onSuccess_ = cb;
|
||||
}
|
||||
|
||||
void NetworkRequest::setRawHeader(const char *headerName, const char *value)
|
||||
{
|
||||
this->data.request.setRawHeader(headerName, value);
|
||||
this->data.request_.setRawHeader(headerName, value);
|
||||
}
|
||||
|
||||
void NetworkRequest::setRawHeader(const char *headerName, const QByteArray &value)
|
||||
{
|
||||
this->data.request.setRawHeader(headerName, value);
|
||||
this->data.request_.setRawHeader(headerName, value);
|
||||
}
|
||||
|
||||
void NetworkRequest::setRawHeader(const char *headerName, const QString &value)
|
||||
{
|
||||
this->data.request.setRawHeader(headerName, value.toUtf8());
|
||||
this->data.request_.setRawHeader(headerName, value.toUtf8());
|
||||
}
|
||||
|
||||
void NetworkRequest::setTimeout(int ms)
|
||||
{
|
||||
this->data.timeoutMS = ms;
|
||||
this->timer->timeoutMS_ = ms;
|
||||
}
|
||||
|
||||
void NetworkRequest::makeAuthorizedV5(const QString &clientID, const QString &oauthToken)
|
||||
@@ -68,190 +84,174 @@ void NetworkRequest::makeAuthorizedV5(const QString &clientID, const QString &oa
|
||||
}
|
||||
}
|
||||
|
||||
void NetworkRequest::setUseQuickLoadCache(bool value)
|
||||
void NetworkRequest::setPayload(const QByteArray &payload)
|
||||
{
|
||||
this->data.useQuickLoadCache = value;
|
||||
this->data.payload_ = payload;
|
||||
}
|
||||
|
||||
void NetworkRequest::Data::writeToCache(const QByteArray &bytes)
|
||||
void NetworkRequest::setUseQuickLoadCache(bool value)
|
||||
{
|
||||
if (this->useQuickLoadCache) {
|
||||
auto app = getApp();
|
||||
|
||||
QFile cachedFile(app->paths->cacheDirectory + "/" + this->getHash());
|
||||
|
||||
if (cachedFile.open(QIODevice::WriteOnly)) {
|
||||
cachedFile.write(bytes);
|
||||
|
||||
cachedFile.close();
|
||||
}
|
||||
}
|
||||
this->data.useQuickLoadCache_ = value;
|
||||
}
|
||||
|
||||
void NetworkRequest::execute()
|
||||
{
|
||||
switch (this->data.requestType) {
|
||||
case GetRequest: {
|
||||
this->executeGet();
|
||||
this->executed_ = true;
|
||||
|
||||
switch (this->data.requestType_) {
|
||||
case NetworkRequestType::Get: {
|
||||
// Get requests try to load from cache, then perform the request
|
||||
if (this->data.useQuickLoadCache_) {
|
||||
if (this->tryLoadCachedFile()) {
|
||||
Log("Loaded from cache");
|
||||
// Successfully loaded from cache
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
this->doRequest();
|
||||
} break;
|
||||
|
||||
case PutRequest: {
|
||||
this->executePut();
|
||||
case NetworkRequestType::Put: {
|
||||
// Put requests cannot be cached, therefore the request is called immediately
|
||||
this->doRequest();
|
||||
} break;
|
||||
|
||||
case DeleteRequest: {
|
||||
this->executeDelete();
|
||||
case NetworkRequestType::Delete: {
|
||||
// Delete requests cannot be cached, therefore the request is called immediately
|
||||
this->doRequest();
|
||||
} break;
|
||||
|
||||
default: {
|
||||
Log("[Execute] Unhandled request type {}", (int)this->data.requestType);
|
||||
Log("[Execute] Unhandled request type");
|
||||
} break;
|
||||
}
|
||||
}
|
||||
|
||||
void NetworkRequest::useCache()
|
||||
bool NetworkRequest::tryLoadCachedFile()
|
||||
{
|
||||
if (this->data.useQuickLoadCache) {
|
||||
auto app = getApp();
|
||||
auto app = getApp();
|
||||
|
||||
QFile cachedFile(app->paths->cacheDirectory + "/" + this->data.getHash());
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!cachedFile.exists()) {
|
||||
// File didn't exist
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!cachedFile.open(QIODevice::ReadOnly)) {
|
||||
// File could not be opened
|
||||
return false;
|
||||
}
|
||||
|
||||
QByteArray bytes = cachedFile.readAll();
|
||||
NetworkResult result(bytes);
|
||||
|
||||
bool success = this->data.onSuccess_(result);
|
||||
|
||||
cachedFile.close();
|
||||
|
||||
// XXX: If success is false, we should invalidate the cache file somehow/somewhere
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
void NetworkRequest::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) {
|
||||
QObject::connect(worker, &NetworkWorker::doneUrl, this->data.caller,
|
||||
[data = this->data](auto reply) mutable {
|
||||
if (reply->error() != QNetworkReply::NetworkError::NoError) {
|
||||
if (data.onError) {
|
||||
data.onError(reply->error());
|
||||
}
|
||||
return;
|
||||
}
|
||||
this->timer->start();
|
||||
|
||||
QByteArray readBytes = reply->readAll();
|
||||
QByteArray bytes;
|
||||
bytes.setRawData(readBytes.data(), readBytes.size());
|
||||
data.writeToCache(bytes);
|
||||
data.onSuccess(parseJSONFromData2(bytes));
|
||||
auto onUrlRequested = [data = std::move(this->data), timer = std::move(this->timer),
|
||||
worker]() mutable {
|
||||
QNetworkReply *reply = nullptr;
|
||||
switch (data.requestType_) {
|
||||
case NetworkRequestType::Get: {
|
||||
reply = NetworkManager::NaM.get(data.request_);
|
||||
} break;
|
||||
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
case NetworkRequestType::Put: {
|
||||
reply = NetworkManager::NaM.put(data.request_, data.payload_);
|
||||
} break;
|
||||
|
||||
if (timer != nullptr) {
|
||||
timer->start(this->data.timeoutMS);
|
||||
}
|
||||
case NetworkRequestType::Delete: {
|
||||
reply = NetworkManager::NaM.deleteResource(data.request_);
|
||||
} break;
|
||||
}
|
||||
|
||||
QObject::connect(&requester, &NetworkRequester::requestUrl, worker,
|
||||
[timer, data = std::move(this->data), worker]() {
|
||||
QNetworkReply *reply = nullptr;
|
||||
switch (data.requestType) {
|
||||
case GetRequest: {
|
||||
reply = NetworkManager::NaM.get(data.request);
|
||||
} break;
|
||||
if (reply == nullptr) {
|
||||
Log("Unhandled request type");
|
||||
return;
|
||||
}
|
||||
|
||||
case PutRequest: {
|
||||
reply = NetworkManager::NaM.put(data.request, data.payload);
|
||||
} break;
|
||||
if (timer->isStarted()) {
|
||||
timer->onTimeout(worker, [reply, data]() {
|
||||
Log("Aborted!");
|
||||
reply->abort();
|
||||
if (data.onError_) {
|
||||
data.onError_(-2);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
case DeleteRequest: {
|
||||
reply = NetworkManager::NaM.deleteResource(data.request);
|
||||
} break;
|
||||
}
|
||||
if (data.onReplyCreated_) {
|
||||
data.onReplyCreated_(reply);
|
||||
}
|
||||
|
||||
if (reply == nullptr) {
|
||||
Log("Unhandled request type {}", (int)data.requestType);
|
||||
return;
|
||||
}
|
||||
bool directAction = (data.caller_ == nullptr);
|
||||
|
||||
if (timer != nullptr) {
|
||||
QObject::connect(timer, &QTimer::timeout, worker,
|
||||
[reply, timer, data]() {
|
||||
Log("Aborted!");
|
||||
reply->abort();
|
||||
timer->deleteLater();
|
||||
data.onError(-2);
|
||||
});
|
||||
}
|
||||
auto handleReply = [data = std::move(data), timer = std::move(timer), reply]() mutable {
|
||||
if (reply->error() != QNetworkReply::NetworkError::NoError) {
|
||||
if (data.onError_) {
|
||||
data.onError_(reply->error());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.onReplyCreated) {
|
||||
data.onReplyCreated(reply);
|
||||
}
|
||||
QByteArray readBytes = reply->readAll();
|
||||
QByteArray bytes;
|
||||
bytes.setRawData(readBytes.data(), readBytes.size());
|
||||
data.writeToCache(bytes);
|
||||
|
||||
QObject::connect(reply, &QNetworkReply::finished, worker,
|
||||
[data = std::move(data), worker, reply]() mutable {
|
||||
if (data.caller == nullptr) {
|
||||
QByteArray bytes = reply->readAll();
|
||||
data.writeToCache(bytes);
|
||||
NetworkResult result(bytes);
|
||||
data.onSuccess_(result);
|
||||
|
||||
if (data.onSuccess) {
|
||||
data.onSuccess(parseJSONFromData2(bytes));
|
||||
} else {
|
||||
qWarning() << "data.onSuccess not found";
|
||||
}
|
||||
reply->deleteLater();
|
||||
};
|
||||
|
||||
reply->deleteLater();
|
||||
} else {
|
||||
emit worker->doneUrl(reply);
|
||||
}
|
||||
if (data.caller_ != nullptr) {
|
||||
QObject::connect(worker, &NetworkWorker::doneUrl, data.caller_, std::move(handleReply));
|
||||
QObject::connect(reply, &QNetworkReply::finished, worker, [worker]() mutable {
|
||||
emit worker->doneUrl();
|
||||
|
||||
delete worker;
|
||||
});
|
||||
});
|
||||
delete worker;
|
||||
});
|
||||
} else {
|
||||
QObject::connect(reply, &QNetworkReply::finished, worker,
|
||||
[handleReply = std::move(handleReply), worker]() mutable {
|
||||
handleReply();
|
||||
|
||||
delete worker;
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
QObject::connect(&requester, &NetworkRequester::requestUrl, worker, std::move(onUrlRequested));
|
||||
|
||||
emit requester.requestUrl();
|
||||
}
|
||||
|
||||
void NetworkRequest::executeGet()
|
||||
// Helper creator functions
|
||||
NetworkRequest NetworkRequest::twitchRequest(QUrl url)
|
||||
{
|
||||
this->useCache();
|
||||
NetworkRequest request(url);
|
||||
|
||||
this->doRequest();
|
||||
request.makeAuthorizedV5(getDefaultClientID());
|
||||
|
||||
return request;
|
||||
}
|
||||
|
||||
void NetworkRequest::executePut()
|
||||
{
|
||||
this->doRequest();
|
||||
}
|
||||
|
||||
void NetworkRequest::executeDelete()
|
||||
{
|
||||
this->doRequest();
|
||||
}
|
||||
} // namespace chatterino
|
||||
|
||||
+35
-213
@@ -1,248 +1,70 @@
|
||||
#pragma once
|
||||
|
||||
#include "Application.hpp"
|
||||
#include "common/NetworkManager.hpp"
|
||||
#include "common/NetworkCommon.hpp"
|
||||
#include "common/NetworkData.hpp"
|
||||
#include "common/NetworkRequester.hpp"
|
||||
#include "common/NetworkResult.hpp"
|
||||
#include "common/NetworkTimer.hpp"
|
||||
#include "common/NetworkWorker.hpp"
|
||||
#include "singletons/Paths.hpp"
|
||||
|
||||
#include <rapidjson/document.h>
|
||||
#include <rapidjson/error/en.h>
|
||||
#include <QCryptographicHash>
|
||||
#include <QFile>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
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) {
|
||||
Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
|
||||
result.Offset());
|
||||
return ret;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
class NetworkRequest
|
||||
{
|
||||
public:
|
||||
enum RequestType {
|
||||
GetRequest,
|
||||
PostRequest,
|
||||
PutRequest,
|
||||
DeleteRequest,
|
||||
};
|
||||
// Stores all data about the request that needs to be passed around to each part of the request
|
||||
NetworkData data;
|
||||
|
||||
private:
|
||||
struct Data {
|
||||
QNetworkRequest request;
|
||||
const QObject *caller = nullptr;
|
||||
std::function<void(QNetworkReply *)> onReplyCreated;
|
||||
int timeoutMS = -1;
|
||||
bool useQuickLoadCache = false;
|
||||
// Timer that tracks the timeout
|
||||
// By default, there's no explicit timeout for the request
|
||||
// to enable the timer, the "setTimeout" function needs to be called before execute is called
|
||||
std::unique_ptr<NetworkTimer> timer;
|
||||
|
||||
std::function<bool(int)> onError;
|
||||
std::function<bool(const rapidjson::Document &)> onSuccess;
|
||||
|
||||
NetworkRequest::RequestType requestType;
|
||||
|
||||
QByteArray payload;
|
||||
|
||||
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;
|
||||
// The NetworkRequest destructor will assert if executed_ hasn't been set to true before dying
|
||||
bool executed_ = false;
|
||||
|
||||
public:
|
||||
NetworkRequest() = delete;
|
||||
explicit NetworkRequest(const char *url);
|
||||
explicit NetworkRequest(const std::string &url);
|
||||
explicit NetworkRequest(const QString &url);
|
||||
NetworkRequest(QUrl url);
|
||||
NetworkRequest(const NetworkRequest &other) = delete;
|
||||
NetworkRequest &operator=(const NetworkRequest &other) = delete;
|
||||
|
||||
void setRequestType(RequestType newRequestType);
|
||||
NetworkRequest(NetworkRequest &&other) = default;
|
||||
NetworkRequest &operator=(NetworkRequest &&other) = default;
|
||||
|
||||
template <typename Func>
|
||||
void onError(Func cb)
|
||||
{
|
||||
this->data.onError = cb;
|
||||
}
|
||||
explicit NetworkRequest(const std::string &url,
|
||||
NetworkRequestType requestType = NetworkRequestType::Get);
|
||||
NetworkRequest(QUrl url, NetworkRequestType requestType = NetworkRequestType::Get);
|
||||
|
||||
template <typename Func>
|
||||
void onSuccess(Func cb)
|
||||
{
|
||||
this->data.onSuccess = cb;
|
||||
}
|
||||
~NetworkRequest();
|
||||
|
||||
void setPayload(const QByteArray &payload)
|
||||
{
|
||||
this->data.payload = payload;
|
||||
}
|
||||
void setRequestType(NetworkRequestType newRequestType);
|
||||
|
||||
void onReplyCreated(NetworkReplyCreatedCallback cb);
|
||||
void onError(NetworkErrorCallback cb);
|
||||
void onSuccess(NetworkSuccessCallback cb);
|
||||
|
||||
void setPayload(const QByteArray &payload);
|
||||
void setUseQuickLoadCache(bool value);
|
||||
void setCaller(const QObject *caller);
|
||||
void setOnReplyCreated(std::function<void(QNetworkReply *)> f);
|
||||
void setRawHeader(const char *headerName, const char *value);
|
||||
void setRawHeader(const char *headerName, const QByteArray &value);
|
||||
void setRawHeader(const char *headerName, const QString &value);
|
||||
void setTimeout(int ms);
|
||||
void makeAuthorizedV5(const QString &clientID, const QString &oauthToken = QString());
|
||||
|
||||
template <typename FinishedCallback>
|
||||
void get(FinishedCallback onFinished)
|
||||
{
|
||||
if (this->data.useQuickLoadCache) {
|
||||
auto app = getApp();
|
||||
|
||||
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();
|
||||
|
||||
bool success = onFinished(bytes);
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
[onFinished, data = this->data](auto reply) mutable {
|
||||
if (reply->error() != QNetworkReply::NetworkError::NoError) {
|
||||
if (data.onError) {
|
||||
data.onError(reply->error());
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
QByteArray readBytes = reply->readAll();
|
||||
QByteArray bytes;
|
||||
bytes.setRawData(readBytes.data(), readBytes.size());
|
||||
data.writeToCache(bytes);
|
||||
onFinished(bytes);
|
||||
|
||||
reply->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
if (timer != nullptr) {
|
||||
timer->start(this->data.timeoutMS);
|
||||
}
|
||||
|
||||
QObject::connect(
|
||||
&requester, &NetworkRequester::requestUrl, worker,
|
||||
[timer, data = std::move(this->data), worker, onFinished{std::move(onFinished)}]() {
|
||||
QNetworkReply *reply = NetworkManager::NaM.get(data.request);
|
||||
|
||||
if (timer != nullptr) {
|
||||
QObject::connect(timer, &QTimer::timeout, worker, [reply, timer]() {
|
||||
Log("Aborted!");
|
||||
reply->abort();
|
||||
timer->deleteLater();
|
||||
});
|
||||
}
|
||||
|
||||
if (data.onReplyCreated) {
|
||||
data.onReplyCreated(reply);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
delete worker;
|
||||
});
|
||||
});
|
||||
|
||||
emit requester.requestUrl();
|
||||
}
|
||||
|
||||
template <typename FinishedCallback>
|
||||
void getJSON(FinishedCallback onFinished)
|
||||
{
|
||||
this->get([onFinished{std::move(onFinished)}](const QByteArray &bytes) -> bool {
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
void execute();
|
||||
|
||||
private:
|
||||
void useCache();
|
||||
// Returns true if the file was successfully loaded from cache
|
||||
// Returns false if the cache file either didn't exist, or it contained "invalid" data
|
||||
// "invalid" is specified by the onSuccess callback
|
||||
bool tryLoadCachedFile();
|
||||
|
||||
void doRequest();
|
||||
void executeGet();
|
||||
void executePut();
|
||||
void executeDelete();
|
||||
|
||||
public:
|
||||
// Helper creator functions
|
||||
static NetworkRequest twitchRequest(QUrl url);
|
||||
};
|
||||
|
||||
} // namespace chatterino
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
#include "common/NetworkResult.hpp"
|
||||
|
||||
#include "debug/Log.hpp"
|
||||
|
||||
#include <rapidjson/document.h>
|
||||
#include <rapidjson/error/en.h>
|
||||
#include <QJsonDocument>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
NetworkResult::NetworkResult(const QByteArray &data)
|
||||
: data_(data)
|
||||
{
|
||||
}
|
||||
|
||||
QJsonObject NetworkResult::parseJson() const
|
||||
{
|
||||
QJsonDocument jsonDoc(QJsonDocument::fromJson(this->data_));
|
||||
if (jsonDoc.isNull()) {
|
||||
return QJsonObject{};
|
||||
}
|
||||
|
||||
return jsonDoc.object();
|
||||
}
|
||||
|
||||
rapidjson::Document NetworkResult::parseRapidJson() const
|
||||
{
|
||||
rapidjson::Document ret(rapidjson::kNullType);
|
||||
|
||||
rapidjson::ParseResult result = ret.Parse(this->data_.data(), this->data_.length());
|
||||
|
||||
if (result.Code() != rapidjson::kParseErrorNone) {
|
||||
Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
|
||||
result.Offset());
|
||||
return ret;
|
||||
}
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
QByteArray NetworkResult::getData() const
|
||||
{
|
||||
return this->data_;
|
||||
}
|
||||
|
||||
} // namespace chatterino
|
||||
@@ -0,0 +1,20 @@
|
||||
#pragma once
|
||||
|
||||
#include <rapidjson/document.h>
|
||||
#include <QJsonObject>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
class NetworkResult
|
||||
{
|
||||
QByteArray data_;
|
||||
|
||||
public:
|
||||
NetworkResult(const QByteArray &data);
|
||||
|
||||
QJsonObject parseJson() const;
|
||||
rapidjson::Document parseRapidJson() const;
|
||||
QByteArray getData() const;
|
||||
};
|
||||
|
||||
} // namespace chatterino
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "common/NetworkWorker.hpp"
|
||||
|
||||
#include <QTimer>
|
||||
|
||||
#include <cassert>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
class NetworkTimer
|
||||
{
|
||||
std::unique_ptr<QTimer> timer_;
|
||||
|
||||
bool started_{};
|
||||
|
||||
public:
|
||||
int timeoutMS_ = -1;
|
||||
|
||||
NetworkTimer() = default;
|
||||
~NetworkTimer() = default;
|
||||
|
||||
NetworkTimer(const NetworkTimer &other) = delete;
|
||||
NetworkTimer &operator=(const NetworkTimer &other) = delete;
|
||||
|
||||
NetworkTimer(NetworkTimer &&other) = default;
|
||||
NetworkTimer &operator=(NetworkTimer &&other) = default;
|
||||
|
||||
void start()
|
||||
{
|
||||
if (this->timeoutMS_ <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
this->timer_ = std::make_unique<QTimer>();
|
||||
this->timer_->start(this->timeoutMS_);
|
||||
|
||||
this->started_ = true;
|
||||
}
|
||||
|
||||
bool isStarted() const
|
||||
{
|
||||
return this->started_;
|
||||
}
|
||||
|
||||
void onTimeout(NetworkWorker *worker, std::function<void()> cb) const
|
||||
{
|
||||
if (!this->timer_) {
|
||||
return;
|
||||
}
|
||||
|
||||
QObject::connect(this->timer_.get(), &QTimer::timeout, worker, cb);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace chatterino
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
#include <QObject>
|
||||
|
||||
class QNetworkReply;
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
class NetworkWorker : public QObject
|
||||
@@ -11,7 +9,7 @@ class NetworkWorker : public QObject
|
||||
Q_OBJECT
|
||||
|
||||
signals:
|
||||
void doneUrl(QNetworkReply *);
|
||||
void doneUrl();
|
||||
};
|
||||
|
||||
} // namespace chatterino
|
||||
|
||||
+15
-126
@@ -1,147 +1,36 @@
|
||||
#pragma once
|
||||
|
||||
#include "common/NetworkManager.hpp"
|
||||
#include "common/NetworkRequest.hpp"
|
||||
#include "controllers/accounts/AccountController.hpp"
|
||||
#include "debug/Log.hpp"
|
||||
#include "providers/twitch/TwitchCommon.hpp"
|
||||
|
||||
#include <rapidjson/document.h>
|
||||
#include <rapidjson/error/en.h>
|
||||
#include <rapidjson/error/error.h>
|
||||
#include <QByteArray>
|
||||
#include <QEventLoop>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QJsonValue>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QObject>
|
||||
#include <QString>
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace chatterino {
|
||||
|
||||
static void twitchApiGet(QString url, const QObject *caller,
|
||||
std::function<void(const QJsonObject &)> successCallback)
|
||||
{
|
||||
NetworkRequest req(url);
|
||||
req.setCaller(caller);
|
||||
req.setRawHeader("Client-ID", getDefaultClientID());
|
||||
req.setRawHeader("Accept", "application/vnd.twitchtv.v5+json");
|
||||
// Not sure if I like these, but I'm trying them out
|
||||
|
||||
req.getJSON([=](const QJsonObject &node) {
|
||||
successCallback(node); //
|
||||
});
|
||||
}
|
||||
|
||||
static void twitchApiGet2(QString url, const QObject *caller, bool useQuickLoadCache,
|
||||
std::function<void(const rapidjson::Document &)> successCallback)
|
||||
static NetworkRequest makeGetChannelRequest(const QString &channelId,
|
||||
const QObject *caller = nullptr)
|
||||
{
|
||||
NetworkRequest request(url);
|
||||
request.setRequestType(NetworkRequest::GetRequest);
|
||||
QString url("https://api.twitch.tv/kraken/channels/" + channelId);
|
||||
|
||||
auto request = NetworkRequest::twitchRequest(url);
|
||||
|
||||
request.setCaller(caller);
|
||||
request.makeAuthorizedV5(getDefaultClientID());
|
||||
request.setUseQuickLoadCache(useQuickLoadCache);
|
||||
|
||||
request.onSuccess([successCallback](const rapidjson::Document &document) {
|
||||
successCallback(document); //
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
request.execute();
|
||||
return request;
|
||||
}
|
||||
|
||||
static void twitchApiGetUserID(QString username, const QObject *caller,
|
||||
std::function<void(QString)> successCallback)
|
||||
static NetworkRequest makeGetStreamRequest(const QString &channelId,
|
||||
const QObject *caller = nullptr)
|
||||
{
|
||||
twitchApiGet(
|
||||
"https://api.twitch.tv/kraken/users?login=" + username, caller,
|
||||
[=](const QJsonObject &root) {
|
||||
if (!root.value("users").isArray()) {
|
||||
Log("API Error while getting user id, users is not an array");
|
||||
return;
|
||||
}
|
||||
QString url("https://api.twitch.tv/kraken/streams/" + channelId);
|
||||
|
||||
auto users = root.value("users").toArray();
|
||||
if (users.size() != 1) {
|
||||
Log("API Error while getting user id, users array size is not 1");
|
||||
return;
|
||||
}
|
||||
if (!users[0].isObject()) {
|
||||
Log("API Error while getting user id, first user is not an object");
|
||||
return;
|
||||
}
|
||||
auto firstUser = users[0].toObject();
|
||||
auto id = firstUser.value("_id");
|
||||
if (!id.isString()) {
|
||||
Log("API Error: while getting user id, first user object `_id` key is not a "
|
||||
"string");
|
||||
return;
|
||||
}
|
||||
successCallback(id.toString());
|
||||
});
|
||||
}
|
||||
static void twitchApiPut(QUrl url, std::function<void(const rapidjson::Document &)> successCallback)
|
||||
{
|
||||
NetworkRequest request(url);
|
||||
request.setRequestType(NetworkRequest::PutRequest);
|
||||
request.setCaller(QThread::currentThread());
|
||||
auto request = NetworkRequest::twitchRequest(url);
|
||||
|
||||
auto currentTwitchUser = getApp()->accounts->twitch.getCurrent();
|
||||
QByteArray oauthToken;
|
||||
if (currentTwitchUser) {
|
||||
oauthToken = currentTwitchUser->getOAuthToken().toUtf8();
|
||||
} else {
|
||||
// XXX(pajlada): Bail out?
|
||||
}
|
||||
request.setCaller(caller);
|
||||
|
||||
request.makeAuthorizedV5(getDefaultClientID(), currentTwitchUser->getOAuthToken());
|
||||
|
||||
request.onSuccess([successCallback](const auto &document) {
|
||||
if (!document.IsNull()) {
|
||||
successCallback(document);
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
request.execute();
|
||||
}
|
||||
|
||||
static void twitchApiDelete(QUrl url, std::function<void()> successCallback)
|
||||
{
|
||||
NetworkRequest request(url);
|
||||
request.setRequestType(NetworkRequest::DeleteRequest);
|
||||
request.setCaller(QThread::currentThread());
|
||||
|
||||
auto currentTwitchUser = getApp()->accounts->twitch.getCurrent();
|
||||
QByteArray oauthToken;
|
||||
if (currentTwitchUser) {
|
||||
oauthToken = currentTwitchUser->getOAuthToken().toUtf8();
|
||||
} else {
|
||||
// XXX(pajlada): Bail out?
|
||||
}
|
||||
|
||||
request.makeAuthorizedV5(getDefaultClientID(), currentTwitchUser->getOAuthToken());
|
||||
|
||||
request.onError([successCallback](int code) {
|
||||
if (code >= 200 && code <= 299) {
|
||||
successCallback();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
request.onSuccess([successCallback](const auto &document) {
|
||||
successCallback();
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
request.execute();
|
||||
return request;
|
||||
}
|
||||
|
||||
} // namespace chatterino
|
||||
|
||||
Reference in New Issue
Block a user