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
+28 -30
View File
@@ -20,40 +20,38 @@ 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 {
auto root = result.parseJson();
auto statusCode = root.value("status").toInt();
QString response = QString();
QString linkString = url;
if (statusCode == 200)
{
response = root.value("tooltip").toString();
if (getSettings()->unshortLinks)
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();
QString linkString = url;
if (statusCode == 200)
{
linkString = root.value("link").toString();
response = root.value("tooltip").toString();
if (getSettings()->unshortLinks)
{
linkString = root.value("link").toString();
}
}
}
else
{
response = root.value("message").toString();
}
successCallback(QUrl::fromPercentEncoding(response.toUtf8()),
Link(Link::Url, linkString));
else
{
response = root.value("message").toString();
}
successCallback(QUrl::fromPercentEncoding(response.toUtf8()),
Link(Link::Url, linkString));
return Success;
});
return Success;
})
.onError([successCallback, url](auto /*result*/) {
successCallback("No link info found", Link(Link::Url, url));
request.onError([successCallback, url](auto result) {
successCallback("No link info found", Link(Link::Url, url));
return true;
});
request.execute();
return true;
})
.execute();
// });
}
+24 -29
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 {
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();
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;
})
.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 {
auto pair = parseChannelEmotes(result.parseJson());
if (pair.first)
callback(std::move(pair.second));
return pair.first;
});
request.execute();
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;
})
.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
+23 -23
View File
@@ -36,32 +36,32 @@ 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 {
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()}},
Tooltip{jsonBadge.value("tooltip").toString()}, Url{}};
emotes.push_back(std::make_shared<const Emote>(std::move(emote)));
for (const auto &user : jsonBadge.value("users").toArray())
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())
{
badgeMap[user.toString()] = index;
auto jsonBadge = jsonBadge_.toObject();
auto emote = Emote{
EmoteName{},
ImageSet{Url{jsonBadge.value("image").toString()}},
Tooltip{jsonBadge.value("tooltip").toString()}, Url{}};
emotes.push_back(
std::make_shared<const Emote>(std::move(emote)));
for (const auto &user : jsonBadge.value("users").toArray())
{
badgeMap[user.toString()] = index;
}
++index;
}
++index;
}
return Success;
});
req.execute();
return Success;
})
.execute();
}
} // namespace chatterino
+39 -45
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 {
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();
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;
})
.execute();
}
void FfzEmotes::loadChannel(const QString &channelName,
@@ -158,40 +156,36 @@ 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);
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;
})
.onError([channelName](int result) {
if (result == 203)
{
// User does not have any FFZ emotes
return true;
}
request.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
auto pair = parseChannelEmotes(result.parseJson());
if (pair.first)
callback(std::move(pair.second));
return pair.first;
});
if (result == -2)
{
// TODO: Auto retry in case of a timeout, with a delay
log("Fetching FFZ emotes for channel {} failed due to timeout",
channelName);
return true;
}
log("Error fetching FFZ emotes for channel {}, error {}",
channelName, result);
request.onError([channelName](int result) {
if (result == 203)
{
// User does not have any FFZ emotes
return true;
}
if (result == -2)
{
// TODO: Auto retry in case of a timeout, with a delay
log("Fetching FFZ emotes for channel {} failed due to timeout",
channelName);
return true;
}
log("Error fetching FFZ emotes for channel {}, error {}", channelName,
result);
return true;
});
request.execute();
})
.execute();
}
} // namespace chatterino
+25 -26
View File
@@ -22,38 +22,37 @@ 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 {
auto data = result.getData();
NetworkRequest(url)
.caller(QThread::currentThread())
.onSuccess([this, url](auto result) -> Outcome {
auto data = result.getData();
QBuffer buffer(const_cast<QByteArray *>(&data));
buffer.open(QIODevice::ReadOnly);
QImageReader reader(&buffer);
if (reader.imageCount() == 0)
return Failure;
QBuffer buffer(const_cast<QByteArray *>(&data));
buffer.open(QIODevice::ReadOnly);
QImageReader reader(&buffer);
if (reader.imageCount() == 0)
return Failure;
QPixmap badgeOverlay = QPixmap::fromImageReader(&reader);
QPixmap badgePixmap(18, 18);
QPixmap badgeOverlay = QPixmap::fromImageReader(&reader);
QPixmap badgePixmap(18, 18);
// the default mod badge green color
badgePixmap.fill(QColor("#34AE0A"));
QPainter painter(&badgePixmap);
QRectF rect(0, 0, 18, 18);
painter.drawPixmap(rect, badgeOverlay, rect);
// the default mod badge green color
badgePixmap.fill(QColor("#34AE0A"));
QPainter painter(&badgePixmap);
QRectF rect(0, 0, 18, 18);
painter.drawPixmap(rect, badgeOverlay, rect);
auto emote = Emote{{""},
ImageSet{Image::fromPixmap(badgePixmap)},
Tooltip{"Twitch Channel Moderator"},
Url{url}};
auto emote = Emote{{""},
ImageSet{Image::fromPixmap(badgePixmap)},
Tooltip{"Twitch Channel Moderator"},
Url{url}};
this->badge_ = std::make_shared<Emote>(emote);
// getBadge.execute();
this->badge_ = std::make_shared<Emote>(emote);
// getBadge.execute();
return Success;
});
req.execute();
return Success;
})
.execute();
}
EmotePtr FfzModBadge::badge() const
+38 -37
View File
@@ -36,45 +36,46 @@ 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());
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())
{
log("API Error while getting user id, users is not an array");
return Failure;
}
request.onSuccess([successCallback](auto result) -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray())
{
log("API Error while getting user id, users is not an array");
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 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");
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 "
"is not a "
"string");
return Failure;
}
successCallback(id.toString());
auto users = root.value("users").toArray();
if (users.size() != 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");
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 "
"is not a "
"string");
return Failure;
}
successCallback(id.toString());
return Success;
});
request.execute();
return Success;
})
.execute();
}
} // namespace chatterino
+238 -262
View File
@@ -94,59 +94,58 @@ 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 {
auto document = result.parseRapidJson();
if (!document.IsObject())
{
return Failure;
}
auto blocksIt = document.FindMember("blocks");
if (blocksIt == document.MemberEnd())
{
return Failure;
}
const auto &blocks = blocksIt->value;
if (!blocks.IsArray())
{
return Failure;
}
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
this->ignores_.clear();
for (const auto &block : blocks.GetArray())
NetworkRequest(url)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject())
{
if (!block.IsObject())
{
continue;
}
auto userIt = block.FindMember("user");
if (userIt == block.MemberEnd())
{
continue;
}
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser))
{
log("Error parsing twitch user JSON {}",
rj::stringify(userIt->value));
continue;
}
this->ignores_.insert(ignoredUser);
return Failure;
}
}
return Success;
});
auto blocksIt = document.FindMember("blocks");
if (blocksIt == document.MemberEnd())
{
return Failure;
}
const auto &blocks = blocksIt->value;
req.execute();
if (!blocks.IsArray())
{
return Failure;
}
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
this->ignores_.clear();
for (const auto &block : blocks.GetArray())
{
if (!block.IsObject())
{
continue;
}
auto userIt = block.FindMember("user");
if (userIt == block.MemberEnd())
{
continue;
}
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser))
{
log("Error parsing twitch user JSON {}",
rj::stringify(userIt->value));
continue;
}
this->ignores_.insert(ignoredUser);
}
}
return Success;
})
.execute();
}
void TwitchAccount::ignore(
@@ -167,64 +166,63 @@ 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) {
onFinished(IgnoreResult_Failed,
"An unknown error occured while trying to ignore user " +
targetName + " (" + QString::number(errorCode) + ")");
return true;
});
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject())
{
NetworkRequest(url, NetworkRequestType::Put)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user " + targetName);
return Failure;
}
"An unknown error occured while trying to ignore user " +
targetName + " (" + QString::number(errorCode) +
")");
auto userIt = document.FindMember("user");
if (userIt == document.MemberEnd())
{
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (missing user) " +
targetName);
return Failure;
}
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser))
{
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (invalid user) " +
targetName);
return Failure;
}
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
auto res = this->ignores_.insert(ignoredUser);
if (!res.second)
return true;
})
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject())
{
const TwitchUser &existingUser = *(res.first);
existingUser.update(ignoredUser);
onFinished(IgnoreResult_AlreadyIgnored,
"User " + targetName + " is already ignored");
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user " + targetName);
return Failure;
}
}
onFinished(IgnoreResult_Success,
"Successfully ignored user " + targetName);
return Success;
});
auto userIt = document.FindMember("user");
if (userIt == document.MemberEnd())
{
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (missing user) " +
targetName);
return Failure;
}
req.execute();
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser))
{
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (invalid user) " +
targetName);
return Failure;
}
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
auto res = this->ignores_.insert(ignoredUser);
if (!res.second)
{
const TwitchUser &existingUser = *(res.first);
existingUser.update(ignoredUser);
onFinished(IgnoreResult_AlreadyIgnored,
"User " + targetName + " is already ignored");
return Failure;
}
}
onFinished(IgnoreResult_Success,
"Successfully ignored user " + targetName);
return Success;
})
.execute();
}
void TwitchAccount::unignore(
@@ -246,34 +244,32 @@ 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());
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) + ")");
req.onError([=](int errorCode) {
onFinished(UnignoreResult_Failed,
"An unknown error occured while trying to unignore user " +
targetName + " (" + QString::number(errorCode) + ")");
return true;
})
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
TwitchUser ignoredUser;
ignoredUser.id = targetUserID;
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
return true;
});
this->ignores_.erase(ignoredUser);
}
onFinished(UnignoreResult_Success,
"Successfully unignored user " + targetName);
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
TwitchUser ignoredUser;
ignoredUser.id = targetUserID;
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
this->ignores_.erase(ignoredUser);
}
onFinished(UnignoreResult_Success,
"Successfully unignored user " + targetName);
return Success;
});
req.execute();
return Success;
})
.execute();
}
void TwitchAccount::checkFollow(const QString targetUserID,
@@ -282,30 +278,27 @@ 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());
NetworkRequest(url)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
if (errorCode == 203)
{
onFinished(FollowResult_NotFollowing);
}
else
{
onFinished(FollowResult_Failed);
}
req.onError([=](int errorCode) {
if (errorCode == 203)
{
onFinished(FollowResult_NotFollowing);
}
else
{
onFinished(FollowResult_Failed);
}
return true;
});
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
onFinished(FollowResult_Following);
return Success;
});
req.execute();
return true;
})
.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
onFinished(FollowResult_Following);
return Success;
})
.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());
NetworkRequest(requestUrl, NetworkRequestType::Put)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onSuccess([successCallback](auto result) -> Outcome {
// TODO: Properly check result of follow request
successCallback();
request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
// TODO: Properly check result of follow request
request.onSuccess([successCallback](auto result) -> Outcome {
successCallback();
return Success;
});
request.execute();
return Success;
})
.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());
NetworkRequest(requestUrl, NetworkRequestType::Delete)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([successCallback](int code) {
if (code >= 200 && code <= 299)
{
successCallback();
}
request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
request.onError([successCallback](int code) {
if (code >= 200 && code <= 299)
{
return true;
})
.onSuccess([successCallback](const auto &document) -> Outcome {
successCallback();
}
return true;
});
request.onSuccess([successCallback](const auto &document) -> Outcome {
successCallback();
return Success;
});
request.execute();
return Success;
})
.execute();
}
std::set<TwitchUser> TwitchAccount::getIgnores() const
@@ -381,31 +367,28 @@ 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());
NetworkRequest(url)
.caller(QThread::currentThread())
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](int errorCode) {
log("[TwitchAccount::loadEmotes] Error {}", errorCode);
if (errorCode == 203)
{
// onFinished(FollowResult_NotFollowing);
}
else
{
// onFinished(FollowResult_Failed);
}
req.onError([=](int errorCode) {
log("[TwitchAccount::loadEmotes] Error {}", errorCode);
if (errorCode == 203)
{
// onFinished(FollowResult_NotFollowing);
}
else
{
// onFinished(FollowResult_Failed);
}
return true;
})
.onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson());
return true;
});
req.onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson());
return Success;
});
req.execute();
return Success;
})
.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) {
log("[TwitchAccounts::autoModAllow] Error {}", errorCode);
return true;
});
req.execute();
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;
})
.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) {
log("[TwitchAccounts::autoModDeny] Error {}", errorCode);
return true;
});
req.execute();
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;
})
.execute();
}
void TwitchAccount::parseEmotes(const rapidjson::Document &root)
@@ -535,49 +514,46 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
return;
}
NetworkRequest req(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key));
req.setUseQuickLoadCache(true);
NetworkRequest(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key))
.cache()
.onError([](int errorCode) -> bool {
log("Error code {} while loading emote set data", errorCode);
return true;
})
.onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson();
if (!root.IsObject())
{
return Failure;
}
req.onError([](int errorCode) -> bool {
log("Error code {} while loading emote set data", errorCode);
return true;
});
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName))
{
return Failure;
}
req.onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson();
if (!root.IsObject())
{
return Failure;
}
if (!rj::getSafe(root, "type", type))
{
return Failure;
}
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName))
{
return Failure;
}
log("Loaded twitch emote set data for {}!", emoteSet->key);
if (!rj::getSafe(root, "type", type))
{
return Failure;
}
auto name = channelName;
name.detach();
name[0] = name[0].toUpper();
log("Loaded twitch emote set data for {}!", emoteSet->key);
emoteSet->text = name;
auto name = channelName;
name.detach();
name[0] = name[0].toUpper();
emoteSet->type = type;
emoteSet->channelName = channelName;
emoteSet->text = name;
emoteSet->type = type;
emoteSet->channelName = channelName;
return Success;
});
req.execute();
return Success;
})
.execute();
}
} // namespace chatterino
+60 -58
View File
@@ -15,46 +15,48 @@ 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 {
auto root = result.parseJson();
if (!root.value("users").isArray())
{
log("API Error while getting user id, users is not an array");
successCallback("");
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 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");
successCallback("");
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 "
"is not a "
"string");
successCallback("");
return Failure;
}
successCallback(id.toString());
return Success;
});
request.execute();
NetworkRequest(requestUrl)
.caller(QThread::currentThread())
.authorizeTwitchV5(getDefaultClientID())
.timeout(30000)
.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray())
{
log("API Error while getting user id, users is not an array");
successCallback("");
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 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");
successCallback("");
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 "
"is not a "
"string");
successCallback("");
return Failure;
}
successCallback(id.toString());
return Success;
})
.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 {
auto root = result.parseJson();
auto name = root.value("name");
if (!name.isString())
{
log("API Error: while getting user name, `name` is not a string");
successCallback("");
return Failure;
}
successCallback(name.toString());
return Success;
});
request.execute();
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");
successCallback("");
return Failure;
}
successCallback(name.toString());
return Success;
})
.execute();
}
} // namespace chatterino
+37 -33
View File
@@ -17,45 +17,49 @@ 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 {
auto root = result.parseJson();
auto badgeSets = this->badgeSets_.access();
NetworkRequest(url)
.caller(QThread::currentThread())
.onSuccess([this](auto result) -> Outcome {
auto root = result.parseJson();
auto badgeSets = this->badgeSets_.access();
auto jsonSets = root.value("badge_sets").toObject();
for (auto sIt = jsonSets.begin(); sIt != jsonSets.end(); ++sIt)
{
auto key = sIt.key();
auto versions = sIt.value().toObject().value("versions").toObject();
for (auto vIt = versions.begin(); vIt != versions.end(); ++vIt)
auto jsonSets = root.value("badge_sets").toObject();
for (auto sIt = jsonSets.begin(); sIt != jsonSets.end(); ++sIt)
{
auto versionObj = vIt.value().toObject();
auto key = sIt.key();
auto versions =
sIt.value().toObject().value("versions").toObject();
auto emote = Emote{
{""},
ImageSet{
Image::fromUrl(
{versionObj.value("image_url_1x").toString()}, 1),
Image::fromUrl(
{versionObj.value("image_url_2x").toString()}, .5),
Image::fromUrl(
{versionObj.value("image_url_4x").toString()}, .25),
},
Tooltip{versionObj.value("description").toString()},
Url{versionObj.value("click_url").toString()}};
// "title"
// "clickAction"
for (auto vIt = versions.begin(); vIt != versions.end(); ++vIt)
{
auto versionObj = vIt.value().toObject();
(*badgeSets)[key][vIt.key()] = std::make_shared<Emote>(emote);
auto emote = Emote{
{""},
ImageSet{
Image::fromUrl(
{versionObj.value("image_url_1x").toString()},
1),
Image::fromUrl(
{versionObj.value("image_url_2x").toString()},
.5),
Image::fromUrl(
{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);
}
}
}
return Success;
});
req.execute();
return Success;
})
.execute();
}
boost::optional<EmotePtr> TwitchBadges::badge(const QString &set,
+86 -95
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());
NetworkRequest::twitchRequest(url)
.caller(QThread::currentThread())
.onSuccess(
[this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared)
return Failure;
request.onSuccess(
[this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared)
return Failure;
return this->parseLiveStatus(result.parseRapidJson());
});
request.execute();
return this->parseLiveStatus(result.parseRapidJson());
})
.execute();
}
Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
@@ -608,42 +606,38 @@ 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);
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;
request.onSuccess([weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared)
return Failure;
auto messages = parseRecentMessages(result.parseJson(), shared);
auto messages = parseRecentMessages(result.parseJson(), shared);
auto &handler = IrcMessageHandler::getInstance();
auto &handler = IrcMessageHandler::getInstance();
std::vector<MessagePtr> allBuiltMessages;
std::vector<MessagePtr> allBuiltMessages;
for (auto message : messages)
{
for (auto builtMessage :
handler.parseMessage(shared.get(), message))
for (auto message : messages)
{
builtMessage->flags.set(MessageFlag::RecentMessage);
allBuiltMessages.emplace_back(builtMessage);
for (auto builtMessage :
handler.parseMessage(shared.get(), message))
{
builtMessage->flags.set(MessageFlag::RecentMessage);
allBuiltMessages.emplace_back(builtMessage);
}
}
}
postToThread(
[shared, messages = std::move(allBuiltMessages)]() mutable {
shared->addMessagesAtStart(messages);
});
postToThread(
[shared, messages = std::move(allBuiltMessages)]() mutable {
shared->addMessagesAtStart(messages);
});
return Success;
});
request.execute();
return Success;
})
.execute();
}
void TwitchChannel::refreshPubsub()
@@ -675,76 +669,73 @@ void TwitchChannel::refreshChatters()
}
// get viewer list
NetworkRequest request("https://tmi.twitch.tv/group/user/" +
this->getName() + "/chatters");
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();
if (!shared)
return Failure;
request.setCaller(QThread::currentThread());
request.onSuccess(
[this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
// channel still exists?
auto shared = weak.lock();
if (!shared)
return Failure;
auto pair = parseChatters(result.parseJson());
if (pair.first)
{
*this->chatters_.access() = std::move(pair.second);
}
auto pair = parseChatters(result.parseJson());
if (pair.first)
{
*this->chatters_.access() = std::move(pair.second);
}
return pair.first;
});
request.execute();
return pair.first;
})
.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());
NetworkRequest(url.string)
.caller(QThread::currentThread())
.onSuccess([this,
weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared)
return Failure;
req.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared)
return Failure;
auto badgeSets = this->badgeSets_.access();
auto badgeSets = this->badgeSets_.access();
auto jsonRoot = result.parseJson();
auto jsonRoot = result.parseJson();
auto _ = jsonRoot["badge_sets"].toObject();
for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end();
jsonBadgeSet++)
{
auto &versions = (*badgeSets)[jsonBadgeSet.key()];
auto _set = jsonBadgeSet->toObject()["versions"].toObject();
for (auto jsonVersion_ = _set.begin(); jsonVersion_ != _set.end();
jsonVersion_++)
auto _ = jsonRoot["badge_sets"].toObject();
for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end();
jsonBadgeSet++)
{
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)},
Tooltip{jsonVersion["description"].toString()},
Url{jsonVersion["clickURL"].toString()}});
auto &versions = (*badgeSets)[jsonBadgeSet.key()];
versions.emplace(jsonVersion_.key(), emote);
};
}
auto _set = jsonBadgeSet->toObject()["versions"].toObject();
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)},
Tooltip{jsonVersion["description"].toString()},
Url{jsonVersion["clickURL"].toString()}});
return Success;
});
versions.emplace(jsonVersion_.key(), emote);
};
}
req.execute();
return Success;
})
.execute();
}
void TwitchChannel::refreshCheerEmotes()