NetworkRequest onError now uses NetworkResult

This commit is contained in:
fourtf 2019-09-19 19:03:50 +02:00
parent 986694e4bc
commit 758a6bb41c
10 changed files with 60 additions and 72 deletions

View file

@ -10,7 +10,7 @@ class Outcome;
class NetworkResult; class NetworkResult;
using NetworkSuccessCallback = std::function<Outcome(NetworkResult)>; using NetworkSuccessCallback = std::function<Outcome(NetworkResult)>;
using NetworkErrorCallback = std::function<bool(int)>; using NetworkErrorCallback = std::function<void(NetworkResult)>;
using NetworkReplyCreatedCallback = std::function<void(QNetworkReply *)>; using NetworkReplyCreatedCallback = std::function<void(QNetworkReply *)>;
enum class NetworkRequestType { enum class NetworkRequestType {

View file

@ -130,15 +130,16 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
if (data->timer_->isActive()) if (data->timer_->isActive())
{ {
QObject::connect(data->timer_, &QTimer::timeout, worker, QObject::connect(
[reply, data]() { data->timer_, &QTimer::timeout, worker, [reply, data]() {
log("Aborted!"); log("Aborted!");
reply->abort(); reply->abort();
if (data->onError_) if (data->onError_)
{ {
data->onError_(-2); data->onError_(
} NetworkResult({}, NetworkResult::timedoutStatus));
}); }
});
} }
if (data->onReplyCreated_) if (data->onReplyCreated_)
@ -157,7 +158,7 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
{ {
if (data->onError_) if (data->onError_)
{ {
data->onError_(reply->error()); data->onError_(NetworkResult({}, reply->error()));
} }
return; return;
} }
@ -165,7 +166,10 @@ void loadUncached(const std::shared_ptr<NetworkData> &data)
QByteArray bytes = reply->readAll(); QByteArray bytes = reply->readAll();
writeToCache(data, bytes); writeToCache(data, bytes);
NetworkResult result(bytes); auto status =
reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
NetworkResult result(bytes, status.toInt());
DebugCount::increase("http request success"); DebugCount::increase("http request success");
// log("starting {}", data->request_.url().toString()); // log("starting {}", data->request_.url().toString());
@ -223,7 +227,7 @@ void loadCached(const std::shared_ptr<NetworkData> &data)
{ {
// XXX: check if bytes is empty? // XXX: check if bytes is empty?
QByteArray bytes = cachedFile.readAll(); QByteArray bytes = cachedFile.readAll();
NetworkResult result(bytes); NetworkResult result(bytes, 200);
if (data->onSuccess_) if (data->onSuccess_)
{ {

View file

@ -8,8 +8,9 @@
namespace chatterino { namespace chatterino {
NetworkResult::NetworkResult(const QByteArray &data) NetworkResult::NetworkResult(const QByteArray &data, int status)
: data_(data) : data_(data)
, status_(status)
{ {
} }
@ -57,4 +58,9 @@ const QByteArray &NetworkResult::getData() const
return this->data_; return this->data_;
} }
int NetworkResult::status() const
{
return this->status_;
}
} // namespace chatterino } // namespace chatterino

View file

@ -8,7 +8,7 @@ namespace chatterino {
class NetworkResult class NetworkResult
{ {
public: public:
NetworkResult(const QByteArray &data); NetworkResult(const QByteArray &data, int status);
/// Parses the result as json and returns the root as an object. /// Parses the result as json and returns the root as an object.
/// Returns empty object if parsing failed. /// Returns empty object if parsing failed.
@ -19,8 +19,12 @@ public:
/// Parses the result as json and returns the document. /// Parses the result as json and returns the document.
rapidjson::Document parseRapidJson() const; rapidjson::Document parseRapidJson() const;
const QByteArray &getData() const; const QByteArray &getData() const;
int status() const;
static constexpr int timedoutStatus = -2;
private: private:
int status_;
QByteArray data_; QByteArray data_;
}; };

View file

@ -364,7 +364,7 @@ void Image::actuallyLoad()
return Success; return Success;
}) })
.onError([weak = weakOf(this)](auto /*result*/) -> bool { .onError([weak = weakOf(this)](auto /*result*/) {
auto shared = weak.lock(); auto shared = weak.lock();
if (!shared) if (!shared)
return false; return false;

View file

@ -49,8 +49,6 @@ void LinkResolver::getLinkInfo(
}) })
.onError([successCallback, url](auto /*result*/) { .onError([successCallback, url](auto /*result*/) {
successCallback("No link info found", Link(Link::Url, url)); successCallback("No link info found", Link(Link::Url, url));
return true;
}) })
.execute(); .execute();
// }); // });

View file

@ -203,25 +203,22 @@ void FfzEmotes::loadChannel(
return Success; return Success;
}) })
.onError([channelId](int result) { .onError([channelId](NetworkResult result) {
if (result == 203) if (result.status() == 203)
{ {
// User does not have any FFZ emotes // User does not have any FFZ emotes
return true;
} }
else if (result.status() == NetworkResult::timedoutStatus)
if (result == -2)
{ {
// TODO: Auto retry in case of a timeout, with a delay // TODO: Auto retry in case of a timeout, with a delay
log("Fetching FFZ emotes for channel {} failed due to timeout", log("Fetching FFZ emotes for channel {} failed due to timeout",
channelId); channelId);
return true;
} }
else
log("Error fetching FFZ emotes for channel {}, error {}", channelId, {
result); log("Error fetching FFZ emotes for channel {}, error {}",
channelId, result.status());
return true; }
}) })
.execute(); .execute();
} }

View file

@ -170,13 +170,11 @@ void TwitchAccount::ignoreByID(
NetworkRequest(url, NetworkRequestType::Put) NetworkRequest(url, NetworkRequestType::Put)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) { .onError([=](NetworkResult result) {
onFinished(IgnoreResult_Failed, onFinished(IgnoreResult_Failed,
"An unknown error occured while trying to ignore user " + "An unknown error occured while trying to ignore user " +
targetName + " (" + QString::number(errorCode) + targetName + " (" +
")"); QString::number(result.status()) + ")");
return true;
}) })
.onSuccess([=](auto result) -> Outcome { .onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson(); auto document = result.parseRapidJson();
@ -247,13 +245,11 @@ void TwitchAccount::unignoreByID(
NetworkRequest(url, NetworkRequestType::Delete) NetworkRequest(url, NetworkRequestType::Delete)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) { .onError([=](NetworkResult result) {
onFinished( onFinished(
UnignoreResult_Failed, UnignoreResult_Failed,
"An unknown error occured while trying to unignore user " + "An unknown error occured while trying to unignore user " +
targetName + " (" + QString::number(errorCode) + ")"); targetName + " (" + QString::number(result.status()) + ")");
return true;
}) })
.onSuccess([=](auto result) -> Outcome { .onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson(); auto document = result.parseRapidJson();
@ -281,8 +277,8 @@ void TwitchAccount::checkFollow(const QString targetUserID,
NetworkRequest(url) NetworkRequest(url)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) { .onError([=](NetworkResult result) {
if (errorCode == 203) if (result.status() == 203)
{ {
onFinished(FollowResult_NotFollowing); onFinished(FollowResult_NotFollowing);
} }
@ -290,8 +286,6 @@ void TwitchAccount::checkFollow(const QString targetUserID,
{ {
onFinished(FollowResult_Failed); onFinished(FollowResult_Failed);
} }
return true;
}) })
.onSuccess([=](auto result) -> Outcome { .onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson(); auto document = result.parseRapidJson();
@ -328,13 +322,11 @@ void TwitchAccount::unfollowUser(const QString userID,
NetworkRequest(requestUrl, NetworkRequestType::Delete) NetworkRequest(requestUrl, NetworkRequestType::Delete)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([successCallback](int code) { .onError([successCallback](NetworkResult result) {
if (code >= 200 && code <= 299) if (result.status() >= 200 && result.status() <= 299)
{ {
successCallback(); successCallback();
} }
return true;
}) })
.onSuccess([successCallback](const auto &document) -> Outcome { .onSuccess([successCallback](const auto &document) -> Outcome {
successCallback(); successCallback();
@ -370,9 +362,9 @@ void TwitchAccount::loadEmotes()
NetworkRequest(url) NetworkRequest(url)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) { .onError([=](NetworkResult result) {
log("[TwitchAccount::loadEmotes] Error {}", errorCode); log("[TwitchAccount::loadEmotes] Error {}", result.status());
if (errorCode == 203) if (result.status() == 203)
{ {
// onFinished(FollowResult_NotFollowing); // onFinished(FollowResult_NotFollowing);
} }
@ -380,8 +372,6 @@ void TwitchAccount::loadEmotes()
{ {
// onFinished(FollowResult_Failed); // onFinished(FollowResult_Failed);
} }
return true;
}) })
.onSuccess([=](auto result) -> Outcome { .onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson()); this->parseEmotes(result.parseRapidJson());
@ -411,9 +401,8 @@ void TwitchAccount::autoModAllow(const QString msgID)
.payload(qba) .payload(qba)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) { .onError([=](NetworkResult result) {
log("[TwitchAccounts::autoModAllow] Error {}", errorCode); log("[TwitchAccounts::autoModAllow] Error {}", result.status());
return true;
}) })
.execute(); .execute();
} }
@ -431,9 +420,8 @@ void TwitchAccount::autoModDeny(const QString msgID)
.payload(qba) .payload(qba)
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken()) .authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) { .onError([=](NetworkResult result) {
log("[TwitchAccounts::autoModDeny] Error {}", errorCode); log("[TwitchAccounts::autoModDeny] Error {}", result.status());
return true;
}) })
.execute(); .execute();
} }
@ -516,9 +504,8 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
NetworkRequest(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key)) NetworkRequest(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key))
.cache() .cache()
.onError([](int errorCode) -> bool { .onError([](NetworkResult result) {
log("Error code {} while loading emote set data", errorCode); log("Error code {} while loading emote set data", result.status());
return true;
}) })
.onSuccess([emoteSet](auto result) -> Outcome { .onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson(); auto root = result.parseRapidJson();

View file

@ -83,7 +83,7 @@ void Updates::installUpdates()
NetworkRequest(this->updatePortable_) NetworkRequest(this->updatePortable_)
.timeout(600000) .timeout(600000)
.onError([this](int) -> bool { .onError([this](NetworkResult) {
this->setStatus_(DownloadFailed); this->setStatus_(DownloadFailed);
postToThread([] { postToThread([] {
@ -94,8 +94,6 @@ void Updates::installUpdates()
box->show(); box->show();
box->raise(); box->raise();
}); });
return true;
}) })
.onSuccess([this](auto result) -> Outcome { .onSuccess([this](auto result) -> Outcome {
QByteArray object = result.getData(); QByteArray object = result.getData();
@ -136,7 +134,7 @@ void Updates::installUpdates()
NetworkRequest(this->updateExe_) NetworkRequest(this->updateExe_)
.timeout(600000) .timeout(600000)
.onError([this](int) -> bool { .onError([this](NetworkResult) {
this->setStatus_(DownloadFailed); this->setStatus_(DownloadFailed);
QMessageBox *box = new QMessageBox( QMessageBox *box = new QMessageBox(
@ -145,7 +143,6 @@ void Updates::installUpdates()
"downloading the update."); "downloading the update.");
box->setAttribute(Qt::WA_DeleteOnClose); box->setAttribute(Qt::WA_DeleteOnClose);
box->exec(); box->exec();
return true;
}) })
.onSuccess([this](auto result) -> Outcome { .onSuccess([this](auto result) -> Outcome {
QByteArray object = result.getData(); QByteArray object = result.getData();

View file

@ -88,10 +88,7 @@ void LogsPopup::getLogviewerLogs(const QString &roomID)
NetworkRequest(url) NetworkRequest(url)
.caller(this) .caller(this)
.onError([this](int /*errorCode*/) { .onError([this](NetworkResult) { this->getOverrustleLogs(); })
this->getOverrustleLogs();
return true;
})
.onSuccess([this, roomID](auto result) -> Outcome { .onSuccess([this, roomID](auto result) -> Outcome {
auto data = result.parseJson(); auto data = result.parseJson();
std::vector<MessagePtr> messages; std::vector<MessagePtr> messages;
@ -140,7 +137,7 @@ void LogsPopup::getOverrustleLogs()
NetworkRequest(url) NetworkRequest(url)
.caller(this) .caller(this)
.onError([this](int /*errorCode*/) { .onError([this](NetworkResult) {
auto box = new QMessageBox( auto box = new QMessageBox(
QMessageBox::Information, "Error getting logs", QMessageBox::Information, "Error getting logs",
"No logs could be found for channel " + this->channelName_); "No logs could be found for channel " + this->channelName_);
@ -150,8 +147,6 @@ void LogsPopup::getOverrustleLogs()
box->raise(); box->raise();
this->close(); this->close();
box->exec(); box->exec();
return true;
}) })
.onSuccess([this](auto result) -> Outcome { .onSuccess([this](auto result) -> Outcome {
auto data = result.parseJson(); auto data = result.parseJson();