removed old NetworkRequest api

This commit is contained in:
fourtf 2019-08-20 21:50:36 +02:00
parent a7cd1fbf97
commit 7697ec01b4
23 changed files with 954 additions and 1101 deletions

View file

@ -3,7 +3,8 @@
namespace chatterino {
class Resources2 : public Singleton {
class Resources2 : public Singleton
{
public:
Resources2();

View file

@ -39,85 +39,9 @@ NetworkRequest::NetworkRequest(QUrl url, NetworkRequestType requestType)
NetworkRequest::~NetworkRequest()
{
//assert(this->executed_);
//assert(!this->data || this->executed_);
}
// old
void NetworkRequest::type(NetworkRequestType newRequestType) &
{
this->data->requestType_ = newRequestType;
}
void NetworkRequest::setCaller(const QObject *caller) &
{
this->data->caller_ = caller;
}
void NetworkRequest::onReplyCreated(NetworkReplyCreatedCallback cb) &
{
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);
}
void NetworkRequest::setRawHeader(const char *headerName,
const QByteArray &value) &
{
this->data->request_.setRawHeader(headerName, value);
}
void NetworkRequest::setRawHeader(const char *headerName,
const QString &value) &
{
this->data->request_.setRawHeader(headerName, value.toUtf8());
}
void NetworkRequest::setTimeout(int ms) &
{
this->data->hasTimeout_ = true;
this->data->timer_.setInterval(ms);
}
void NetworkRequest::setExecuteConcurrently(bool value) &
{
this->data->executeConcurrently = value;
}
void NetworkRequest::makeAuthorizedV5(const QString &clientID,
const QString &oauthToken) &
{
this->setRawHeader("Client-ID", clientID);
this->setRawHeader("Accept", "application/vnd.twitchtv.v5+json");
if (!oauthToken.isEmpty())
{
this->setRawHeader("Authorization", "OAuth " + oauthToken);
}
}
void NetworkRequest::setPayload(const QByteArray &payload) &
{
this->data->payload_ = payload;
}
void NetworkRequest::setUseQuickLoadCache(bool value) &
{
this->data->useQuickLoadCache_ = value;
}
// new
NetworkRequest NetworkRequest::type(NetworkRequestType newRequestType) &&
{
this->data->requestType_ = newRequestType;

View file

@ -36,28 +36,6 @@ public:
~NetworkRequest();
// old
[[deprecated]] void type(NetworkRequestType newRequestType) &;
[[deprecated]] void onReplyCreated(NetworkReplyCreatedCallback cb) &;
[[deprecated]] void onError(NetworkErrorCallback cb) &;
[[deprecated]] void onSuccess(NetworkSuccessCallback cb) &;
[[deprecated]] void setPayload(const QByteArray &payload) &;
[[deprecated]] void setUseQuickLoadCache(bool value) &;
[[deprecated]] void setCaller(const QObject *caller) &;
[[deprecated]] void setRawHeader(const char *headerName,
const char *value) &;
[[deprecated]] void setRawHeader(const char *headerName,
const QByteArray &value) &;
[[deprecated]] void setRawHeader(const char *headerName,
const QString &value) &;
[[deprecated]] void setTimeout(int ms) &;
[[deprecated]] void setExecuteConcurrently(bool value) &;
[[deprecated]] void makeAuthorizedV5(
const QString &clientID, const QString &oauthToken = QString()) &;
// new
NetworkRequest type(NetworkRequestType newRequestType) &&;
NetworkRequest onReplyCreated(NetworkReplyCreatedCallback cb) &&;

View file

@ -106,8 +106,7 @@ public:
{
if (!this->emotesChecked_)
{
const auto &accvec =
getApp()->accounts->twitch.accounts;
const auto &accvec = getApp()->accounts->twitch.accounts;
for (const auto &acc : accvec)
{
const auto &accemotes = *acc->accessEmotes();

View file

@ -155,20 +155,21 @@ void NotificationController::getFakeTwitchChannelLiveStatus(
log("[TwitchChannel:{}] Refreshing live status", channelName);
QString url("https://api.twitch.tv/kraken/streams/" + roomID);
auto request = NetworkRequest::twitchRequest(url);
request.setCaller(QThread::currentThread());
request.onSuccess([this, channelName](auto result) -> Outcome {
NetworkRequest::twitchRequest(url)
.caller(QThread::currentThread())
.onSuccess([this, channelName](auto result) -> Outcome {
rapidjson::Document document = result.parseRapidJson();
if (!document.IsObject())
{
log("[TwitchChannel:refreshLiveStatus]root is not an object");
log("[TwitchChannel:refreshLiveStatus]root is not an "
"object");
return Failure;
}
if (!document.HasMember("stream"))
{
log("[TwitchChannel:refreshLiveStatus] Missing stream in root");
log("[TwitchChannel:refreshLiveStatus] Missing stream in "
"root");
return Failure;
}
@ -189,8 +190,8 @@ void NotificationController::getFakeTwitchChannelLiveStatus(
fakeTwitchChannels.push_back(channelName);
if (Toasts::isEnabled())
{
getApp()->toasts->sendChannelNotification(channelName,
Platform::Twitch);
getApp()->toasts->sendChannelNotification(
channelName, Platform::Twitch);
}
if (getSettings()->notificationPlaySound)
{
@ -202,9 +203,8 @@ void NotificationController::getFakeTwitchChannelLiveStatus(
}
}
return Success;
});
request.execute();
})
.execute();
});
}

View file

@ -20,11 +20,11 @@ void LinkResolver::getLinkInfo(
}
// Uncomment to test crashes
// QTimer::singleShot(3000, [=]() {
NetworkRequest request(Env::get().linkResolverUrl.arg(
QString::fromUtf8(QUrl::toPercentEncoding(url, "", "/:"))));
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([successCallback, url](auto result) mutable -> Outcome {
NetworkRequest(Env::get().linkResolverUrl.arg(QString::fromUtf8(
QUrl::toPercentEncoding(url, "", "/:"))))
.caller(QThread::currentThread())
.timeout(30000)
.onSuccess([successCallback, url](auto result) mutable -> Outcome {
auto root = result.parseJson();
auto statusCode = root.value("status").toInt();
QString response = QString();
@ -45,15 +45,13 @@ void LinkResolver::getLinkInfo(
Link(Link::Url, linkString));
return Success;
});
request.onError([successCallback, url](auto result) {
})
.onError([successCallback, url](auto /*result*/) {
successCallback("No link info found", Link(Link::Url, url));
return true;
});
request.execute();
})
.execute();
// });
}

View file

@ -112,42 +112,36 @@ boost::optional<EmotePtr> BttvEmotes::emote(const EmoteName &name) const
void BttvEmotes::loadEmotes()
{
auto request = NetworkRequest(QString(globalEmoteApiUrl));
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([this](auto result) -> Outcome {
NetworkRequest(QString(globalEmoteApiUrl))
.caller(QThread::currentThread())
.timeout(30000)
.onSuccess([this](auto result) -> Outcome {
auto emotes = this->global_.get();
auto pair = parseGlobalEmotes(result.parseJson(), *emotes);
if (pair.first)
this->global_.set(
std::make_shared<EmoteMap>(std::move(pair.second)));
return pair.first;
});
request.execute();
})
.execute();
}
void BttvEmotes::loadChannel(const QString &channelName,
std::function<void(EmoteMap &&)> callback)
{
auto request =
NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName)
.caller(QThread::currentThread())
.timeout(3000)
.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
auto pair = parseChannelEmotes(result.parseJson());
if (pair.first)
callback(std::move(pair.second));
return pair.first;
});
request.execute();
})
.execute();
}
/*
static Url getEmoteLink(QString urlTemplate, const EmoteId &id,
const QString &emoteScale)
{
@ -156,5 +150,6 @@ static Url getEmoteLink(QString urlTemplate, const EmoteId &id,
return {urlTemplate.replace("{{id}}", id.string)
.replace("{{image}}", emoteScale)};
}
*/
} // namespace chatterino

View file

@ -36,20 +36,21 @@ void ChatterinoBadges::loadChatterinoBadges()
{
static QUrl url("https://fourtf.com/chatterino/badges.json");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) -> Outcome {
NetworkRequest(url)
.caller(QThread::currentThread())
.onSuccess([this](auto result) -> Outcome {
auto jsonRoot = result.parseJson();
int index = 0;
for (const auto &jsonBadge_ : jsonRoot.value("badges").toArray())
{
auto jsonBadge = jsonBadge_.toObject();
auto emote = Emote{
EmoteName{}, ImageSet{Url{jsonBadge.value("image").toString()}},
EmoteName{},
ImageSet{Url{jsonBadge.value("image").toString()}},
Tooltip{jsonBadge.value("tooltip").toString()}, Url{}};
emotes.push_back(std::make_shared<const Emote>(std::move(emote)));
emotes.push_back(
std::make_shared<const Emote>(std::move(emote)));
for (const auto &user : jsonBadge.value("users").toArray())
{
@ -59,9 +60,8 @@ void ChatterinoBadges::loadChatterinoBadges()
}
return Success;
});
req.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -137,20 +137,18 @@ void FfzEmotes::loadEmotes()
{
QString url("https://api.frankerfacez.com/v1/set/global");
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([this](auto result) -> Outcome {
NetworkRequest(url)
.caller(QThread::currentThread())
.timeout(30000)
.onSuccess([this](auto result) -> Outcome {
auto emotes = this->emotes();
auto pair = parseGlobalEmotes(result.parseJson(), *emotes);
if (pair.first)
this->global_.set(
std::make_shared<EmoteMap>(std::move(pair.second)));
return pair.first;
});
request.execute();
})
.execute();
}
void FfzEmotes::loadChannel(const QString &channelName,
@ -158,19 +156,16 @@ void FfzEmotes::loadChannel(const QString &channelName,
{
log("[FFZEmotes] Reload FFZ Channel Emotes for channel {}\n", channelName);
NetworkRequest request("https://api.frankerfacez.com/v1/room/" +
channelName);
request.setCaller(QThread::currentThread());
request.setTimeout(20000);
request.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
NetworkRequest("https://api.frankerfacez.com/v1/room/" + channelName)
.caller(QThread::currentThread())
.timeout(20000)
.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
auto pair = parseChannelEmotes(result.parseJson());
if (pair.first)
callback(std::move(pair.second));
return pair.first;
});
request.onError([channelName](int result) {
})
.onError([channelName](int result) {
if (result == 203)
{
// User does not have any FFZ emotes
@ -185,13 +180,12 @@ void FfzEmotes::loadChannel(const QString &channelName,
return true;
}
log("Error fetching FFZ emotes for channel {}, error {}", channelName,
result);
log("Error fetching FFZ emotes for channel {}, error {}",
channelName, result);
return true;
});
request.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -22,9 +22,9 @@ void FfzModBadge::loadCustomModBadge()
static QString partialUrl("https://cdn.frankerfacez.com/room-badge/mod/");
QString url = partialUrl + channelName_ + "/1";
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this, url](auto result) -> Outcome {
NetworkRequest(url)
.caller(QThread::currentThread())
.onSuccess([this, url](auto result) -> Outcome {
auto data = result.getData();
QBuffer buffer(const_cast<QByteArray *>(&data));
@ -51,9 +51,8 @@ void FfzModBadge::loadCustomModBadge()
// getBadge.execute();
return Success;
});
req.execute();
})
.execute();
}
EmotePtr FfzModBadge::badge() const

View file

@ -36,12 +36,11 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback,
caller = QThread::currentThread();
}
NetworkRequest request("https://api.twitch.tv/kraken/users?login=" +
this->username_);
request.setCaller(caller);
request.makeAuthorizedV5(getDefaultClientID());
request.onSuccess([successCallback](auto result) -> Outcome {
NetworkRequest("https://api.twitch.tv/kraken/users?login=" +
this->username_)
.caller(caller)
.authorizeTwitchV5(getDefaultClientID())
.onSuccess([successCallback](auto result) -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray())
{
@ -52,19 +51,22 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback,
auto users = root.value("users").toArray();
if (users.size() != 1)
{
log("API Error while getting user id, users array size is not 1");
log("API Error while getting user id, users array size is not "
"1");
return Failure;
}
if (!users[0].isObject())
{
log("API Error while getting user id, first user is not an object");
log("API Error while getting user id, first user is not an "
"object");
return Failure;
}
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 "
log("API Error: while getting user id, first user object `_id` "
"key "
"is not a "
"string");
return Failure;
@ -72,9 +74,8 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback,
successCallback(id.toString());
return Success;
});
request.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -94,10 +94,10 @@ void TwitchAccount::loadIgnores()
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/blocks");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onSuccess([=](auto result) -> Outcome {
NetworkRequest(url)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject())
{
@ -144,9 +144,8 @@ void TwitchAccount::loadIgnores()
}
return Success;
});
req.execute();
})
.execute();
}
void TwitchAccount::ignore(
@ -167,19 +166,19 @@ void TwitchAccount::ignoreByID(
{
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/blocks/" + targetUserID);
NetworkRequest req(url, NetworkRequestType::Put);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onError([=](int errorCode) {
NetworkRequest(url, NetworkRequestType::Put)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
onFinished(IgnoreResult_Failed,
"An unknown error occured while trying to ignore user " +
targetName + " (" + QString::number(errorCode) + ")");
targetName + " (" + QString::number(errorCode) +
")");
return true;
});
req.onSuccess([=](auto result) -> Outcome {
})
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject())
{
@ -222,9 +221,8 @@ void TwitchAccount::ignoreByID(
"Successfully ignored user " + targetName);
return Success;
});
req.execute();
})
.execute();
}
void TwitchAccount::unignore(
@ -246,19 +244,18 @@ void TwitchAccount::unignoreByID(
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/blocks/" + targetUserID);
NetworkRequest req(url, NetworkRequestType::Delete);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onError([=](int errorCode) {
onFinished(UnignoreResult_Failed,
NetworkRequest(url, NetworkRequestType::Delete)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
onFinished(
UnignoreResult_Failed,
"An unknown error occured while trying to unignore user " +
targetName + " (" + QString::number(errorCode) + ")");
return true;
});
req.onSuccess([=](auto result) -> Outcome {
})
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
TwitchUser ignoredUser;
ignoredUser.id = targetUserID;
@ -271,9 +268,8 @@ void TwitchAccount::unignoreByID(
"Successfully unignored user " + targetName);
return Success;
});
req.execute();
})
.execute();
}
void TwitchAccount::checkFollow(const QString targetUserID,
@ -282,11 +278,10 @@ void TwitchAccount::checkFollow(const QString targetUserID,
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/follows/channels/" + targetUserID);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onError([=](int errorCode) {
NetworkRequest(url)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
if (errorCode == 203)
{
onFinished(FollowResult_NotFollowing);
@ -297,15 +292,13 @@ void TwitchAccount::checkFollow(const QString targetUserID,
}
return true;
});
req.onSuccess([=](auto result) -> Outcome {
})
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
onFinished(FollowResult_Following);
return Success;
});
req.execute();
})
.execute();
}
void TwitchAccount::followUser(const QString userID,
@ -314,19 +307,16 @@ void TwitchAccount::followUser(const QString userID,
QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/follows/channels/" + userID);
NetworkRequest request(requestUrl, NetworkRequestType::Put);
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
NetworkRequest(requestUrl, NetworkRequestType::Put)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onSuccess([successCallback](auto result) -> Outcome {
// TODO: Properly check result of follow request
request.onSuccess([successCallback](auto result) -> Outcome {
successCallback();
return Success;
});
request.execute();
})
.execute();
}
void TwitchAccount::unfollowUser(const QString userID,
@ -335,27 +325,23 @@ void TwitchAccount::unfollowUser(const QString userID,
QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/follows/channels/" + userID);
NetworkRequest request(requestUrl, NetworkRequestType::Delete);
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
request.onError([successCallback](int code) {
NetworkRequest(requestUrl, NetworkRequestType::Delete)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([successCallback](int code) {
if (code >= 200 && code <= 299)
{
successCallback();
}
return true;
});
request.onSuccess([successCallback](const auto &document) -> Outcome {
})
.onSuccess([successCallback](const auto &document) -> Outcome {
successCallback();
return Success;
});
request.execute();
})
.execute();
}
std::set<TwitchUser> TwitchAccount::getIgnores() const
@ -381,11 +367,10 @@ void TwitchAccount::loadEmotes()
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/emotes");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onError([=](int errorCode) {
NetworkRequest(url)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
log("[TwitchAccount::loadEmotes] Error {}", errorCode);
if (errorCode == 203)
{
@ -397,15 +382,13 @@ void TwitchAccount::loadEmotes()
}
return true;
});
req.onSuccess([=](auto result) -> Outcome {
})
.onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson());
return Success;
});
req.execute();
})
.execute();
}
AccessGuard<const TwitchAccount::TwitchAccountEmoteData>
@ -419,44 +402,40 @@ void TwitchAccount::autoModAllow(const QString msgID)
{
QString url("https://api.twitch.tv/kraken/chat/twitchbot/approve");
NetworkRequest req(url, NetworkRequestType::Post);
req.setRawHeader("Content-Type", "application/json");
auto qba = (QString("{\"msg_id\":\"") + msgID + "\"}").toUtf8();
qDebug() << qba;
req.setRawHeader("Content-Length", QByteArray::number(qba.size()));
req.setPayload(qba);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onError([=](int errorCode) {
NetworkRequest(url, NetworkRequestType::Post)
.header("Content-Type", "application/json")
.header("Content-Length", QByteArray::number(qba.size()))
.payload(qba)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
log("[TwitchAccounts::autoModAllow] Error {}", errorCode);
return true;
});
req.execute();
})
.execute();
}
void TwitchAccount::autoModDeny(const QString msgID)
{
QString url("https://api.twitch.tv/kraken/chat/twitchbot/deny");
NetworkRequest req(url, NetworkRequestType::Post);
req.setRawHeader("Content-Type", "application/json");
auto qba = (QString("{\"msg_id\":\"") + msgID + "\"}").toUtf8();
qDebug() << qba;
req.setRawHeader("Content-Length", QByteArray::number(qba.size()));
req.setPayload(qba);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onError([=](int errorCode) {
NetworkRequest(url, NetworkRequestType::Post)
.header("Content-Type", "application/json")
.header("Content-Length", QByteArray::number(qba.size()))
.payload(qba)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
log("[TwitchAccounts::autoModDeny] Error {}", errorCode);
return true;
});
req.execute();
})
.execute();
}
void TwitchAccount::parseEmotes(const rapidjson::Document &root)
@ -535,15 +514,13 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
return;
}
NetworkRequest req(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key));
req.setUseQuickLoadCache(true);
req.onError([](int errorCode) -> bool {
NetworkRequest(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key))
.cache()
.onError([](int errorCode) -> bool {
log("Error code {} while loading emote set data", errorCode);
return true;
});
req.onSuccess([emoteSet](auto result) -> Outcome {
})
.onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson();
if (!root.IsObject())
{
@ -575,9 +552,8 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
emoteSet->channelName = channelName;
return Success;
});
req.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -15,11 +15,11 @@ void TwitchApi::findUserId(const QString user,
{
QString requestUrl("https://api.twitch.tv/kraken/users?login=" + user);
NetworkRequest request(requestUrl);
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(getDefaultClientID());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable -> Outcome {
NetworkRequest(requestUrl)
.caller(QThread::currentThread())
.authorizeTwitchV5(getDefaultClientID())
.timeout(30000)
.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray())
{
@ -30,13 +30,15 @@ void TwitchApi::findUserId(const QString user,
auto users = root.value("users").toArray();
if (users.size() != 1)
{
log("API Error while getting user id, users array size is not 1");
log("API Error while getting user id, users array size is not "
"1");
successCallback("");
return Failure;
}
if (!users[0].isObject())
{
log("API Error while getting user id, first user is not an object");
log("API Error while getting user id, first user is not an "
"object");
successCallback("");
return Failure;
}
@ -44,7 +46,8 @@ void TwitchApi::findUserId(const QString user,
auto id = firstUser.value("_id");
if (!id.isString())
{
log("API Error: while getting user id, first user object `_id` key "
log("API Error: while getting user id, first user object `_id` "
"key "
"is not a "
"string");
successCallback("");
@ -52,9 +55,8 @@ void TwitchApi::findUserId(const QString user,
}
successCallback(id.toString());
return Success;
});
request.execute();
})
.execute();
}
void TwitchApi::findUserName(const QString userid,
@ -62,24 +64,24 @@ void TwitchApi::findUserName(const QString userid,
{
QString requestUrl("https://api.twitch.tv/kraken/users/" + userid);
NetworkRequest request(requestUrl);
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(getDefaultClientID());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable -> Outcome {
NetworkRequest(requestUrl)
.caller(QThread::currentThread())
.authorizeTwitchV5(getDefaultClientID())
.timeout(30000)
.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
auto name = root.value("name");
if (!name.isString())
{
log("API Error: while getting user name, `name` is not a string");
log("API Error: while getting user name, `name` is not a "
"string");
successCallback("");
return Failure;
}
successCallback(name.toString());
return Success;
});
request.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -17,9 +17,9 @@ void TwitchBadges::loadTwitchBadges()
static QString url(
"https://badges.twitch.tv/v1/badges/global/display?language=en");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) -> Outcome {
NetworkRequest(url)
.caller(QThread::currentThread())
.onSuccess([this](auto result) -> Outcome {
auto root = result.parseJson();
auto badgeSets = this->badgeSets_.access();
@ -27,7 +27,8 @@ void TwitchBadges::loadTwitchBadges()
for (auto sIt = jsonSets.begin(); sIt != jsonSets.end(); ++sIt)
{
auto key = sIt.key();
auto versions = sIt.value().toObject().value("versions").toObject();
auto versions =
sIt.value().toObject().value("versions").toObject();
for (auto vIt = versions.begin(); vIt != versions.end(); ++vIt)
{
@ -37,25 +38,28 @@ void TwitchBadges::loadTwitchBadges()
{""},
ImageSet{
Image::fromUrl(
{versionObj.value("image_url_1x").toString()}, 1),
{versionObj.value("image_url_1x").toString()},
1),
Image::fromUrl(
{versionObj.value("image_url_2x").toString()}, .5),
{versionObj.value("image_url_2x").toString()},
.5),
Image::fromUrl(
{versionObj.value("image_url_4x").toString()}, .25),
{versionObj.value("image_url_4x").toString()},
.25),
},
Tooltip{versionObj.value("description").toString()},
Url{versionObj.value("click_url").toString()}};
// "title"
// "clickAction"
(*badgeSets)[key][vIt.key()] = std::make_shared<Emote>(emote);
(*badgeSets)[key][vIt.key()] =
std::make_shared<Emote>(emote);
}
}
return Success;
});
req.execute();
})
.execute();
}
boost::optional<EmotePtr> TwitchBadges::badge(const QString &set,

View file

@ -501,19 +501,17 @@ void TwitchChannel::refreshLiveStatus()
QString url("https://api.twitch.tv/kraken/streams/" + roomID);
// auto request = makeGetStreamRequest(roomID, QThread::currentThread());
auto request = NetworkRequest::twitchRequest(url);
request.setCaller(QThread::currentThread());
request.onSuccess(
NetworkRequest::twitchRequest(url)
.caller(QThread::currentThread())
.onSuccess(
[this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared)
return Failure;
return this->parseLiveStatus(result.parseRapidJson());
});
request.execute();
})
.execute();
}
Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
@ -608,13 +606,10 @@ void TwitchChannel::loadRecentMessages()
return;
}
NetworkRequest request(
Env::get().recentMessagesApiUrl.arg(this->getName()));
request.setCaller(QThread::currentThread());
// can't be concurrent right now due to SignalVector
request.setExecuteConcurrently(true);
request.onSuccess([weak = weakOf<Channel>(this)](auto result) -> Outcome {
NetworkRequest(Env::get().recentMessagesApiUrl.arg(this->getName()))
.caller(QThread::currentThread())
.concurrent()
.onSuccess([weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared)
return Failure;
@ -641,9 +636,8 @@ void TwitchChannel::loadRecentMessages()
});
return Success;
});
request.execute();
})
.execute();
}
void TwitchChannel::refreshPubsub()
@ -675,11 +669,10 @@ void TwitchChannel::refreshChatters()
}
// get viewer list
NetworkRequest request("https://tmi.twitch.tv/group/user/" +
this->getName() + "/chatters");
request.setCaller(QThread::currentThread());
request.onSuccess(
NetworkRequest("https://tmi.twitch.tv/group/user/" + this->getName() +
"/chatters")
.caller(QThread::currentThread())
.onSuccess(
[this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
// channel still exists?
auto shared = weak.lock();
@ -693,19 +686,18 @@ void TwitchChannel::refreshChatters()
}
return pair.first;
});
request.execute();
})
.execute();
}
void TwitchChannel::refreshBadges()
{
auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" +
this->roomId() + "/display?language=en"};
NetworkRequest req(url.string);
req.setCaller(QThread::currentThread());
req.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
NetworkRequest(url.string)
.caller(QThread::currentThread())
.onSuccess([this,
weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared)
return Failure;
@ -721,19 +713,19 @@ void TwitchChannel::refreshBadges()
auto &versions = (*badgeSets)[jsonBadgeSet.key()];
auto _set = jsonBadgeSet->toObject()["versions"].toObject();
for (auto jsonVersion_ = _set.begin(); jsonVersion_ != _set.end();
jsonVersion_++)
for (auto jsonVersion_ = _set.begin();
jsonVersion_ != _set.end(); jsonVersion_++)
{
auto jsonVersion = jsonVersion_->toObject();
auto emote = std::make_shared<Emote>(Emote{
EmoteName{},
ImageSet{
Image::fromUrl({jsonVersion["image_url_1x"].toString()},
1),
Image::fromUrl({jsonVersion["image_url_2x"].toString()},
.5),
Image::fromUrl({jsonVersion["image_url_4x"].toString()},
.25)},
Image::fromUrl(
{jsonVersion["image_url_1x"].toString()}, 1),
Image::fromUrl(
{jsonVersion["image_url_2x"].toString()}, .5),
Image::fromUrl(
{jsonVersion["image_url_4x"].toString()}, .25)},
Tooltip{jsonVersion["description"].toString()},
Url{jsonVersion["clickURL"].toString()}});
@ -742,9 +734,8 @@ void TwitchChannel::refreshBadges()
}
return Success;
});
req.execute();
})
.execute();
}
void TwitchChannel::refreshCheerEmotes()

View file

@ -42,8 +42,8 @@ public:
BoolSetting hideModerated = {"/appearance/messages/hideModerated", false};
BoolSetting hideModerationActions = {
"/appearance/messages/hideModerationActions", false};
BoolSetting colorizeNicknames = {
"/appearance/messages/colorizeNicknames", false};
BoolSetting colorizeNicknames = {"/appearance/messages/colorizeNicknames",
false};
// BoolSetting collapseLongMessages =
// {"/appearance/messages/collapseLongMessages", false};
@ -99,7 +99,8 @@ public:
"/behaviour/autocompletion/onlyFetchChattersForSmallerStreamers", true};
IntSetting smallStreamerLimit = {
"/behaviour/autocompletion/smallStreamerLimit", 1000};
BoolSetting prefixOnlyEmoteCompletion = {"/behaviour/autocompletion/prefixOnlyCompletion", true};
BoolSetting prefixOnlyEmoteCompletion = {
"/behaviour/autocompletion/prefixOnlyCompletion", true};
BoolSetting pauseChatOnHover = {"/behaviour/pauseChatHover", false};
BoolSetting autorun = {"/behaviour/autorun", false};

View file

@ -213,11 +213,11 @@ void Toasts::fetchChannelAvatar(const QString channelName,
QString requestUrl("https://api.twitch.tv/kraken/users?login=" +
channelName);
NetworkRequest request(requestUrl);
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(getDefaultClientID());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable -> Outcome {
NetworkRequest(requestUrl)
.caller(QThread::currentThread())
.authorizeTwitchV5(getDefaultClientID())
.timeout(30000)
.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray())
{
@ -253,8 +253,7 @@ void Toasts::fetchChannelAvatar(const QString channelName,
}
successCallback(avatar.toString());
return Success;
});
request.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -73,9 +73,9 @@ void Updates::installUpdates()
box->setAttribute(Qt::WA_DeleteOnClose);
box->show();
NetworkRequest req(this->updatePortable_);
req.setTimeout(600000);
req.onError([this](int) -> bool {
NetworkRequest(this->updatePortable_)
.timeout(600000)
.onError([this](int) -> bool {
this->setStatus_(DownloadFailed);
postToThread([] {
@ -88,9 +88,8 @@ void Updates::installUpdates()
});
return true;
});
req.onSuccess([this](auto result) -> Outcome {
})
.onSuccess([this](auto result) -> Outcome {
QByteArray object = result.getData();
auto filename =
combinePath(getPaths()->miscDirectory, "update.zip");
@ -111,9 +110,9 @@ void Updates::installUpdates()
QApplication::exit(0);
return Success;
});
})
.execute();
this->setStatus_(Downloading);
req.execute();
}
else
{
@ -125,9 +124,9 @@ void Updates::installUpdates()
box->setAttribute(Qt::WA_DeleteOnClose);
box->show();
NetworkRequest req(this->updateExe_);
req.setTimeout(600000);
req.onError([this](int) -> bool {
NetworkRequest(this->updateExe_)
.timeout(600000)
.onError([this](int) -> bool {
this->setStatus_(DownloadFailed);
QMessageBox *box = new QMessageBox(
@ -137,9 +136,8 @@ void Updates::installUpdates()
box->setAttribute(Qt::WA_DeleteOnClose);
box->exec();
return true;
});
req.onSuccess([this](auto result) -> Outcome {
})
.onSuccess([this](auto result) -> Outcome {
QByteArray object = result.getData();
auto filename =
combinePath(getPaths()->miscDirectory, "Update.exe");
@ -153,7 +151,8 @@ void Updates::installUpdates()
QMessageBox *box = new QMessageBox(
QMessageBox::Information, "Chatterino Update",
"Failed to save the update file. This could be due to "
"window settings or antivirus software.\n\nTry manually "
"window settings or antivirus software.\n\nTry "
"manually "
"downloading the update.");
box->setAttribute(Qt::WA_DeleteOnClose);
box->exec();
@ -183,9 +182,9 @@ void Updates::installUpdates()
}
return Success;
});
})
.execute();
this->setStatus_(Downloading);
req.execute();
}
#endif
}
@ -196,9 +195,9 @@ void Updates::checkForUpdates()
"https://notitia.chatterino.com/version/chatterino/" CHATTERINO_OS
"/stable";
NetworkRequest req(url);
req.setTimeout(60000);
req.onSuccess([this](auto result) -> Outcome {
NetworkRequest(url)
.timeout(60000)
.onSuccess([this](auto result) -> Outcome {
auto object = result.parseJson();
/// Version available on every platform
QJsonValue version_val = object.value("version");
@ -254,9 +253,9 @@ void Updates::checkForUpdates()
this->setStatus_(NoUpdateAvailable);
}
return Failure;
});
})
.execute();
this->setStatus_(Searching);
req.execute();
}
Updates::Status Updates::getStatus() const

View file

@ -91,15 +91,13 @@ void LogsPopup::getLogviewerLogs(const QString &roomID)
auto url = QString("https://cbenni.com/api/logs/%1/?nick=%2&before=500")
.arg(this->channelName_, this->userName_);
NetworkRequest req(url);
req.setCaller(this);
req.onError([this](int errorCode) {
NetworkRequest(url)
.caller(this)
.onError([this](int errorCode) {
this->getOverrustleLogs();
return true;
});
req.onSuccess([this, roomID](auto result) -> Outcome {
})
.onSuccess([this, roomID](auto result) -> Outcome {
auto data = result.parseJson();
std::vector<MessagePtr> messages;
@ -121,15 +119,15 @@ void LogsPopup::getLogviewerLogs(const QString &roomID)
Communi::IrcMessage::fromData(message.toUtf8(), nullptr);
auto privMsg =
static_cast<Communi::IrcPrivateMessage *>(ircMessage);
TwitchMessageBuilder builder(this->channel_.get(), privMsg, args);
TwitchMessageBuilder builder(this->channel_.get(), privMsg,
args);
messages.push_back(builder.build());
}
this->setMessages(messages);
return Success;
});
req.execute();
})
.execute();
}
void LogsPopup::getOverrustleLogs()
@ -138,9 +136,9 @@ void LogsPopup::getOverrustleLogs()
QString("https://overrustlelogs.net/api/v1/stalk/%1/%2.json?limit=500")
.arg(this->channelName_, this->userName_);
NetworkRequest req(url);
req.setCaller(this);
req.onError([this](int errorCode) {
NetworkRequest(url)
.caller(this)
.onError([this](int errorCode) {
auto box = new QMessageBox(
QMessageBox::Information, "Error getting logs",
"No logs could be found for channel " + this->channelName_);
@ -158,9 +156,8 @@ void LogsPopup::getOverrustleLogs()
}
return true;
});
req.onSuccess([this](auto result) -> Outcome {
})
.onSuccess([this](auto result) -> Outcome {
auto data = result.parseJson();
std::vector<MessagePtr> messages;
if (data.contains("lines"))
@ -169,7 +166,8 @@ void LogsPopup::getOverrustleLogs()
for (auto i : dataMessages)
{
QJsonObject singleMessage = i.toObject();
QTime timeStamp = QDateTime::fromSecsSinceEpoch(
QTime timeStamp =
QDateTime::fromSecsSinceEpoch(
singleMessage.value("timestamp").toInt())
.time();
@ -187,8 +185,7 @@ void LogsPopup::getOverrustleLogs()
this->setMessages(messages);
return Success;
});
req.execute();
})
.execute();
}
} // namespace chatterino

View file

@ -350,10 +350,9 @@ void UserInfoPopup::updateUserData()
QString url("https://api.twitch.tv/kraken/channels/" + id);
auto request = NetworkRequest::twitchRequest(url);
request.setCaller(this);
request.onSuccess([this](auto result) -> Outcome {
NetworkRequest::twitchRequest(url)
.caller(this)
.onSuccess([this](auto result) -> Outcome {
auto obj = result.parseJson();
this->ui_.followerCountLabel->setText(
TEXT_FOLLOWERS +
@ -367,9 +366,8 @@ void UserInfoPopup::updateUserData()
this->loadAvatar(QUrl(obj.value("logo").toString()));
return Success;
});
request.execute();
})
.execute();
// get follow state
currentUser->checkFollow(id, [this, hack](auto result) {

View file

@ -1,10 +1,10 @@
#pragma once
#include "common/FlagsEnum.hpp"
#include "messages/Image.hpp"
#include "messages/LimitedQueue.hpp"
#include "messages/LimitedQueueSnapshot.hpp"
#include "messages/Selection.hpp"
#include "messages/Image.hpp"
#include "widgets/BaseWidget.hpp"
#include <QPaintEvent>

View file

@ -218,9 +218,9 @@ void GeneralPage::initLayout(SettingsLayout &layout)
layout.addCheckbox("Hide moderated messages", s.hideModerated);
layout.addCheckbox("Hide moderation messages", s.hideModerationActions);
layout.addCheckbox("Colorize gray nicknames", s.colorizeNicknames);
layout.addDropdown<int>(
"Timeout stacking style", {"Stack", "Stack sparingly"},
s.timeoutStackStyle, [](int index) { return index; },
layout.addDropdown<int>("Timeout stacking style",
{"Stack", "Stack sparingly"}, s.timeoutStackStyle,
[](int index) { return index; },
[](auto args) { return args.index; }, false);
layout.addTitle("Emotes");
@ -278,11 +278,11 @@ void GeneralPage::initLayout(SettingsLayout &layout)
layout.addCheckbox("Double click links to open", s.linksDoubleClickOnly);
layout.addCheckbox("Unshorten links", s.unshortLinks);
layout.addCheckbox("Show live indicator in tabs", s.showTabLive);
layout.addDropdown<int>(
"Show emote preview in tooltip on hover",
{"Don't show", "Always show", "Hold shift"}, s.emotesTooltipPreview,
[](int index) { return index; }, [](auto args) { return args.index; },
false);
layout.addDropdown<int>("Show emote preview in tooltip on hover",
{"Don't show", "Always show", "Hold shift"},
s.emotesTooltipPreview,
[](int index) { return index; },
[](auto args) { return args.index; }, false);
layout.addCheckbox(
"Only search for emote autocompletion at the start of emote names",

View file

@ -554,12 +554,10 @@ void Split::showViewerList()
}
auto loadingLabel = new QLabel("Loading...");
auto request = NetworkRequest::twitchRequest(
"https://tmi.twitch.tv/group/user/" + this->getChannel()->getName() +
"/chatters");
request.setCaller(this);
request.onSuccess([=](auto result) -> Outcome {
NetworkRequest::twitchRequest("https://tmi.twitch.tv/group/user/" +
this->getChannel()->getName() + "/chatters")
.caller(this)
.onSuccess([=](auto result) -> Outcome {
auto obj = result.parseJson();
QJsonObject chattersObj = obj.value("chatters").toObject();
@ -579,9 +577,8 @@ void Split::showViewerList()
}
return Success;
});
request.execute();
})
.execute();
searchBar->setPlaceholderText("Search User...");
QObject::connect(searchBar, &QLineEdit::textEdited, this, [=]() {