mirror-chatterino2/src/providers/twitch/TwitchAccount.cpp

385 lines
10 KiB
C++
Raw Normal View History

2018-06-26 14:09:39 +02:00
#include "providers/twitch/TwitchAccount.hpp"
2018-08-02 14:23:27 +02:00
#include <QThread>
#include "Application.hpp"
#include "common/Env.hpp"
2018-06-26 15:33:51 +02:00
#include "common/NetworkRequest.hpp"
#include "common/Outcome.hpp"
#include "common/QLogging.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include "providers/twitch/TwitchUser.hpp"
#include "providers/twitch/api/Helix.hpp"
2018-08-02 14:23:27 +02:00
#include "singletons/Emotes.hpp"
2018-06-26 17:20:03 +02:00
#include "util/RapidjsonHelpers.hpp"
2018-02-05 15:11:50 +01:00
namespace chatterino {
2018-07-06 19:23:47 +02:00
TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken,
const QString &oauthClient, const QString &userID)
2018-06-26 17:06:17 +02:00
: Account(ProviderId::Twitch)
2018-07-06 19:23:47 +02:00
, oauthClient_(oauthClient)
, oauthToken_(oauthToken)
, userName_(username)
, userId_(userID)
, isAnon_(username == ANONYMOUS_USERNAME)
2018-02-05 15:11:50 +01:00
{
}
2018-05-06 12:52:47 +02:00
QString TwitchAccount::toString() const
{
return this->getUserName();
}
2018-02-05 15:11:50 +01:00
const QString &TwitchAccount::getUserName() const
{
2018-07-06 19:23:47 +02:00
return this->userName_;
2018-02-05 15:11:50 +01:00
}
const QString &TwitchAccount::getOAuthClient() const
{
2018-07-06 19:23:47 +02:00
return this->oauthClient_;
2018-02-05 15:11:50 +01:00
}
const QString &TwitchAccount::getOAuthToken() const
{
2018-07-06 19:23:47 +02:00
return this->oauthToken_;
2018-02-05 15:11:50 +01:00
}
const QString &TwitchAccount::getUserId() const
{
2018-07-06 19:23:47 +02:00
return this->userId_;
2018-02-05 15:11:50 +01:00
}
QColor TwitchAccount::color()
{
return this->color_.get();
}
void TwitchAccount::setColor(QColor color)
{
this->color_.set(color);
}
2018-02-05 15:11:50 +01:00
bool TwitchAccount::setOAuthClient(const QString &newClientID)
{
2018-10-21 13:43:02 +02:00
if (this->oauthClient_.compare(newClientID) == 0)
{
2018-02-05 15:11:50 +01:00
return false;
}
2018-07-06 19:23:47 +02:00
this->oauthClient_ = newClientID;
2018-02-05 15:11:50 +01:00
return true;
}
bool TwitchAccount::setOAuthToken(const QString &newOAuthToken)
{
2018-10-21 13:43:02 +02:00
if (this->oauthToken_.compare(newOAuthToken) == 0)
{
2018-02-05 15:11:50 +01:00
return false;
}
2018-07-06 19:23:47 +02:00
this->oauthToken_ = newOAuthToken;
2018-02-05 15:11:50 +01:00
return true;
}
bool TwitchAccount::isAnon() const
{
2018-07-06 19:23:47 +02:00
return this->isAnon_;
2018-02-05 15:11:50 +01:00
}
void TwitchAccount::loadBlocks()
{
getHelix()->loadBlocks(
getApp()->accounts->twitch.getCurrent()->userId_,
[this](std::vector<HelixBlock> blocks) {
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
this->ignores_.clear();
for (const HelixBlock &block : blocks)
2018-10-21 13:43:02 +02:00
{
TwitchUser blockedUser;
blockedUser.fromHelixBlock(block);
this->ignores_.insert(blockedUser);
}
},
[] {
qDebug() << "Fetching blocks failed!";
});
}
void TwitchAccount::blockUser(QString userId, std::function<void()> onSuccess,
std::function<void()> onFailure)
{
getHelix()->blockUser(
userId,
[this, userId, onSuccess] {
TwitchUser blockedUser;
blockedUser.id = userId;
2019-08-20 21:50:36 +02:00
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
this->ignores_.insert(blockedUser);
2019-08-20 21:50:36 +02:00
}
onSuccess();
},
onFailure);
}
void TwitchAccount::unblockUser(QString userId, std::function<void()> onSuccess,
std::function<void()> onFailure)
{
getHelix()->unblockUser(
userId,
[this, userId, onSuccess] {
2019-08-20 21:50:36 +02:00
TwitchUser ignoredUser;
ignoredUser.id = userId;
2019-08-20 21:50:36 +02:00
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
2019-08-20 21:50:36 +02:00
this->ignores_.erase(ignoredUser);
}
onSuccess();
},
onFailure);
}
void TwitchAccount::checkFollow(const QString targetUserID,
std::function<void(FollowResult)> onFinished)
{
const auto onResponse = [onFinished](bool following, const auto &record) {
if (!following)
{
onFinished(FollowResult_NotFollowing);
return;
}
onFinished(FollowResult_Following);
};
Improvements to Message Search (#1237) * Ran clang-format * Implement user-specific search in message history This functionality was originally requested in #1236. This commit changes the SearchPopup::performSearch method so that only messages from specific users can be shown. In order to filter for a specific user, enter their username with a leading '@' in the search popup. You can also add an additional search phrase which will also be considered in the search. * Naive implementation for "from:" tags Rebase later? * Cleverer (?) version using Predicates Commit adds two POC predicates: one for the author of messages, and one for substring search in messages. Problems/TODOs: * Best way to register new predicates? * Clean up tags (e.g. "from:") or not? * Test combinations of different predicates * Add a predicate to check for links in messages * Remove a dumb TODO * Rewrite SearchPopup::performSearch to be cleaner * Ran clang-format on all files * Remove TODO I missed earlier * Forgot to run clang-format peepoSadDank * Re-use {}-initialization Was accidentally removed when fixing earlier merge conflict. * Does this fix line endings? No diffs are shown locally, hopefully Git doesn't lie to me. * Rename "predicates" directory to "search" Resolving one conversation in the review of #1237. * Use LinkParser in LinkPredicate Resolving a conversation in the review of #1237. * Predicates: Use unique_ptr instead of shared_ptr Resolves a conversation in the review of #1237. * Refactor of SearchPopup and AuthorPredicate Resolving some points from the review in #1237. * Moved parsing of comma-seperated values into AuthorPredicate constructor. * Rewrite SearchPopup::parsePredicates as suggested. * Deleted now redundant methods in SearchPopup. * MessagePredicate::appliesTo now takes a Message& ... instead of a MessagePtr. This resolves a conversation in the review of #1237. * Run clang-format on two files I missed * AuthorPredicate: Check for displayName & loginName Resolving conversation on #1237.
2019-09-09 15:21:49 +02:00
getHelix()->getUserFollow(this->getUserId(), targetUserID, onResponse,
[] {});
}
std::set<TwitchUser> TwitchAccount::getBlocks() const
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
2018-07-06 19:23:47 +02:00
return this->ignores_;
}
2018-08-02 14:23:27 +02:00
void TwitchAccount::loadEmotes()
{
qCDebug(chatterinoTwitch)
<< "Loading Twitch emotes for user" << this->getUserName();
const auto &clientID = this->getOAuthClient();
const auto &oauthToken = this->getOAuthToken();
2018-10-21 13:43:02 +02:00
if (clientID.isEmpty() || oauthToken.isEmpty())
{
qCDebug(chatterinoTwitch) << "Missing Client ID or OAuth token";
return;
}
2018-08-06 21:17:03 +02:00
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/emotes");
2019-08-20 21:50:36 +02:00
NetworkRequest(url)
Improvements to Message Search (#1237) * Ran clang-format * Implement user-specific search in message history This functionality was originally requested in #1236. This commit changes the SearchPopup::performSearch method so that only messages from specific users can be shown. In order to filter for a specific user, enter their username with a leading '@' in the search popup. You can also add an additional search phrase which will also be considered in the search. * Naive implementation for "from:" tags Rebase later? * Cleverer (?) version using Predicates Commit adds two POC predicates: one for the author of messages, and one for substring search in messages. Problems/TODOs: * Best way to register new predicates? * Clean up tags (e.g. "from:") or not? * Test combinations of different predicates * Add a predicate to check for links in messages * Remove a dumb TODO * Rewrite SearchPopup::performSearch to be cleaner * Ran clang-format on all files * Remove TODO I missed earlier * Forgot to run clang-format peepoSadDank * Re-use {}-initialization Was accidentally removed when fixing earlier merge conflict. * Does this fix line endings? No diffs are shown locally, hopefully Git doesn't lie to me. * Rename "predicates" directory to "search" Resolving one conversation in the review of #1237. * Use LinkParser in LinkPredicate Resolving a conversation in the review of #1237. * Predicates: Use unique_ptr instead of shared_ptr Resolves a conversation in the review of #1237. * Refactor of SearchPopup and AuthorPredicate Resolving some points from the review in #1237. * Moved parsing of comma-seperated values into AuthorPredicate constructor. * Rewrite SearchPopup::parsePredicates as suggested. * Deleted now redundant methods in SearchPopup. * MessagePredicate::appliesTo now takes a Message& ... instead of a MessagePtr. This resolves a conversation in the review of #1237. * Run clang-format on two files I missed * AuthorPredicate: Check for displayName & loginName Resolving conversation on #1237.
2019-09-09 15:21:49 +02:00
2019-08-20 21:50:36 +02:00
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](NetworkResult result) {
qCWarning(chatterinoTwitch)
<< "[TwitchAccount::loadEmotes] Error" << result.status();
if (result.status() == 203)
2019-08-20 21:50:36 +02:00
{
// onFinished(FollowResult_NotFollowing);
}
else
{
// onFinished(FollowResult_Failed);
}
})
.onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson());
2018-08-02 14:23:27 +02:00
2019-08-20 21:50:36 +02:00
return Success;
})
.execute();
2018-08-02 14:23:27 +02:00
}
2018-08-06 21:17:03 +02:00
AccessGuard<const TwitchAccount::TwitchAccountEmoteData>
2018-08-15 22:46:20 +02:00
TwitchAccount::accessEmotes() const
2018-08-02 14:23:27 +02:00
{
return this->emotes_.accessConst();
}
// AutoModActions
2019-01-20 16:07:31 +01:00
void TwitchAccount::autoModAllow(const QString msgID)
2019-01-20 14:47:04 +01:00
{
2019-01-20 16:07:31 +01:00
QString url("https://api.twitch.tv/kraken/chat/twitchbot/approve");
auto qba = (QString("{\"msg_id\":\"") + msgID + "\"}").toUtf8();
2019-08-20 21:50:36 +02:00
NetworkRequest(url, NetworkRequestType::Post)
.header("Content-Type", "application/json")
.header("Content-Length", QByteArray::number(qba.size()))
.payload(qba)
Improvements to Message Search (#1237) * Ran clang-format * Implement user-specific search in message history This functionality was originally requested in #1236. This commit changes the SearchPopup::performSearch method so that only messages from specific users can be shown. In order to filter for a specific user, enter their username with a leading '@' in the search popup. You can also add an additional search phrase which will also be considered in the search. * Naive implementation for "from:" tags Rebase later? * Cleverer (?) version using Predicates Commit adds two POC predicates: one for the author of messages, and one for substring search in messages. Problems/TODOs: * Best way to register new predicates? * Clean up tags (e.g. "from:") or not? * Test combinations of different predicates * Add a predicate to check for links in messages * Remove a dumb TODO * Rewrite SearchPopup::performSearch to be cleaner * Ran clang-format on all files * Remove TODO I missed earlier * Forgot to run clang-format peepoSadDank * Re-use {}-initialization Was accidentally removed when fixing earlier merge conflict. * Does this fix line endings? No diffs are shown locally, hopefully Git doesn't lie to me. * Rename "predicates" directory to "search" Resolving one conversation in the review of #1237. * Use LinkParser in LinkPredicate Resolving a conversation in the review of #1237. * Predicates: Use unique_ptr instead of shared_ptr Resolves a conversation in the review of #1237. * Refactor of SearchPopup and AuthorPredicate Resolving some points from the review in #1237. * Moved parsing of comma-seperated values into AuthorPredicate constructor. * Rewrite SearchPopup::parsePredicates as suggested. * Deleted now redundant methods in SearchPopup. * MessagePredicate::appliesTo now takes a Message& ... instead of a MessagePtr. This resolves a conversation in the review of #1237. * Run clang-format on two files I missed * AuthorPredicate: Check for displayName & loginName Resolving conversation on #1237.
2019-09-09 15:21:49 +02:00
2019-08-20 21:50:36 +02:00
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](NetworkResult result) {
qCWarning(chatterinoTwitch)
<< "[TwitchAccounts::autoModAllow] Error" << result.status();
2019-08-20 21:50:36 +02:00
})
.execute();
2019-01-20 14:47:04 +01:00
}
2019-01-20 16:07:31 +01:00
void TwitchAccount::autoModDeny(const QString msgID)
2019-01-20 14:47:04 +01:00
{
2019-01-20 16:07:31 +01:00
QString url("https://api.twitch.tv/kraken/chat/twitchbot/deny");
auto qba = (QString("{\"msg_id\":\"") + msgID + "\"}").toUtf8();
2019-08-20 21:50:36 +02:00
NetworkRequest(url, NetworkRequestType::Post)
.header("Content-Type", "application/json")
.header("Content-Length", QByteArray::number(qba.size()))
.payload(qba)
Improvements to Message Search (#1237) * Ran clang-format * Implement user-specific search in message history This functionality was originally requested in #1236. This commit changes the SearchPopup::performSearch method so that only messages from specific users can be shown. In order to filter for a specific user, enter their username with a leading '@' in the search popup. You can also add an additional search phrase which will also be considered in the search. * Naive implementation for "from:" tags Rebase later? * Cleverer (?) version using Predicates Commit adds two POC predicates: one for the author of messages, and one for substring search in messages. Problems/TODOs: * Best way to register new predicates? * Clean up tags (e.g. "from:") or not? * Test combinations of different predicates * Add a predicate to check for links in messages * Remove a dumb TODO * Rewrite SearchPopup::performSearch to be cleaner * Ran clang-format on all files * Remove TODO I missed earlier * Forgot to run clang-format peepoSadDank * Re-use {}-initialization Was accidentally removed when fixing earlier merge conflict. * Does this fix line endings? No diffs are shown locally, hopefully Git doesn't lie to me. * Rename "predicates" directory to "search" Resolving one conversation in the review of #1237. * Use LinkParser in LinkPredicate Resolving a conversation in the review of #1237. * Predicates: Use unique_ptr instead of shared_ptr Resolves a conversation in the review of #1237. * Refactor of SearchPopup and AuthorPredicate Resolving some points from the review in #1237. * Moved parsing of comma-seperated values into AuthorPredicate constructor. * Rewrite SearchPopup::parsePredicates as suggested. * Deleted now redundant methods in SearchPopup. * MessagePredicate::appliesTo now takes a Message& ... instead of a MessagePtr. This resolves a conversation in the review of #1237. * Run clang-format on two files I missed * AuthorPredicate: Check for displayName & loginName Resolving conversation on #1237.
2019-09-09 15:21:49 +02:00
2019-08-20 21:50:36 +02:00
.authorizeTwitchV5(this->getOAuthClient(), this->getOAuthToken())
.onError([=](NetworkResult result) {
qCWarning(chatterinoTwitch)
<< "[TwitchAccounts::autoModDeny] Error" << result.status();
2019-08-20 21:50:36 +02:00
})
.execute();
2019-01-20 14:47:04 +01:00
}
2018-08-02 14:23:27 +02:00
void TwitchAccount::parseEmotes(const rapidjson::Document &root)
{
auto emoteData = this->emotes_.access();
emoteData->emoteSets.clear();
emoteData->allEmoteNames.clear();
auto emoticonSets = root.FindMember("emoticon_sets");
2018-10-21 13:43:02 +02:00
if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject())
{
qCWarning(chatterinoTwitch)
<< "No emoticon_sets in load emotes response";
2018-08-02 14:23:27 +02:00
return;
}
2018-10-21 13:43:02 +02:00
for (const auto &emoteSetJSON : emoticonSets->value.GetObject())
{
2018-08-02 14:23:27 +02:00
auto emoteSet = std::make_shared<EmoteSet>();
emoteSet->key = emoteSetJSON.name.GetString();
this->loadEmoteSetData(emoteSet);
2018-10-21 13:43:02 +02:00
for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray())
{
if (!emoteJSON.IsObject())
{
qCWarning(chatterinoTwitch) << "Emote value was invalid";
2018-08-02 14:23:27 +02:00
return;
}
uint64_t idNumber;
2018-10-21 13:43:02 +02:00
if (!rj::getSafe(emoteJSON, "id", idNumber))
{
qCWarning(chatterinoTwitch) << "No ID key found in Emote value";
2018-08-02 14:23:27 +02:00
return;
}
2018-08-07 06:25:58 +02:00
QString _code;
2018-10-21 13:43:02 +02:00
if (!rj::getSafe(emoteJSON, "code", _code))
{
qCWarning(chatterinoTwitch)
<< "No code key found in Emote value";
2018-08-02 14:23:27 +02:00
return;
}
2018-08-07 06:25:58 +02:00
auto code = EmoteName{_code};
2018-08-02 14:23:27 +02:00
auto id = EmoteId{QString::number(idNumber)};
auto cleanCode = EmoteName{TwitchEmotes::cleanUpEmoteCode(code)};
2018-08-02 14:23:27 +02:00
emoteSet->emotes.emplace_back(TwitchEmote{id, cleanCode});
emoteData->allEmoteNames.push_back(cleanCode);
auto emote = getApp()->emotes->twitch.getOrCreateEmote(id, code);
emoteData->emotes.emplace(code, emote);
}
std::sort(emoteSet->emotes.begin(), emoteSet->emotes.end(),
[](const TwitchEmote &l, const TwitchEmote &r) {
return l.name.string < r.name.string;
});
2018-08-02 14:23:27 +02:00
emoteData->emoteSets.emplace_back(emoteSet);
}
};
void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
{
2018-10-21 13:43:02 +02:00
if (!emoteSet)
{
qCWarning(chatterinoTwitch) << "null emote set sent";
2018-08-02 14:23:27 +02:00
return;
}
auto staticSetIt = this->staticEmoteSets.find(emoteSet->key);
2018-10-21 13:43:02 +02:00
if (staticSetIt != this->staticEmoteSets.end())
{
2018-08-02 14:23:27 +02:00
const auto &staticSet = staticSetIt->second;
emoteSet->channelName = staticSet.channelName;
emoteSet->text = staticSet.text;
return;
}
2019-08-20 21:50:36 +02:00
NetworkRequest(Env::get().twitchEmoteSetResolverUrl.arg(emoteSet->key))
.cache()
.onError([](NetworkResult result) {
qCWarning(chatterinoTwitch) << "Error code" << result.status()
<< "while loading emote set data";
2019-08-20 21:50:36 +02:00
})
.onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson();
if (!root.IsObject())
{
return Failure;
}
2018-08-02 14:23:27 +02:00
2019-08-20 21:50:36 +02:00
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName))
{
return Failure;
}
2018-08-02 14:23:27 +02:00
2019-08-20 21:50:36 +02:00
if (!rj::getSafe(root, "type", type))
{
return Failure;
}
2018-08-02 14:23:27 +02:00
qCDebug(chatterinoTwitch)
<< "Loaded twitch emote set data for" << emoteSet->key;
2018-08-11 14:20:53 +02:00
2019-08-20 21:50:36 +02:00
auto name = channelName;
name.detach();
name[0] = name[0].toUpper();
2018-08-02 14:23:27 +02:00
2019-08-20 21:50:36 +02:00
emoteSet->text = name;
2018-08-02 14:23:27 +02:00
2019-08-20 21:50:36 +02:00
emoteSet->type = type;
emoteSet->channelName = channelName;
2018-08-02 14:23:27 +02:00
2019-08-20 21:50:36 +02:00
return Success;
})
.execute();
}
2018-02-05 15:11:50 +01:00
} // namespace chatterino