changed to 80 max column

This commit is contained in:
fourtf
2018-08-06 21:17:03 +02:00
parent defa7e41fa
commit f71ff08e68
203 changed files with 3792 additions and 2405 deletions
+16 -11
View File
@@ -13,11 +13,13 @@ namespace chatterino {
namespace {
Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale)
Url getEmoteLink(QString urlTemplate, const EmoteId &id,
const QString &emoteScale)
{
urlTemplate.detach();
return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)};
return {urlTemplate.replace("{{id}}", id.string)
.replace("{{image}}", emoteScale)};
}
} // namespace
@@ -76,23 +78,26 @@ void BttvEmotes::loadGlobalEmotes()
request.execute();
}
std::pair<Outcome, EmoteMap> BttvEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot,
const EmoteMap &currentEmotes)
std::pair<Outcome, EmoteMap> BttvEmotes::parseGlobalEmotes(
const QJsonObject &jsonRoot, const EmoteMap &currentEmotes)
{
auto emotes = EmoteMap();
auto jsonEmotes = jsonRoot.value("emotes").toArray();
auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString());
auto urlTemplate =
QString("https:" + jsonRoot.value("urlTemplate").toString());
for (const QJsonValue &jsonEmote : jsonEmotes) {
auto id = EmoteId{jsonEmote.toObject().value("id").toString()};
auto name = EmoteName{jsonEmote.toObject().value("code").toString()};
auto emote = Emote({name,
ImageSet{Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1),
Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5),
Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)},
Tooltip{name.string + "<br />Global Bttv Emote"},
Url{"https://manage.betterttv.net/emotes/" + id.string}});
auto emote = Emote(
{name,
ImageSet{
Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1),
Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5),
Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)},
Tooltip{name.string + "<br />Global Bttv Emote"},
Url{"https://manage.betterttv.net/emotes/" + id.string}});
auto it = currentEmotes.find(name);
if (it != currentEmotes.end() && *it->second == emote) {
+4 -3
View File
@@ -10,7 +10,8 @@ namespace chatterino {
class BttvEmotes final : std::enable_shared_from_this<BttvEmotes>
{
static constexpr const char *globalEmoteApiUrl = "https://api.betterttv.net/2/emotes";
static constexpr const char *globalEmoteApiUrl =
"https://api.betterttv.net/2/emotes";
public:
// BttvEmotes();
@@ -22,8 +23,8 @@ public:
void loadGlobalEmotes();
private:
std::pair<Outcome, EmoteMap> parseGlobalEmotes(const QJsonObject &jsonRoot,
const EmoteMap &currentEmotes);
std::pair<Outcome, EmoteMap> parseGlobalEmotes(
const QJsonObject &jsonRoot, const EmoteMap &currentEmotes);
UniqueAccess<EmoteMap> globalEmotes_;
// UniqueAccess<WeakEmoteIdMap> channelEmoteCache_;
+28 -16
View File
@@ -11,12 +11,16 @@
namespace chatterino {
static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale);
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(const QJsonObject &jsonRoot);
static Url getEmoteLink(QString urlTemplate, const EmoteId &id,
const QString &emoteScale);
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(
const QJsonObject &jsonRoot);
void loadBttvChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback)
void loadBttvChannelEmotes(const QString &channelName,
std::function<void(EmoteMap &&)> callback)
{
auto request = NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName);
auto request =
NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
@@ -31,14 +35,17 @@ void loadBttvChannelEmotes(const QString &channelName, std::function<void(EmoteM
request.execute();
}
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(const QJsonObject &jsonRoot)
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(
const QJsonObject &jsonRoot)
{
static UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<const Emote>>> cache_;
static UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<const Emote>>>
cache_;
auto cache = cache_.access();
auto emotes = EmoteMap();
auto jsonEmotes = jsonRoot.value("emotes").toArray();
auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString());
auto urlTemplate =
QString("https:" + jsonRoot.value("urlTemplate").toString());
for (auto jsonEmote_ : jsonEmotes) {
auto jsonEmote = jsonEmote_.toObject();
@@ -47,30 +54,35 @@ static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(const QJsonObject &js
auto name = EmoteName{jsonEmote.value("code").toString()};
// emoteObject.value("imageType").toString();
auto emote = Emote({name,
ImageSet{Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1),
Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5),
Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)},
Tooltip{name.string + "<br />Channel Bttv Emote"},
Url{"https://manage.betterttv.net/emotes/" + id.string}});
auto emote = Emote(
{name,
ImageSet{
Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1),
Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5),
Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)},
Tooltip{name.string + "<br />Channel Bttv Emote"},
Url{"https://manage.betterttv.net/emotes/" + id.string}});
auto shared = (*cache)[id].lock();
if (shared && *shared == emote) {
// reuse old shared_ptr if nothing changed
emotes[name] = shared;
} else {
(*cache)[id] = emotes[name] = std::make_shared<Emote>(std::move(emote));
(*cache)[id] = emotes[name] =
std::make_shared<Emote>(std::move(emote));
}
}
return {Success, std::move(emotes)};
}
static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale)
static Url getEmoteLink(QString urlTemplate, const EmoteId &id,
const QString &emoteScale)
{
urlTemplate.detach();
return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)};
return {urlTemplate.replace("{{id}}", id.string)
.replace("{{image}}", emoteScale)};
}
} // namespace chatterino
+4 -2
View File
@@ -7,8 +7,10 @@ class QString;
namespace chatterino {
class EmoteMap;
constexpr const char *bttvChannelEmoteApiUrl = "https://api.betterttv.net/2/channels/";
constexpr const char *bttvChannelEmoteApiUrl =
"https://api.betterttv.net/2/channels/";
void loadBttvChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback);
void loadBttvChannelEmotes(const QString &channelName,
std::function<void(EmoteMap &&)> callback);
} // namespace chatterino
@@ -32,11 +32,13 @@ void ChatterinoBadges::loadChatterinoBadges()
for (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{}};
auto emote = Emote{
EmoteName{}, ImageSet{Url{jsonBadge.value("image").toString()}},
Tooltip{jsonBadge.value("tooltip").toString()}, Url{}};
for (auto jsonUser : jsonBadge.value("users").toArray()) {
replacement.add(UserName{jsonUser.toString()}, std::move(emote));
replacement.add(UserName{jsonUser.toString()},
std::move(emote));
}
}
+40 -25
View File
@@ -15,7 +15,8 @@ namespace chatterino {
namespace {
void parseEmoji(const std::shared_ptr<EmojiData> &emojiData, const rapidjson::Value &unparsedEmoji,
void parseEmoji(const std::shared_ptr<EmojiData> &emojiData,
const rapidjson::Value &unparsedEmoji,
QString shortCode = QString())
{
static uint unicodeBytes[4];
@@ -80,7 +81,8 @@ void parseEmoji(const std::shared_ptr<EmojiData> &emojiData, const rapidjson::Va
int numUnicodeBytes = 0;
for (const QString &unicodeCharacter : unicodeCharacters) {
unicodeBytes[numUnicodeBytes++] = QString(unicodeCharacter).toUInt(nullptr, 16);
unicodeBytes[numUnicodeBytes++] =
QString(unicodeCharacter).toUInt(nullptr, 16);
}
emojiData->value = QString::fromUcs4(unicodeBytes, numUnicodeBytes);
@@ -116,8 +118,8 @@ void Emojis::loadEmojis()
rapidjson::ParseResult result = root.Parse(data.toUtf8(), data.length());
if (result.Code() != rapidjson::kParseErrorNone) {
Log("JSON parse error: {} ({})", rapidjson::GetParseError_En(result.Code()),
result.Offset());
Log("JSON parse error: {} ({})",
rapidjson::GetParseError_En(result.Code()), result.Offset());
return;
}
@@ -135,7 +137,8 @@ void Emojis::loadEmojis()
this->emojis.insert(emojiData->unifiedCode, emojiData);
if (unparsedEmoji.HasMember("skin_variations")) {
for (const auto &skinVariation : unparsedEmoji["skin_variations"].GetObject()) {
for (const auto &skinVariation :
unparsedEmoji["skin_variations"].GetObject()) {
std::string tone = skinVariation.name.GetString();
const auto &variation = skinVariation.value;
@@ -143,20 +146,23 @@ void Emojis::loadEmojis()
auto toneNameIt = toneNames.find(tone);
if (toneNameIt == toneNames.end()) {
Log("Tone with key {} does not exist in tone names map", tone);
Log("Tone with key {} does not exist in tone names map",
tone);
continue;
}
parseEmoji(variationEmojiData, variation,
emojiData->shortCodes[0] + "_" + toneNameIt->second);
this->emojiShortCodeToEmoji_.insert(variationEmojiData->shortCodes[0],
variationEmojiData);
this->emojiShortCodeToEmoji_.insert(
variationEmojiData->shortCodes[0], variationEmojiData);
this->shortCodes.push_back(variationEmojiData->shortCodes[0]);
this->emojiFirstByte_[variationEmojiData->value.at(0)].append(variationEmojiData);
this->emojiFirstByte_[variationEmojiData->value.at(0)].append(
variationEmojiData);
this->emojis.insert(variationEmojiData->unifiedCode, variationEmojiData);
this->emojis.insert(variationEmojiData->unifiedCode,
variationEmojiData);
}
}
}
@@ -196,14 +202,16 @@ void Emojis::loadEmojiOne2Capabilities()
void Emojis::sortEmojis()
{
for (auto &p : this->emojiFirstByte_) {
std::stable_sort(p.begin(), p.end(), [](const auto &lhs, const auto &rhs) {
return lhs->value.length() > rhs->value.length();
});
std::stable_sort(p.begin(), p.end(),
[](const auto &lhs, const auto &rhs) {
return lhs->value.length() > rhs->value.length();
});
}
auto &p = this->shortCodes;
std::stable_sort(p.begin(), p.end(),
[](const auto &lhs, const auto &rhs) { return lhs < rhs; });
std::stable_sort(p.begin(), p.end(), [](const auto &lhs, const auto &rhs) {
return lhs < rhs;
});
}
void Emojis::loadEmojiSet()
@@ -212,7 +220,8 @@ void Emojis::loadEmojiSet()
app->settings->emojiSet.connect([=](const auto &emojiSet, auto) {
Log("Using emoji set {}", emojiSet);
this->emojis.each([=](const auto &name, std::shared_ptr<EmojiData> &emoji) {
this->emojis.each([=](const auto &name,
std::shared_ptr<EmojiData> &emoji) {
QString emojiSetToUse = emojiSet;
// clang-format off
static std::map<QString, QString> emojiSets = {
@@ -259,20 +268,22 @@ void Emojis::loadEmojiSet()
}
}
code = code.toLower();
QString urlPrefix = "https://cdnjs.cloudflare.com/ajax/libs/emojione/2.2.6/assets/png/";
QString urlPrefix = "https://cdnjs.cloudflare.com/ajax/libs/"
"emojione/2.2.6/assets/png/";
auto it = emojiSets.find(emojiSetToUse);
if (it != emojiSets.end()) {
urlPrefix = it->second;
}
QString url = urlPrefix + code + ".png";
emoji->emote = std::make_shared<Emote>(
Emote{EmoteName{emoji->value}, ImageSet{Image::fromUrl({url}, 0.35)},
Tooltip{":" + emoji->shortCodes[0] + ":<br/>Emoji"}, Url{}});
emoji->emote = std::make_shared<Emote>(Emote{
EmoteName{emoji->value}, ImageSet{Image::fromUrl({url}, 0.35)},
Tooltip{":" + emoji->shortCodes[0] + ":<br/>Emoji"}, Url{}});
});
});
}
std::vector<boost::variant<EmotePtr, QString>> Emojis::parse(const QString &text)
std::vector<boost::variant<EmotePtr, QString>> Emojis::parse(
const QString &text)
{
auto result = std::vector<boost::variant<EmotePtr, QString>>();
int lastParsedEmojiEndIndex = 0;
@@ -330,11 +341,13 @@ std::vector<boost::variant<EmotePtr, QString>> Emojis::parse(const QString &text
int currentParsedEmojiFirstIndex = i;
int currentParsedEmojiEndIndex = i + (matchedEmojiLength);
int charactersFromLastParsedEmoji = currentParsedEmojiFirstIndex - lastParsedEmojiEndIndex;
int charactersFromLastParsedEmoji =
currentParsedEmojiFirstIndex - lastParsedEmojiEndIndex;
if (charactersFromLastParsedEmoji > 0) {
// Add characters inbetween emojis
result.emplace_back(text.mid(lastParsedEmojiEndIndex, charactersFromLastParsedEmoji));
result.emplace_back(text.mid(lastParsedEmojiEndIndex,
charactersFromLastParsedEmoji));
}
// Push the emoji as a word to parsedWords
@@ -365,7 +378,8 @@ QString Emojis::replaceShortCodes(const QString &text)
auto capturedString = match.captured();
QString matchString = capturedString.toLower().mid(1, capturedString.size() - 2);
QString matchString =
capturedString.toLower().mid(1, capturedString.size() - 2);
auto emojiIt = this->emojiShortCodeToEmoji_.constFind(matchString);
@@ -375,7 +389,8 @@ QString Emojis::replaceShortCodes(const QString &text)
auto emojiData = emojiIt.value();
ret.replace(offset + match.capturedStart(), match.capturedLength(), emojiData->value);
ret.replace(offset + match.capturedStart(), match.capturedLength(),
emojiData->value);
offset += emojiData->value.size() - match.capturedLength();
}
+4 -2
View File
@@ -15,7 +15,8 @@
namespace chatterino {
struct EmojiData {
// actual byte-representation of the emoji (i.e. \154075\156150 which is :male:)
// actual byte-representation of the emoji (i.e. \154075\156150 which is
// :male:)
QString value;
// i.e. 204e-50a2
@@ -57,7 +58,8 @@ private:
// shortCodeToEmoji maps strings like "sunglasses" to its emoji
QMap<QString, std::shared_ptr<EmojiData>> emojiShortCodeToEmoji_;
// Maps the first character of the emoji unicode string to a vector of possible emojis
// Maps the first character of the emoji unicode string to a vector of
// possible emojis
QMap<QChar, QVector<std::shared_ptr<EmojiData>>> emojiFirstByte_;
};
+19 -13
View File
@@ -20,8 +20,8 @@ Url getEmoteLink(const QJsonObject &urls, const QString &emoteScale)
return {"https:" + emote.toString()};
}
void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, const QString &tooltip,
Emote &emoteData)
void fillInEmoteData(const QJsonObject &urls, const EmoteName &name,
const QString &tooltip, Emote &emoteData)
{
auto url1x = getEmoteLink(urls, "1");
auto url2x = getEmoteLink(urls, "2");
@@ -30,7 +30,8 @@ void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, const QStri
//, code, tooltip
emoteData.name = name;
emoteData.images =
ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), Image::fromUrl(url3x, 0.25)};
ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5),
Image::fromUrl(url3x, 0.25)};
emoteData.tooltip = {tooltip};
}
} // namespace
@@ -67,8 +68,9 @@ void FfzEmotes::loadGlobalEmotes()
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess(
[this](auto result) -> Outcome { return this->parseGlobalEmotes(result.parseJson()); });
request.onSuccess([this](auto result) -> Outcome {
return this->parseGlobalEmotes(result.parseJson());
});
request.execute();
}
@@ -90,10 +92,12 @@ Outcome FfzEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot)
auto urls = jsonEmote.value("urls").toObject();
auto emote = Emote();
fillInEmoteData(urls, name, name.string + "<br/>Global FFZ Emote", emote);
emote.homePage = Url{QString("https://www.frankerfacez.com/emoticon/%1-%2")
.arg(id.string)
.arg(name.string)};
fillInEmoteData(urls, name, name.string + "<br/>Global FFZ Emote",
emote);
emote.homePage =
Url{QString("https://www.frankerfacez.com/emoticon/%1-%2")
.arg(id.string)
.arg(name.string)};
replacement.add(name, emote);
}
@@ -105,7 +109,8 @@ Outcome FfzEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot)
void FfzEmotes::loadChannelEmotes(const QString &channelName,
std::function<void(EmoteMap &&)> callback)
{
// printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", qPrintable(channelName));
// printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n",
// qPrintable(channelName));
// QString url("https://api.frankerfacez.com/v1/room/" + channelName);
@@ -145,10 +150,11 @@ Outcome parseChannelEmotes(const QJsonObject &jsonRoot)
// QJsonObject urls = emoteObject.value("urls").toObject();
// auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, &urls] {
// auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code,
// &urls] {
// EmoteData emoteData;
// fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote", emoteData);
// emoteData.pageLink =
// fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote",
// emoteData); emoteData.pageLink =
// QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
// return emoteData;
+6 -3
View File
@@ -10,8 +10,10 @@ namespace chatterino {
class FfzEmotes final : std::enable_shared_from_this<FfzEmotes>
{
static constexpr const char *globalEmoteApiUrl = "https://api.frankerfacez.com/v1/set/global";
static constexpr const char *channelEmoteApiUrl = "https://api.betterttv.net/2/channels/";
static constexpr const char *globalEmoteApiUrl =
"https://api.frankerfacez.com/v1/set/global";
static constexpr const char *channelEmoteApiUrl =
"https://api.betterttv.net/2/channels/";
public:
// FfzEmotes();
@@ -23,7 +25,8 @@ public:
boost::optional<EmotePtr> getEmote(const EmoteId &id);
void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback);
void loadChannelEmotes(const QString &channelName,
std::function<void(EmoteMap &&)> callback);
protected:
Outcome parseGlobalEmotes(const QJsonObject &jsonRoot);
+38 -21
View File
@@ -12,27 +12,35 @@ AbstractIrcServer::AbstractIrcServer()
{
// Initialize the connections
this->writeConnection_.reset(new IrcConnection);
this->writeConnection_->moveToThread(QCoreApplication::instance()->thread());
this->writeConnection_->moveToThread(
QCoreApplication::instance()->thread());
QObject::connect(this->writeConnection_.get(), &Communi::IrcConnection::messageReceived,
[this](auto msg) { this->writeConnectionMessageReceived(msg); });
QObject::connect(
this->writeConnection_.get(), &Communi::IrcConnection::messageReceived,
[this](auto msg) { this->writeConnectionMessageReceived(msg); });
// Listen to read connection message signals
this->readConnection_.reset(new IrcConnection);
this->readConnection_->moveToThread(QCoreApplication::instance()->thread());
QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::messageReceived,
QObject::connect(this->readConnection_.get(),
&Communi::IrcConnection::messageReceived,
[this](auto msg) { this->messageReceived(msg); });
QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::privateMessageReceived,
QObject::connect(this->readConnection_.get(),
&Communi::IrcConnection::privateMessageReceived,
[this](auto msg) { this->privateMessageReceived(msg); });
QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::connected,
QObject::connect(this->readConnection_.get(),
&Communi::IrcConnection::connected,
[this] { this->onConnected(); });
QObject::connect(this->readConnection_.get(), &Communi::IrcConnection::disconnected,
QObject::connect(this->readConnection_.get(),
&Communi::IrcConnection::disconnected,
[this] { this->onDisconnected(); });
// listen to reconnect request
this->readConnection_->reconnectRequested.connect([this] { this->connect(); });
// this->writeConnection->reconnectRequested.connect([this] { this->connect(); });
this->readConnection_->reconnectRequested.connect(
[this] { this->connect(); });
// this->writeConnection->reconnectRequested.connect([this] {
// this->connect(); });
}
void AbstractIrcServer::connect()
@@ -75,7 +83,8 @@ void AbstractIrcServer::disconnect()
this->writeConnection_->close();
}
void AbstractIrcServer::sendMessage(const QString &channelName, const QString &message)
void AbstractIrcServer::sendMessage(const QString &channelName,
const QString &message)
{
this->sendRawMessage("PRIVMSG #" + channelName + " :" + message);
}
@@ -91,11 +100,13 @@ void AbstractIrcServer::sendRawMessage(const QString &rawMessage)
}
}
void AbstractIrcServer::writeConnectionMessageReceived(Communi::IrcMessage *message)
void AbstractIrcServer::writeConnectionMessageReceived(
Communi::IrcMessage *message)
{
}
std::shared_ptr<Channel> AbstractIrcServer::getOrAddChannel(const QString &dirtyChannelName)
std::shared_ptr<Channel> AbstractIrcServer::getOrAddChannel(
const QString &dirtyChannelName)
{
auto channelName = this->cleanChannelName(dirtyChannelName);
@@ -119,7 +130,8 @@ std::shared_ptr<Channel> AbstractIrcServer::getOrAddChannel(const QString &dirty
chan->destroyed.connect([this, clojuresInCppAreShit] {
// fourtf: issues when the server itself is destroyed
Log("[AbstractIrcServer::addChannel] {} was destroyed", clojuresInCppAreShit);
Log("[AbstractIrcServer::addChannel] {} was destroyed",
clojuresInCppAreShit);
this->channels.remove(clojuresInCppAreShit);
if (this->readConnection_) {
@@ -147,7 +159,8 @@ std::shared_ptr<Channel> AbstractIrcServer::getOrAddChannel(const QString &dirty
return chan;
}
std::shared_ptr<Channel> AbstractIrcServer::getChannelOrEmpty(const QString &dirtyChannelName)
std::shared_ptr<Channel> AbstractIrcServer::getChannelOrEmpty(
const QString &dirtyChannelName)
{
auto channelName = this->cleanChannelName(dirtyChannelName);
@@ -187,9 +200,9 @@ void AbstractIrcServer::onConnected()
LimitedQueueSnapshot<MessagePtr> snapshot = chan->getMessageSnapshot();
bool replaceMessage =
snapshot.getLength() > 0 &&
snapshot[snapshot.getLength() - 1]->flags & Message::DisconnectedMessage;
bool replaceMessage = snapshot.getLength() > 0 &&
snapshot[snapshot.getLength() - 1]->flags &
Message::DisconnectedMessage;
if (replaceMessage) {
chan->replaceMessage(snapshot[snapshot.getLength() - 1], reconnMsg);
@@ -217,7 +230,8 @@ void AbstractIrcServer::onDisconnected()
}
}
std::shared_ptr<Channel> AbstractIrcServer::getCustomChannel(const QString &channelName)
std::shared_ptr<Channel> AbstractIrcServer::getCustomChannel(
const QString &channelName)
{
return nullptr;
}
@@ -229,16 +243,19 @@ QString AbstractIrcServer::cleanChannelName(const QString &dirtyChannelName)
void AbstractIrcServer::addFakeMessage(const QString &data)
{
auto fakeMessage = Communi::IrcMessage::fromData(data.toUtf8(), this->readConnection_.get());
auto fakeMessage = Communi::IrcMessage::fromData(
data.toUtf8(), this->readConnection_.get());
if (fakeMessage->command() == "PRIVMSG") {
this->privateMessageReceived(static_cast<Communi::IrcPrivateMessage *>(fakeMessage));
this->privateMessageReceived(
static_cast<Communi::IrcPrivateMessage *>(fakeMessage));
} else {
this->messageReceived(fakeMessage);
}
}
void AbstractIrcServer::privateMessageReceived(Communi::IrcPrivateMessage *message)
void AbstractIrcServer::privateMessageReceived(
Communi::IrcPrivateMessage *message)
{
}
+8 -4
View File
@@ -30,7 +30,8 @@ public:
// signals
pajlada::Signals::NoArgSignal connected;
pajlada::Signals::NoArgSignal disconnected;
// pajlada::Signals::Signal<Communi::IrcPrivateMessage *> onPrivateMessage;
// pajlada::Signals::Signal<Communi::IrcPrivateMessage *>
// onPrivateMessage;
void addFakeMessage(const QString &data);
@@ -40,8 +41,10 @@ public:
protected:
AbstractIrcServer();
virtual void initializeConnection(IrcConnection *connection, bool isRead, bool isWrite) = 0;
virtual std::shared_ptr<Channel> createChannel(const QString &channelName) = 0;
virtual void initializeConnection(IrcConnection *connection, bool isRead,
bool isWrite) = 0;
virtual std::shared_ptr<Channel> createChannel(
const QString &channelName) = 0;
virtual void privateMessageReceived(Communi::IrcPrivateMessage *message);
virtual void messageReceived(Communi::IrcMessage *message);
@@ -50,7 +53,8 @@ protected:
virtual void onConnected();
virtual void onDisconnected();
virtual std::shared_ptr<Channel> getCustomChannel(const QString &channelName);
virtual std::shared_ptr<Channel> getCustomChannel(
const QString &channelName);
virtual bool hasSeparateWriteConnection() const = 0;
virtual QString cleanChannelName(const QString &dirtyChannelName);
+2 -1
View File
@@ -2,7 +2,8 @@
// namespace chatterino {
//
// IrcAccount::IrcAccount(const QString &_userName, const QString &_nickName, const QString
// IrcAccount::IrcAccount(const QString &_userName, const QString &_nickName,
// const QString
// &_realName,
// const QString &_password)
// : userName(_userName)
+2 -1
View File
@@ -7,7 +7,8 @@
// class IrcAccount
//{
// public:
// IrcAccount(const QString &userName, const QString &nickName, const QString &realName,
// IrcAccount(const QString &userName, const QString &nickName, const QString
// &realName,
// const QString &password);
// const QString &getUserName() const;
+7 -6
View File
@@ -27,13 +27,14 @@ IrcConnection::IrcConnection(QObject *parent)
}
});
QObject::connect(this, &Communi::IrcConnection::messageReceived, [this](Communi::IrcMessage *) {
this->recentlyReceivedMessage_ = true;
QObject::connect(this, &Communi::IrcConnection::messageReceived,
[this](Communi::IrcMessage *) {
this->recentlyReceivedMessage_ = true;
if (this->reconnectTimer_.isActive()) {
this->reconnectTimer_.stop();
}
});
if (this->reconnectTimer_.isActive()) {
this->reconnectTimer_.stop();
}
});
}
} // namespace chatterino
+2 -1
View File
@@ -14,7 +14,8 @@ namespace chatterino {
// std::shared_ptr<IrcAccount> getAccount() const;
// protected:
// virtual void initializeConnection(Communi::IrcConnection *connection, bool isReadConnection);
// virtual void initializeConnection(Communi::IrcConnection *connection, bool
// isReadConnection);
// virtual void privateMessageReceived(Communi::IrcPrivateMessage *message);
// virtual void messageReceived(Communi::IrcMessage *message);
+48 -27
View File
@@ -25,15 +25,17 @@ IrcMessageHandler &IrcMessageHandler::getInstance()
return instance;
}
void IrcMessageHandler::handlePrivMessage(Communi::IrcPrivateMessage *message, TwitchServer &server)
void IrcMessageHandler::handlePrivMessage(Communi::IrcPrivateMessage *message,
TwitchServer &server)
{
this->addMessage(message, message->target(), message->content(), server, false,
message->isAction());
this->addMessage(message, message->target(), message->content(), server,
false, message->isAction());
}
void IrcMessageHandler::addMessage(Communi::IrcMessage *_message, const QString &target,
const QString &content, TwitchServer &server, bool isSub,
bool isAction)
void IrcMessageHandler::addMessage(Communi::IrcMessage *_message,
const QString &target,
const QString &content, TwitchServer &server,
bool isSub, bool isAction)
{
QString channelName;
if (!trimChannelName(target, channelName)) {
@@ -140,14 +142,17 @@ void IrcMessageHandler::handleClearChatMessage(Communi::IrcMessage *message)
auto chan = app->twitch.server->getChannelOrEmpty(chanName);
if (chan->isEmpty()) {
Log("[IrcMessageHandler:handleClearChatMessage] Twitch channel {} not found", chanName);
Log("[IrcMessageHandler:handleClearChatMessage] Twitch channel {} not "
"found",
chanName);
return;
}
// check if the chat has been cleared by a moderator
if (message->parameters().length() == 1) {
chan->disableAllMessages();
chan->addMessage(Message::createSystemMessage("Chat has been cleared by a moderator."));
chan->addMessage(Message::createSystemMessage(
"Chat has been cleared by a moderator."));
return;
}
@@ -165,7 +170,8 @@ void IrcMessageHandler::handleClearChatMessage(Communi::IrcMessage *message)
reason = v.toString();
}
auto timeoutMsg = Message::createTimeoutMessage(username, durationInSeconds, reason, false);
auto timeoutMsg = Message::createTimeoutMessage(username, durationInSeconds,
reason, false);
chan->addOrReplaceTimeout(timeoutMsg);
// refresh all
@@ -206,7 +212,8 @@ void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message)
auto c = app->twitch.server->whispersChannel.get();
TwitchMessageBuilder builder(c, message, args, message->parameter(1), false);
TwitchMessageBuilder builder(c, message, args, message->parameter(1),
false);
if (!builder.isIgnored()) {
MessagePtr _message = builder.build();
@@ -229,7 +236,8 @@ void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message)
}
}
void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, TwitchServer &server)
void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message,
TwitchServer &server)
{
auto data = message->toData();
@@ -244,7 +252,8 @@ void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, Tw
}
if (msgType == "sub" || msgType == "resub" || msgType == "subgift") {
// Sub-specific message. I think it's only allowed for "resub" messages atm
// Sub-specific message. I think it's only allowed for "resub" messages
// atm
if (!content.isEmpty()) {
this->addMessage(message, target, content, server, true, false);
}
@@ -253,7 +262,8 @@ void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message, Tw
auto it = tags.find("system-msg");
if (it != tags.end()) {
auto newMessage = Message::createSystemMessage(parseTagString(it.value().toString()));
auto newMessage =
Message::createSystemMessage(parseTagString(it.value().toString()));
newMessage->flags |= Message::Subscription;
@@ -279,7 +289,8 @@ void IrcMessageHandler::handleModeMessage(Communi::IrcMessage *message)
{
auto app = getApp();
auto channel = app->twitch.server->getChannelOrEmpty(message->parameter(0).remove(0, 1));
auto channel = app->twitch.server->getChannelOrEmpty(
message->parameter(0).remove(0, 1));
if (channel->isEmpty()) {
return;
@@ -299,10 +310,12 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message)
QString channelName;
if (!trimChannelName(message->target(), channelName)) {
// Notice wasn't targeted at a single channel, send to all twitch channels
app->twitch.server->forEachChannelAndSpecialChannels([msg](const auto &c) {
c->addMessage(msg); //
});
// Notice wasn't targeted at a single channel, send to all twitch
// channels
app->twitch.server->forEachChannelAndSpecialChannels(
[msg](const auto &c) {
c->addMessage(msg); //
});
return;
}
@@ -310,7 +323,8 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message)
auto channel = app->twitch.server->getChannelOrEmpty(channelName);
if (channel->isEmpty()) {
Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel manager ",
Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel "
"manager ",
channelName);
return;
}
@@ -318,7 +332,8 @@ void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message)
channel->addMessage(msg);
}
void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMessage *message)
void IrcMessageHandler::handleWriteConnectionNoticeMessage(
Communi::IrcNoticeMessage *message)
{
static std::unordered_set<std::string> readConnectionOnlyIDs{
"host_on",
@@ -333,8 +348,9 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes
"r9k_on",
"r9k_off",
// Display for user who times someone out. This implies you're a moderator, at which point
// you will be connected to PubSub and receive a better message from there
// Display for user who times someone out. This implies you're a
// moderator, at which point you will be connected to PubSub and receive
// a better message from there
"timeout_success",
"ban_success",
};
@@ -347,7 +363,8 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes
return;
}
Log("Showing notice message from write connection with message id '{}'", msgID);
Log("Showing notice message from write connection with message id '{}'",
msgID);
}
this->handleNoticeMessage(message);
@@ -356,9 +373,11 @@ void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMes
void IrcMessageHandler::handleJoinMessage(Communi::IrcMessage *message)
{
auto app = getApp();
auto channel = app->twitch.server->getChannelOrEmpty(message->parameter(0).remove(0, 1));
auto channel = app->twitch.server->getChannelOrEmpty(
message->parameter(0).remove(0, 1));
if (TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get())) {
if (TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(channel.get())) {
twitchChannel->addJoinedUser(message->nick());
}
}
@@ -366,9 +385,11 @@ void IrcMessageHandler::handleJoinMessage(Communi::IrcMessage *message)
void IrcMessageHandler::handlePartMessage(Communi::IrcMessage *message)
{
auto app = getApp();
auto channel = app->twitch.server->getChannelOrEmpty(message->parameter(0).remove(0, 1));
auto channel = app->twitch.server->getChannelOrEmpty(
message->parameter(0).remove(0, 1));
if (TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get())) {
if (TwitchChannel *twitchChannel =
dynamic_cast<TwitchChannel *>(channel.get())) {
twitchChannel->addPartedUser(message->nick());
}
}
+7 -4
View File
@@ -13,13 +13,15 @@ class IrcMessageHandler
public:
static IrcMessageHandler &getInstance();
void handlePrivMessage(Communi::IrcPrivateMessage *message, TwitchServer &server);
void handlePrivMessage(Communi::IrcPrivateMessage *message,
TwitchServer &server);
void handleRoomStateMessage(Communi::IrcMessage *message);
void handleClearChatMessage(Communi::IrcMessage *message);
void handleUserStateMessage(Communi::IrcMessage *message);
void handleWhisperMessage(Communi::IrcMessage *message);
void handleUserNoticeMessage(Communi::IrcMessage *message, TwitchServer &server);
void handleUserNoticeMessage(Communi::IrcMessage *message,
TwitchServer &server);
void handleModeMessage(Communi::IrcMessage *message);
void handleNoticeMessage(Communi::IrcNoticeMessage *message);
void handleWriteConnectionNoticeMessage(Communi::IrcNoticeMessage *message);
@@ -28,8 +30,9 @@ public:
void handlePartMessage(Communi::IrcMessage *message);
private:
void addMessage(Communi::IrcMessage *message, const QString &target, const QString &content,
TwitchServer &server, bool isResub, bool isAction);
void addMessage(Communi::IrcMessage *message, const QString &target,
const QString &content, TwitchServer &server, bool isResub,
bool isAction);
};
} // namespace chatterino
+6 -3
View File
@@ -25,7 +25,8 @@ PartialTwitchUser PartialTwitchUser::byId(const QString &id)
return user;
}
void PartialTwitchUser::getId(std::function<void(QString)> successCallback, const QObject *caller)
void PartialTwitchUser::getId(std::function<void(QString)> successCallback,
const QObject *caller)
{
assert(!this->username_.isEmpty());
@@ -33,7 +34,8 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback, cons
caller = QThread::currentThread();
}
NetworkRequest request("https://api.twitch.tv/kraken/users?login=" + this->username_);
NetworkRequest request("https://api.twitch.tv/kraken/users?login=" +
this->username_);
request.setCaller(caller);
request.makeAuthorizedV5(getDefaultClientID());
@@ -56,7 +58,8 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback, cons
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 "
Log("API Error: while getting user id, first user object `_id` key "
"is not a "
"string");
return Failure;
}
+2 -1
View File
@@ -19,7 +19,8 @@ public:
static PartialTwitchUser byName(const QString &username);
static PartialTwitchUser byId(const QString &id);
void getId(std::function<void(QString)> successCallback, const QObject *caller = nullptr);
void getId(std::function<void(QString)> successCallback,
const QObject *caller = nullptr);
};
} // namespace chatterino
+2 -1
View File
@@ -21,7 +21,8 @@ struct PubSubAction {
QString roomID;
};
// Used when a chat mode (i.e. slowmode, subscribers only mode) is enabled or disabled
// Used when a chat mode (i.e. slowmode, subscribers only mode) is enabled or
// disabled
struct ModeChangedAction : PubSubAction {
using PubSubAction::PubSubAction;
+98 -64
View File
@@ -24,7 +24,8 @@ static std::map<QString, std::string> sentMessages;
namespace detail {
PubSubClient::PubSubClient(WebsocketClient &websocketClient, WebsocketHandle handle)
PubSubClient::PubSubClient(WebsocketClient &websocketClient,
WebsocketHandle handle)
: websocketClient_(websocketClient)
, handle_(handle)
{
@@ -58,7 +59,8 @@ bool PubSubClient::listen(rapidjson::Document &message)
this->numListens_ += numRequestedListens;
for (const auto &topic : message["data"]["topics"].GetArray()) {
this->listeners_.emplace_back(Listener{topic.GetString(), false, false, false});
this->listeners_.emplace_back(
Listener{topic.GetString(), false, false, false});
}
auto uuid = CreateUUID();
@@ -135,34 +137,38 @@ void PubSubClient::ping()
auto self = this->shared_from_this();
runAfter(this->websocketClient_.get_io_service(), std::chrono::seconds(15), [self](auto timer) {
if (!self->started_) {
return;
}
runAfter(this->websocketClient_.get_io_service(), std::chrono::seconds(15),
[self](auto timer) {
if (!self->started_) {
return;
}
if (self->awaitingPong_) {
Log("No pong respnose, disconnect!");
// TODO(pajlada): Label this connection as "disconnect me"
}
});
if (self->awaitingPong_) {
Log("No pong respnose, disconnect!");
// TODO(pajlada): Label this connection as "disconnect me"
}
});
runAfter(this->websocketClient_.get_io_service(), std::chrono::minutes(5), [self](auto timer) {
if (!self->started_) {
return;
}
runAfter(this->websocketClient_.get_io_service(), std::chrono::minutes(5),
[self](auto timer) {
if (!self->started_) {
return;
}
self->ping(); //
});
self->ping(); //
});
}
bool PubSubClient::send(const char *payload)
{
WebsocketErrorCode ec;
this->websocketClient_.send(this->handle_, payload, websocketpp::frame::opcode::text, ec);
this->websocketClient_.send(this->handle_, payload,
websocketpp::frame::opcode::text, ec);
if (ec) {
Log("Error sending message {}: {}", payload, ec.message());
// TODO(pajlada): Check which error code happened and maybe gracefully handle it
// TODO(pajlada): Check which error code happened and maybe gracefully
// handle it
return false;
}
@@ -176,13 +182,15 @@ PubSub::PubSub()
{
qDebug() << "init PubSub";
this->moderationActionHandlers["clear"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["clear"] = [this](const auto &data,
const auto &roomID) {
ClearChatAction action(data, roomID);
this->signals_.moderation.chatCleared.invoke(action);
};
this->moderationActionHandlers["slowoff"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["slowoff"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::Slow;
@@ -191,7 +199,8 @@ PubSub::PubSub()
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["slow"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["slow"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::Slow;
@@ -228,7 +237,8 @@ PubSub::PubSub()
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["r9kbetaoff"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["r9kbetaoff"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::R9K;
@@ -237,7 +247,8 @@ PubSub::PubSub()
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["r9kbeta"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["r9kbeta"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::R9K;
@@ -246,17 +257,18 @@ PubSub::PubSub()
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["subscribersoff"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
this->moderationActionHandlers["subscribersoff"] =
[this](const auto &data, const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::SubscribersOnly;
action.state = ModeChangedAction::State::Off;
action.mode = ModeChangedAction::Mode::SubscribersOnly;
action.state = ModeChangedAction::State::Off;
this->signals_.moderation.modeChanged.invoke(action);
};
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["subscribers"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["subscribers"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::SubscribersOnly;
@@ -265,16 +277,18 @@ PubSub::PubSub()
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["emoteonlyoff"] = [this](const auto &data, const auto &roomID) {
ModeChangedAction action(data, roomID);
this->moderationActionHandlers["emoteonlyoff"] =
[this](const auto &data, const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::EmoteOnly;
action.state = ModeChangedAction::State::Off;
action.mode = ModeChangedAction::Mode::EmoteOnly;
action.state = ModeChangedAction::State::Off;
this->signals_.moderation.modeChanged.invoke(action);
};
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["emoteonly"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["emoteonly"] = [this](const auto &data,
const auto &roomID) {
ModeChangedAction action(data, roomID);
action.mode = ModeChangedAction::Mode::EmoteOnly;
@@ -283,7 +297,8 @@ PubSub::PubSub()
this->signals_.moderation.modeChanged.invoke(action);
};
this->moderationActionHandlers["unmod"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["unmod"] = [this](const auto &data,
const auto &roomID) {
ModerationStateAction action(data, roomID);
getTargetUser(data, action.target);
@@ -307,7 +322,8 @@ PubSub::PubSub()
this->signals_.moderation.moderationStateChanged.invoke(action);
};
this->moderationActionHandlers["mod"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["mod"] = [this](const auto &data,
const auto &roomID) {
ModerationStateAction action(data, roomID);
getTargetUser(data, action.target);
@@ -331,7 +347,8 @@ PubSub::PubSub()
this->signals_.moderation.moderationStateChanged.invoke(action);
};
this->moderationActionHandlers["timeout"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["timeout"] = [this](const auto &data,
const auto &roomID) {
BanAction action(data, roomID);
getCreatedByUser(data, action.source);
@@ -367,7 +384,8 @@ PubSub::PubSub()
}
};
this->moderationActionHandlers["ban"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["ban"] = [this](const auto &data,
const auto &roomID) {
BanAction action(data, roomID);
getCreatedByUser(data, action.source);
@@ -396,7 +414,8 @@ PubSub::PubSub()
}
};
this->moderationActionHandlers["unban"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["unban"] = [this](const auto &data,
const auto &roomID) {
UnbanAction action(data, roomID);
getCreatedByUser(data, action.source);
@@ -421,7 +440,8 @@ PubSub::PubSub()
}
};
this->moderationActionHandlers["untimeout"] = [this](const auto &data, const auto &roomID) {
this->moderationActionHandlers["untimeout"] = [this](const auto &data,
const auto &roomID) {
UnbanAction action(data, roomID);
getCreatedByUser(data, action.source);
@@ -447,16 +467,21 @@ PubSub::PubSub()
};
this->websocketClient.set_access_channels(websocketpp::log::alevel::all);
this->websocketClient.clear_access_channels(websocketpp::log::alevel::frame_payload);
this->websocketClient.clear_access_channels(
websocketpp::log::alevel::frame_payload);
this->websocketClient.init_asio();
// SSL Handshake
this->websocketClient.set_tls_init_handler(bind(&PubSub::onTLSInit, this, ::_1));
this->websocketClient.set_tls_init_handler(
bind(&PubSub::onTLSInit, this, ::_1));
this->websocketClient.set_message_handler(bind(&PubSub::onMessage, this, ::_1, ::_2));
this->websocketClient.set_open_handler(bind(&PubSub::onConnectionOpen, this, ::_1));
this->websocketClient.set_close_handler(bind(&PubSub::onConnectionClose, this, ::_1));
this->websocketClient.set_message_handler(
bind(&PubSub::onMessage, this, ::_1, ::_2));
this->websocketClient.set_open_handler(
bind(&PubSub::onConnectionOpen, this, ::_1));
this->websocketClient.set_close_handler(
bind(&PubSub::onConnectionClose, this, ::_1));
// Add an initial client
this->addClient();
@@ -477,7 +502,8 @@ void PubSub::addClient()
void PubSub::start()
{
this->mainThread.reset(new std::thread(std::bind(&PubSub::runThread, this)));
this->mainThread.reset(
new std::thread(std::bind(&PubSub::runThread, this)));
}
void PubSub::listenToWhispers(std::shared_ptr<TwitchAccount> account)
@@ -507,8 +533,8 @@ void PubSub::unlistenAllModerationActions()
}
}
void PubSub::listenToChannelModerationActions(const QString &channelID,
std::shared_ptr<TwitchAccount> account)
void PubSub::listenToChannelModerationActions(
const QString &channelID, std::shared_ptr<TwitchAccount> account)
{
assert(!channelID.isEmpty());
assert(account != nullptr);
@@ -527,7 +553,8 @@ void PubSub::listenToChannelModerationActions(const QString &channelID,
this->listenToTopic(topic, account);
}
void PubSub::listenToTopic(const std::string &topic, std::shared_ptr<TwitchAccount> account)
void PubSub::listenToTopic(const std::string &topic,
std::shared_ptr<TwitchAccount> account)
{
auto message = createListenMessage({topic}, account);
@@ -542,7 +569,8 @@ void PubSub::listen(rapidjson::Document &&msg)
}
Log("Added to the back of the queue");
this->requests.emplace_back(std::make_unique<rapidjson::Document>(std::move(msg)));
this->requests.emplace_back(
std::make_unique<rapidjson::Document>(std::move(msg)));
}
bool PubSub::tryListen(rapidjson::Document &msg)
@@ -570,7 +598,8 @@ bool PubSub::isListeningToTopic(const std::string &topic)
return false;
}
void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr websocketMessage)
void PubSub::onMessage(websocketpp::connection_hdl hdl,
WebsocketMessagePtr websocketMessage)
{
const std::string &payload = websocketMessage->get_payload();
@@ -585,7 +614,9 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs
}
if (!msg.IsObject()) {
Log("Error parsing message '{}' from PubSub. Root object is not an object", payload);
Log("Error parsing message '{}' from PubSub. Root object is not an "
"object",
payload);
return;
}
@@ -615,8 +646,8 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs
} else if (type == "PONG") {
auto clientIt = this->clients.find(hdl);
// If this assert goes off, there's something wrong with the connection creation/preserving
// code KKona
// If this assert goes off, there's something wrong with the connection
// creation/preserving code KKona
assert(clientIt != this->clients.end());
auto &client = *clientIt;
@@ -629,9 +660,11 @@ void PubSub::onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr webs
void PubSub::onConnectionOpen(WebsocketHandle hdl)
{
auto client = std::make_shared<detail::PubSubClient>(this->websocketClient, hdl);
auto client =
std::make_shared<detail::PubSubClient>(this->websocketClient, hdl);
// We separate the starting from the constructor because we will want to use shared_from_this
// We separate the starting from the constructor because we will want to use
// shared_from_this
client->start();
this->clients.emplace(hdl, client);
@@ -643,8 +676,8 @@ void PubSub::onConnectionClose(WebsocketHandle hdl)
{
auto clientIt = this->clients.find(hdl);
// If this assert goes off, there's something wrong with the connection creation/preserving
// code KKona
// If this assert goes off, there's something wrong with the connection
// creation/preserving code KKona
assert(clientIt != this->clients.end());
auto &client = clientIt->second;
@@ -658,7 +691,8 @@ void PubSub::onConnectionClose(WebsocketHandle hdl)
PubSub::WebsocketContextPtr PubSub::onTLSInit(websocketpp::connection_hdl hdl)
{
WebsocketContextPtr ctx(new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1));
WebsocketContextPtr ctx(
new boost::asio::ssl::context(boost::asio::ssl::context::tlsv1));
try {
ctx->set_options(boost::asio::ssl::context::default_workarounds |
+14 -8
View File
@@ -22,7 +22,8 @@
namespace chatterino {
using WebsocketClient = websocketpp::client<websocketpp::config::asio_tls_client>;
using WebsocketClient =
websocketpp::client<websocketpp::config::asio_tls_client>;
using WebsocketHandle = websocketpp::connection_hdl;
using WebsocketErrorCode = websocketpp::lib::error_code;
@@ -71,11 +72,14 @@ private:
class PubSub
{
using WebsocketMessagePtr = websocketpp::config::asio_tls_client::message_type::ptr;
using WebsocketContextPtr = websocketpp::lib::shared_ptr<boost::asio::ssl::context>;
using WebsocketMessagePtr =
websocketpp::config::asio_tls_client::message_type::ptr;
using WebsocketContextPtr =
websocketpp::lib::shared_ptr<boost::asio::ssl::context>;
template <typename T>
using Signal = pajlada::Signals::Signal<T>; // type-id is vector<T, Alloc<T>>
using Signal =
pajlada::Signals::Signal<T>; // type-id is vector<T, Alloc<T>>
WebsocketClient websocketClient;
std::unique_ptr<std::thread> mainThread;
@@ -121,13 +125,14 @@ public:
void unlistenAllModerationActions();
void listenToChannelModerationActions(const QString &channelID,
std::shared_ptr<TwitchAccount> account);
void listenToChannelModerationActions(
const QString &channelID, std::shared_ptr<TwitchAccount> account);
std::vector<std::unique_ptr<rapidjson::Document>> requests;
private:
void listenToTopic(const std::string &topic, std::shared_ptr<TwitchAccount> account);
void listenToTopic(const std::string &topic,
std::shared_ptr<TwitchAccount> account);
void listen(rapidjson::Document &&msg);
bool tryListen(rapidjson::Document &msg);
@@ -142,7 +147,8 @@ private:
std::owner_less<WebsocketHandle>>
clients;
std::unordered_map<std::string, std::function<void(const rapidjson::Value &, const QString &)>>
std::unordered_map<std::string, std::function<void(const rapidjson::Value &,
const QString &)>>
moderationActionHandlers;
void onMessage(websocketpp::connection_hdl hdl, WebsocketMessagePtr msg);
+5 -3
View File
@@ -31,8 +31,9 @@ bool getTargetUser(const rapidjson::Value &data, ActionUser &user)
return rj::getSafe(data, "target_user_id", user.id);
}
rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVec,
std::shared_ptr<TwitchAccount> account)
rapidjson::Document createListenMessage(
const std::vector<std::string> &topicsVec,
std::shared_ptr<TwitchAccount> account)
{
rapidjson::Document msg(rapidjson::kObjectType);
auto &a = msg.GetAllocator();
@@ -57,7 +58,8 @@ rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVe
return msg;
}
rapidjson::Document createUnlistenMessage(const std::vector<std::string> &topicsVec)
rapidjson::Document createUnlistenMessage(
const std::vector<std::string> &topicsVec)
{
rapidjson::Document msg(rapidjson::kObjectType);
auto &a = msg.GetAllocator();
+9 -5
View File
@@ -19,13 +19,16 @@ bool getCreatedByUser(const rapidjson::Value &data, ActionUser &user);
bool getTargetUser(const rapidjson::Value &data, ActionUser &user);
rapidjson::Document createListenMessage(const std::vector<std::string> &topicsVec,
std::shared_ptr<TwitchAccount> account);
rapidjson::Document createUnlistenMessage(const std::vector<std::string> &topicsVec);
rapidjson::Document createListenMessage(
const std::vector<std::string> &topicsVec,
std::shared_ptr<TwitchAccount> account);
rapidjson::Document createUnlistenMessage(
const std::vector<std::string> &topicsVec);
// Create timer using given ioService
template <typename Duration, typename Callback>
void runAfter(boost::asio::io_service &ioService, Duration duration, Callback cb)
void runAfter(boost::asio::io_service &ioService, Duration duration,
Callback cb)
{
auto timer = std::make_shared<boost::asio::steady_timer>(ioService);
timer->expires_from_now(duration);
@@ -42,7 +45,8 @@ void runAfter(boost::asio::io_service &ioService, Duration duration, Callback cb
// Use provided timer
template <typename Duration, typename Callback>
void runAfter(std::shared_ptr<boost::asio::steady_timer> timer, Duration duration, Callback cb)
void runAfter(std::shared_ptr<boost::asio::steady_timer> timer,
Duration duration, Callback cb)
{
timer->expires_from_now(duration);
+61 -38
View File
@@ -20,10 +20,12 @@ EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode)
cleanCode.detach();
static QMap<QString, QString> emoteNameReplacements{
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"},
{"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"},
{"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("},
{"\\&lt\\;3", "&lt;3"}, {"\\:-?(o|O)", ":O"},
{"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("},
{"\\:-?\\)", ":)"}, {"\\:-?D", ":D"},
{"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
@@ -105,7 +107,8 @@ bool TwitchAccount::isAnon() const
void TwitchAccount::loadIgnores()
{
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks");
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/blocks");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
@@ -140,7 +143,8 @@ void TwitchAccount::loadIgnores()
}
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser)) {
Log("Error parsing twitch user JSON {}", rj::stringify(userIt->value));
Log("Error parsing twitch user JSON {}",
rj::stringify(userIt->value));
continue;
}
@@ -154,28 +158,32 @@ void TwitchAccount::loadIgnores()
req.execute();
}
void TwitchAccount::ignore(const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished)
void TwitchAccount::ignore(
const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished)
{
const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) {
const auto onIdFetched = [this, targetName,
onFinished](QString targetUserId) {
this->ignoreByID(targetUserId, targetName, onFinished); //
};
PartialTwitchUser::byName(targetName).getId(onIdFetched);
}
void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished)
void TwitchAccount::ignoreByID(
const QString &targetUserID, const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished)
{
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" +
targetUserID);
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) + ")");
onFinished(IgnoreResult_Failed,
"An unknown error occured while trying to ignore user " +
targetName + " (" + QString::number(errorCode) + ")");
return true;
});
@@ -183,21 +191,24 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject()) {
onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user " + targetName);
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user " + targetName);
return Failure;
}
auto userIt = document.FindMember("user");
if (userIt == document.MemberEnd()) {
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (missing user) " + targetName);
"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);
"Bad JSON data while ignoring user (invalid user) " +
targetName);
return Failure;
}
{
@@ -212,7 +223,8 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
return Failure;
}
}
onFinished(IgnoreResult_Success, "Successfully ignored user " + targetName);
onFinished(IgnoreResult_Success,
"Successfully ignored user " + targetName);
return Success;
});
@@ -220,10 +232,12 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
req.execute();
}
void TwitchAccount::unignore(const QString &targetName,
std::function<void(UnignoreResult, const QString &message)> onFinished)
void TwitchAccount::unignore(
const QString &targetName,
std::function<void(UnignoreResult, const QString &message)> onFinished)
{
const auto onIdFetched = [this, targetName, onFinished](QString targetUserId) {
const auto onIdFetched = [this, targetName,
onFinished](QString targetUserId) {
this->unignoreByID(targetUserId, targetName, onFinished); //
};
@@ -234,8 +248,8 @@ void TwitchAccount::unignoreByID(
const QString &targetUserID, const QString &targetName,
std::function<void(UnignoreResult, const QString &message)> onFinished)
{
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/blocks/" +
targetUserID);
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/blocks/" + targetUserID);
NetworkRequest req(url, NetworkRequestType::Delete);
req.setCaller(QThread::currentThread());
@@ -243,8 +257,8 @@ void TwitchAccount::unignoreByID(
req.onError([=](int errorCode) {
onFinished(UnignoreResult_Failed,
"An unknown error occured while trying to unignore user " + targetName + " (" +
QString::number(errorCode) + ")");
"An unknown error occured while trying to unignore user " +
targetName + " (" + QString::number(errorCode) + ")");
return true;
});
@@ -258,7 +272,8 @@ void TwitchAccount::unignoreByID(
this->ignores_.erase(ignoredUser);
}
onFinished(UnignoreResult_Success, "Successfully unignored user " + targetName);
onFinished(UnignoreResult_Success,
"Successfully unignored user " + targetName);
return Success;
});
@@ -269,8 +284,8 @@ void TwitchAccount::unignoreByID(
void TwitchAccount::checkFollow(const QString targetUserID,
std::function<void(FollowResult)> onFinished)
{
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/follows/channels/" +
targetUserID);
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/follows/channels/" + targetUserID);
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
@@ -295,7 +310,8 @@ void TwitchAccount::checkFollow(const QString targetUserID,
req.execute();
}
void TwitchAccount::followUser(const QString userID, std::function<void()> successCallback)
void TwitchAccount::followUser(const QString userID,
std::function<void()> successCallback)
{
QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/follows/channels/" + userID);
@@ -315,7 +331,8 @@ void TwitchAccount::followUser(const QString userID, std::function<void()> succe
request.execute();
}
void TwitchAccount::unfollowUser(const QString userID, std::function<void()> successCallback)
void TwitchAccount::unfollowUser(const QString userID,
std::function<void()> successCallback)
{
QUrl requestUrl("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/follows/channels/" + userID);
@@ -361,7 +378,8 @@ void TwitchAccount::loadEmotes()
return;
}
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() + "/emotes");
QString url("https://api.twitch.tv/kraken/users/" + this->getUserId() +
"/emotes");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
@@ -387,7 +405,8 @@ void TwitchAccount::loadEmotes()
req.execute();
}
AccessGuard<const TwitchAccount::TwitchAccountEmoteData> TwitchAccount::accessEmotes() const
AccessGuard<const TwitchAccount::TwitchAccountEmoteData>
TwitchAccount::accessEmotes() const
{
return this->emotes_.accessConst();
}
@@ -412,7 +431,8 @@ void TwitchAccount::parseEmotes(const rapidjson::Document &root)
this->loadEmoteSetData(emoteSet);
for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) {
for (const rapidjson::Value &emoteJSON :
emoteSetJSON.value.GetArray()) {
if (!emoteJSON.IsObject()) {
Log("Emote value was invalid");
return;
@@ -459,8 +479,9 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
return;
}
NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
"/");
NetworkRequest req(
"https://braize.pajlada.com/chatterino/twitchemotes/set/" +
emoteSet->key + "/");
req.setUseQuickLoadCache(true);
req.onError([](int errorCode) -> bool {
@@ -488,9 +509,11 @@ void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
Log("Loaded twitch emote set data for {}!", emoteSet->key);
if (type == "sub") {
emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName);
emoteSet->text =
QString("Twitch Subscriber Emote (%1)").arg(channelName);
} else {
emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName);
emoteSet->text =
QString("Twitch Account Emote (%1)").arg(channelName);
}
emoteSet->channelName = channelName;
+17 -11
View File
@@ -57,8 +57,8 @@ public:
EmoteMap emotes;
};
TwitchAccount(const QString &username, const QString &oauthToken_, const QString &oauthClient_,
const QString &_userID);
TwitchAccount(const QString &username, const QString &oauthToken_,
const QString &oauthClient_, const QString &_userID);
virtual QString toString() const override;
@@ -81,16 +81,22 @@ public:
void loadIgnores();
void ignore(const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished);
void ignoreByID(const QString &targetUserID, const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished);
void unignore(const QString &targetName,
std::function<void(UnignoreResult, const QString &)> onFinished);
void unignoreByID(const QString &targetUserID, const QString &targetName,
std::function<void(UnignoreResult, const QString &message)> onFinished);
void ignoreByID(
const QString &targetUserID, const QString &targetName,
std::function<void(IgnoreResult, const QString &)> onFinished);
void unignore(
const QString &targetName,
std::function<void(UnignoreResult, const QString &)> onFinished);
void unignoreByID(
const QString &targetUserID, const QString &targetName,
std::function<void(UnignoreResult, const QString &message)> onFinished);
void checkFollow(const QString targetUserID, std::function<void(FollowResult)> onFinished);
void followUser(const QString userID, std::function<void()> successCallback);
void unfollowUser(const QString userID, std::function<void()> successCallback);
void checkFollow(const QString targetUserID,
std::function<void(FollowResult)> onFinished);
void followUser(const QString userID,
std::function<void()> successCallback);
void unfollowUser(const QString userID,
std::function<void()> successCallback);
std::set<TwitchUser> getIgnores() const;
+27 -19
View File
@@ -72,16 +72,17 @@ void TwitchAccountManager::reloadUsers()
continue;
}
std::string username =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/username");
std::string userID =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/userID");
std::string clientID =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/clientID");
std::string oauthToken =
pajlada::Settings::Setting<std::string>::get("/accounts/" + uid + "/oauthToken");
std::string username = pajlada::Settings::Setting<std::string>::get(
"/accounts/" + uid + "/username");
std::string userID = pajlada::Settings::Setting<std::string>::get(
"/accounts/" + uid + "/userID");
std::string clientID = pajlada::Settings::Setting<std::string>::get(
"/accounts/" + uid + "/clientID");
std::string oauthToken = pajlada::Settings::Setting<std::string>::get(
"/accounts/" + uid + "/oauthToken");
if (username.empty() || userID.empty() || clientID.empty() || oauthToken.empty()) {
if (username.empty() || userID.empty() || clientID.empty() ||
oauthToken.empty()) {
continue;
}
@@ -96,9 +97,11 @@ void TwitchAccountManager::reloadUsers()
// Do nothing
} break;
case AddUserResponse::UserValuesUpdated: {
Log("User {} already exists, and values updated!", userData.username);
Log("User {} already exists, and values updated!",
userData.username);
if (userData.username == this->getCurrent()->getUserName()) {
Log("It was the current user, so we need to reconnect stuff!");
Log("It was the current user, so we need to reconnect "
"stuff!");
this->currentUserChanged.invoke();
}
} break;
@@ -122,11 +125,13 @@ void TwitchAccountManager::load()
QString newUsername(QString::fromStdString(newValue));
auto user = this->findUserByUsername(newUsername);
if (user) {
Log("[AccountManager:currentUsernameChanged] User successfully updated to {}",
Log("[AccountManager:currentUsernameChanged] User successfully "
"updated to {}",
newUsername);
this->currentUser_ = user;
} else {
Log("[AccountManager:currentUsernameChanged] User successfully updated to anonymous");
Log("[AccountManager:currentUsernameChanged] User successfully "
"updated to anonymous");
this->currentUser_ = this->anonymousUser_;
}
@@ -140,8 +145,8 @@ bool TwitchAccountManager::isLoggedIn() const
return false;
}
// Once `TwitchAccount` class has a way to check, we should also return false if the credentials
// are incorrect
// Once `TwitchAccount` class has a way to check, we should also return
// false if the credentials are incorrect
return !this->currentUser_->isAnon();
}
@@ -151,11 +156,13 @@ bool TwitchAccountManager::removeUser(TwitchAccount *account)
std::string userID(account->getUserId().toStdString());
if (!userID.empty()) {
pajlada::Settings::SettingManager::removeSetting("/accounts/uid" + userID);
pajlada::Settings::SettingManager::removeSetting("/accounts/uid" +
userID);
}
if (account->getUserName() == qS(this->currentUsername.getValue())) {
// The user that was removed is the current user, log into the anonymous user
// The user that was removed is the current user, log into the anonymous
// user
this->currentUsername = "";
}
@@ -186,8 +193,9 @@ TwitchAccountManager::AddUserResponse TwitchAccountManager::addUser(
}
}
auto newUser = std::make_shared<TwitchAccount>(userData.username, userData.oauthToken,
userData.clientID, userData.userID);
auto newUser =
std::make_shared<TwitchAccount>(userData.username, userData.oauthToken,
userData.clientID, userData.userID);
// std::lock_guard<std::mutex> lock(this->mutex);
+10 -5
View File
@@ -11,7 +11,8 @@
//
// Warning: This class is not supposed to be created directly.
// Get yourself an instance from our friends over at AccountManager.hpp
// Get yourself an instance from our friends over at
// AccountManager.hpp
//
namespace chatterino {
@@ -30,12 +31,14 @@ public:
QString oauthToken;
};
// Returns the current twitchUsers, or the anonymous user if we're not currently logged in
// Returns the current twitchUsers, or the anonymous user if we're not
// currently logged in
std::shared_ptr<TwitchAccount> getCurrent();
std::vector<QString> getUsernames() const;
std::shared_ptr<TwitchAccount> findUserByUsername(const QString &username) const;
std::shared_ptr<TwitchAccount> findUserByUsername(
const QString &username) const;
bool userExists(const QString &username) const;
void reloadUsers();
@@ -43,11 +46,13 @@ public:
bool isLoggedIn() const;
pajlada::Settings::Setting<std::string> currentUsername = {"/accounts/current", ""};
pajlada::Settings::Setting<std::string> currentUsername = {
"/accounts/current", ""};
pajlada::Signals::NoArgSignal currentUserChanged;
pajlada::Signals::NoArgSignal userListUpdated;
SortedSignalVector<std::shared_ptr<TwitchAccount>, SharedPtrElementLess<TwitchAccount>>
SortedSignalVector<std::shared_ptr<TwitchAccount>,
SharedPtrElementLess<TwitchAccount>>
accounts;
private:
+4 -2
View File
@@ -8,7 +8,8 @@
namespace chatterino {
void TwitchApi::findUserId(const QString user, std::function<void(QString)> successCallback)
void TwitchApi::findUserId(const QString user,
std::function<void(QString)> successCallback)
{
QString requestUrl("https://api.twitch.tv/kraken/users?login=" + user);
@@ -37,7 +38,8 @@ void TwitchApi::findUserId(const QString user, std::function<void(QString)> succ
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 "
Log("API Error: while getting user id, first user object `_id` key "
"is not a "
"string");
successCallback("");
return Failure;
+2 -1
View File
@@ -7,7 +7,8 @@ namespace chatterino {
class TwitchApi
{
public:
static void findUserId(const QString user, std::function<void(QString)> callback);
static void findUserId(const QString user,
std::function<void(QString)> callback);
private:
};
+20 -14
View File
@@ -19,7 +19,8 @@ void TwitchBadges::initialize(Settings &settings, Paths &paths)
void TwitchBadges::loadTwitchBadges()
{
static QString url("https://badges.twitch.tv/v1/badges/global/display?language=en");
static QString url(
"https://badges.twitch.tv/v1/badges/global/display?language=en");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
@@ -28,24 +29,29 @@ void TwitchBadges::loadTwitchBadges()
QJsonObject sets = root.value("badge_sets").toObject();
for (QJsonObject::iterator it = sets.begin(); it != sets.end(); ++it) {
QJsonObject versions = it.value().toObject().value("versions").toObject();
QJsonObject versions =
it.value().toObject().value("versions").toObject();
for (auto versionIt = std::begin(versions); versionIt != std::end(versions);
++versionIt) {
auto emote =
Emote{{""},
ImageSet{
Image::fromUrl({root.value("image_url_1x").toString()}, 1),
Image::fromUrl({root.value("image_url_2x").toString()}, 0.5),
Image::fromUrl({root.value("image_url_4x").toString()}, 0.25),
},
Tooltip{root.value("description").toString()},
Url{root.value("clickURL").toString()}};
for (auto versionIt = std::begin(versions);
versionIt != std::end(versions); ++versionIt) {
auto emote = Emote{
{""},
ImageSet{
Image::fromUrl({root.value("image_url_1x").toString()},
1),
Image::fromUrl({root.value("image_url_2x").toString()},
0.5),
Image::fromUrl({root.value("image_url_4x").toString()},
0.25),
},
Tooltip{root.value("description").toString()},
Url{root.value("clickURL").toString()}};
// "title"
// "clickAction"
QJsonObject versionObj = versionIt.value().toObject();
this->badges.emplace(versionIt.key(), std::make_shared<Emote>(emote));
this->badges.emplace(versionIt.key(),
std::make_shared<Emote>(emote));
}
}
+136 -106
View File
@@ -57,7 +57,8 @@ TwitchChannel::TwitchChannel(const QString &name)
[=] { this->refreshViewerList(); });
this->chattersListTimer_.start(5 * 60 * 1000);
QObject::connect(&this->liveStatusTimer_, &QTimer::timeout, [=] { this->refreshLiveStatus(); });
QObject::connect(&this->liveStatusTimer_, &QTimer::timeout,
[=] { this->refreshLiveStatus(); });
this->liveStatusTimer_.start(60 * 1000);
// --
@@ -84,15 +85,16 @@ bool TwitchChannel::canSendMessage() const
void TwitchChannel::refreshChannelEmotes()
{
loadBttvChannelEmotes(this->getName(), [this, weak = weakOf<Channel>(this)](auto &&emoteMap) {
if (auto shared = weak.lock()) //
*this->bttvEmotes_.access() = emoteMap;
});
getApp()->emotes->ffz.loadChannelEmotes(this->getName(),
[this, weak = weakOf<Channel>(this)](auto &&emoteMap) {
if (auto shared = weak.lock())
*this->ffzEmotes_.access() = emoteMap;
});
loadBttvChannelEmotes(
this->getName(), [this, weak = weakOf<Channel>(this)](auto &&emoteMap) {
if (auto shared = weak.lock()) //
*this->bttvEmotes_.access() = emoteMap;
});
getApp()->emotes->ffz.loadChannelEmotes(
this->getName(), [this, weak = weakOf<Channel>(this)](auto &&emoteMap) {
if (auto shared = weak.lock())
*this->ffzEmotes_.access() = emoteMap;
});
}
void TwitchChannel::sendMessage(const QString &message)
@@ -100,11 +102,11 @@ void TwitchChannel::sendMessage(const QString &message)
auto app = getApp();
if (!app->accounts->twitch.isLoggedIn()) {
// XXX: It would be nice if we could add a link here somehow that opened the "account
// manager" dialog
this->addMessage(
Message::createSystemMessage("You need to log in to send messages. You can "
"link your Twitch account in the settings."));
// XXX: It would be nice if we could add a link here somehow that opened
// the "account manager" dialog
this->addMessage(Message::createSystemMessage(
"You need to log in to send messages. You can "
"link your Twitch account in the settings."));
return;
}
@@ -181,7 +183,8 @@ void TwitchChannel::addJoinedUser(const QString &user)
QTimer::singleShot(500, &this->lifetimeGuard_, [this] {
auto joinedUsers = this->joinedUsers_.access();
auto message = Message::createSystemMessage("Users joined: " + joinedUsers->join(", "));
auto message = Message::createSystemMessage(
"Users joined: " + joinedUsers->join(", "));
message->flags |= Message::Collapsed;
joinedUsers->clear();
this->addMessage(message);
@@ -208,7 +211,8 @@ void TwitchChannel::addPartedUser(const QString &user)
QTimer::singleShot(500, &this->lifetimeGuard_, [this] {
auto partedUsers = this->partedUsers_.access();
auto message = Message::createSystemMessage("Users parted: " + partedUsers->join(", "));
auto message = Message::createSystemMessage(
"Users parted: " + partedUsers->join(", "));
message->flags |= Message::Collapsed;
this->addMessage(message);
partedUsers->clear();
@@ -230,7 +234,8 @@ void TwitchChannel::setRoomId(const QString &id)
this->loadRecentMessages();
}
AccessGuard<const TwitchChannel::RoomModes> TwitchChannel::accessRoomModes() const
AccessGuard<const TwitchChannel::RoomModes> TwitchChannel::accessRoomModes()
const
{
return this->roomModes_.accessConst();
}
@@ -247,12 +252,14 @@ bool TwitchChannel::isLive() const
return this->streamStatus_.access()->live;
}
AccessGuard<const TwitchChannel::StreamStatus> TwitchChannel::accessStreamStatus() const
AccessGuard<const TwitchChannel::StreamStatus>
TwitchChannel::accessStreamStatus() const
{
return this->streamStatus_.accessConst();
}
boost::optional<EmotePtr> TwitchChannel::getBttvEmote(const EmoteName &name) const
boost::optional<EmotePtr> TwitchChannel::getBttvEmote(
const EmoteName &name) const
{
auto emotes = this->bttvEmotes_.access();
auto it = emotes->find(name);
@@ -261,7 +268,8 @@ boost::optional<EmotePtr> TwitchChannel::getBttvEmote(const EmoteName &name) con
return it->second;
}
boost::optional<EmotePtr> TwitchChannel::getFfzEmote(const EmoteName &name) const
boost::optional<EmotePtr> TwitchChannel::getFfzEmote(
const EmoteName &name) const
{
auto emotes = this->bttvEmotes_.access();
auto it = emotes->find(name);
@@ -316,7 +324,8 @@ void TwitchChannel::refreshLiveStatus()
auto roomID = this->getRoomId();
if (roomID.isEmpty()) {
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->getName());
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)",
this->getName());
this->setLive(false);
return;
}
@@ -332,12 +341,13 @@ void TwitchChannel::refreshLiveStatus()
request.setCaller(QThread::currentThread());
//>>>>>>> 9bfbdefd2f0972a738230d5b95a009f73b1dd933
request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared) return Failure;
request.onSuccess(
[this, weak = this->weak_from_this()](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared) return Failure;
return this->parseLiveStatus(result.parseRapidJson());
});
return this->parseLiveStatus(result.parseRapidJson());
});
request.execute();
}
@@ -362,8 +372,8 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
return Failure;
}
if (!stream.HasMember("viewers") || !stream.HasMember("game") || !stream.HasMember("channel") ||
!stream.HasMember("created_at")) {
if (!stream.HasMember("viewers") || !stream.HasMember("game") ||
!stream.HasMember("channel") || !stream.HasMember("created_at")) {
Log("[TwitchChannel:refreshLiveStatus] Missing members in stream");
this->setLive(false);
return Failure;
@@ -372,7 +382,8 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
const rapidjson::Value &streamChannel = stream["channel"];
if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) {
Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel");
Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in "
"channel");
return Failure;
}
@@ -384,10 +395,11 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
status->viewerCount = stream["viewers"].GetUint();
status->game = stream["game"].GetString();
status->title = streamChannel["status"].GetString();
QDateTime since = QDateTime::fromString(stream["created_at"].GetString(), Qt::ISODate);
QDateTime since = QDateTime::fromString(
stream["created_at"].GetString(), Qt::ISODate);
auto diff = since.secsTo(QDateTime::currentDateTime());
status->uptime =
QString::number(diff / 3600) + "h " + QString::number(diff % 3600 / 60) + "m";
status->uptime = QString::number(diff / 3600) + "h " +
QString::number(diff % 3600 / 60) + "m";
status->rerun = false;
if (stream.HasMember("stream_type")) {
@@ -400,7 +412,8 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
const auto &broadcastPlatformValue = stream["broadcast_platform"];
if (broadcastPlatformValue.IsString()) {
const char *broadcastPlatform = stream["broadcast_platform"].GetString();
const char *broadcastPlatform =
stream["broadcast_platform"].GetString();
if (strcmp(broadcastPlatform, "rerun") == 0) {
status->rerun = true;
}
@@ -417,18 +430,20 @@ Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
void TwitchChannel::loadRecentMessages()
{
static QString genericURL =
"https://tmi.twitch.tv/api/rooms/%1/recent_messages?client_id=" + getDefaultClientID();
"https://tmi.twitch.tv/api/rooms/%1/recent_messages?client_id=" +
getDefaultClientID();
NetworkRequest request(genericURL.arg(this->getRoomId()));
request.makeAuthorizedV5(getDefaultClientID());
request.setCaller(QThread::currentThread());
request.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->parseRecentMessages(result.parseJson());
});
return this->parseRecentMessages(result.parseJson());
});
request.execute();
}
@@ -442,8 +457,8 @@ Outcome TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
for (const auto jsonMessage : jsonMessages) {
auto content = jsonMessage.toString().toUtf8();
// passing nullptr as the channel makes the message invalid but we don't check for that
// anyways
// passing nullptr as the channel makes the message invalid but we don't
// check for that anyways
auto message = Communi::IrcMessage::fromData(content, nullptr);
auto privMsg = dynamic_cast<Communi::IrcPrivateMessage *>(message);
assert(privMsg);
@@ -468,7 +483,8 @@ void TwitchChannel::refreshPubsub()
if (roomId.isEmpty()) return;
auto account = getApp()->accounts->twitch.getCurrent();
getApp()->twitch2->pubsub->listenToChannelModerationActions(roomId, account);
getApp()->twitch2->pubsub->listenToChannelModerationActions(roomId,
account);
}
void TwitchChannel::refreshViewerList()
@@ -477,35 +493,40 @@ void TwitchChannel::refreshViewerList()
const auto streamStatus = this->accessStreamStatus();
if (getSettings()->onlyFetchChattersForSmallerStreamers) {
if (streamStatus->live && streamStatus->viewerCount > getSettings()->smallStreamerLimit) {
if (streamStatus->live &&
streamStatus->viewerCount > getSettings()->smallStreamerLimit) {
return;
}
}
// get viewer list
NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->getName() + "/chatters");
NetworkRequest request("https://tmi.twitch.tv/group/user/" +
this->getName() + "/chatters");
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome {
// channel still exists?
auto shared = weak.lock();
if (!shared) return Failure;
request.onSuccess(
[this, weak = this->weak_from_this()](auto result) -> Outcome {
// channel still exists?
auto shared = weak.lock();
if (!shared) return Failure;
return this->parseViewerList(result.parseJson());
});
return this->parseViewerList(result.parseJson());
});
request.execute();
}
Outcome TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
{
static QStringList categories = {"moderators", "staff", "admins", "global_mods", "viewers"};
static QStringList categories = {"moderators", "staff", "admins",
"global_mods", "viewers"};
// parse json
QJsonObject jsonCategories = jsonRoot.value("chatters").toObject();
for (const auto &category : categories) {
for (const auto jsonCategory : jsonCategories.value(category).toArray()) {
for (const auto jsonCategory :
jsonCategories.value(category).toArray()) {
this->completionModel.addUser(jsonCategory.toString());
}
}
@@ -515,8 +536,8 @@ Outcome TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
void TwitchChannel::loadBadges()
{
auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" + this->getRoomId() +
"/display?language=en"};
auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" +
this->getRoomId() + "/display?language=en"};
NetworkRequest req(url.string);
req.setCaller(QThread::currentThread());
@@ -529,19 +550,24 @@ void TwitchChannel::loadBadges()
auto jsonRoot = result.parseJson();
auto _ = jsonRoot["badge_sets"].toObject();
for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end(); jsonBadgeSet++) {
for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end();
jsonBadgeSet++) {
auto &versions = (*badgeSets)[jsonBadgeSet.key()];
auto _ = jsonBadgeSet->toObject()["versions"].toObject();
for (auto jsonVersion_ = _.begin(); jsonVersion_ != _.end(); jsonVersion_++) {
for (auto jsonVersion_ = _.begin(); jsonVersion_ != _.end();
jsonVersion_++) {
auto jsonVersion = jsonVersion_->toObject();
auto emote = std::make_shared<Emote>(
Emote{EmoteName{},
ImageSet{Image::fromUrl({jsonVersion["image_url_1x"].toString()}),
Image::fromUrl({jsonVersion["image_url_2x"].toString()}),
Image::fromUrl({jsonVersion["image_url_4x"].toString()})},
Tooltip{jsonRoot["description"].toString()},
Url{jsonVersion["clickURL"].toString()}});
auto emote = std::make_shared<Emote>(Emote{
EmoteName{},
ImageSet{Image::fromUrl(
{jsonVersion["image_url_1x"].toString()}),
Image::fromUrl(
{jsonVersion["image_url_2x"].toString()}),
Image::fromUrl(
{jsonVersion["image_url_4x"].toString()})},
Tooltip{jsonRoot["description"].toString()},
Url{jsonVersion["clickURL"].toString()}});
versions.emplace(jsonVersion_.key(), emote);
};
@@ -555,63 +581,67 @@ void TwitchChannel::loadBadges()
void TwitchChannel::loadCheerEmotes()
{
auto url = Url{"https://api.twitch.tv/kraken/bits/actions?channel_id=" + this->getRoomId()};
auto url = Url{"https://api.twitch.tv/kraken/bits/actions?channel_id=" +
this->getRoomId()};
auto request = NetworkRequest::twitchRequest(url.string);
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto cheerEmoteSets = ParseCheermoteSets(result.parseRapidJson());
request.onSuccess(
[this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto cheerEmoteSets = ParseCheermoteSets(result.parseRapidJson());
for (auto &set : cheerEmoteSets) {
auto cheerEmoteSet = CheerEmoteSet();
cheerEmoteSet.regex = QRegularExpression("^" + set.prefix.toLower() + "([1-9][0-9]*)$");
for (auto &set : cheerEmoteSets) {
auto cheerEmoteSet = CheerEmoteSet();
cheerEmoteSet.regex = QRegularExpression(
"^" + set.prefix.toLower() + "([1-9][0-9]*)$");
for (auto &tier : set.tiers) {
CheerEmote cheerEmote;
for (auto &tier : set.tiers) {
CheerEmote cheerEmote;
cheerEmote.color = QColor(tier.color);
cheerEmote.minBits = tier.minBits;
cheerEmote.color = QColor(tier.color);
cheerEmote.minBits = tier.minBits;
// TODO(pajlada): We currently hardcode dark here :|
// We will continue to do so for now since we haven't had to
// solve that anywhere else
// TODO(pajlada): We currently hardcode dark here :|
// We will continue to do so for now since we haven't had to
// solve that anywhere else
cheerEmote.animatedEmote =
std::make_shared<Emote>(Emote{EmoteName{"cheer emote"},
ImageSet{
tier.images["dark"]["animated"]["1"],
tier.images["dark"]["animated"]["2"],
tier.images["dark"]["animated"]["4"],
},
Tooltip{}, Url{}});
cheerEmote.staticEmote =
std::make_shared<Emote>(Emote{EmoteName{"cheer emote"},
ImageSet{
tier.images["dark"]["static"]["1"],
tier.images["dark"]["static"]["2"],
tier.images["dark"]["static"]["4"],
},
Tooltip{}, Url{}});
cheerEmote.animatedEmote = std::make_shared<Emote>(
Emote{EmoteName{"cheer emote"},
ImageSet{
tier.images["dark"]["animated"]["1"],
tier.images["dark"]["animated"]["2"],
tier.images["dark"]["animated"]["4"],
},
Tooltip{}, Url{}});
cheerEmote.staticEmote = std::make_shared<Emote>(
Emote{EmoteName{"cheer emote"},
ImageSet{
tier.images["dark"]["static"]["1"],
tier.images["dark"]["static"]["2"],
tier.images["dark"]["static"]["4"],
},
Tooltip{}, Url{}});
cheerEmoteSet.cheerEmotes.emplace_back(cheerEmote);
cheerEmoteSet.cheerEmotes.emplace_back(cheerEmote);
}
std::sort(cheerEmoteSet.cheerEmotes.begin(),
cheerEmoteSet.cheerEmotes.end(),
[](const auto &lhs, const auto &rhs) {
return lhs.minBits < rhs.minBits; //
});
this->cheerEmoteSets_.emplace_back(cheerEmoteSet);
}
std::sort(cheerEmoteSet.cheerEmotes.begin(), cheerEmoteSet.cheerEmotes.end(),
[](const auto &lhs, const auto &rhs) {
return lhs.minBits < rhs.minBits; //
});
this->cheerEmoteSets_.emplace_back(cheerEmoteSet);
}
return Success;
});
return Success;
});
request.execute();
}
boost::optional<EmotePtr> TwitchChannel::getTwitchBadge(const QString &set,
const QString &version) const
boost::optional<EmotePtr> TwitchChannel::getTwitchBadge(
const QString &set, const QString &version) const
{
auto badgeSets = this->badgeSets_.access();
auto it = badgeSets->find(set);
+2 -1
View File
@@ -78,7 +78,8 @@ public:
const QString &getChannelUrl();
const QString &getPopoutPlayerUrl();
boost::optional<EmotePtr> getTwitchBadge(const QString &set, const QString &version) const;
boost::optional<EmotePtr> getTwitchBadge(const QString &set,
const QString &version) const;
// Signals
pajlada::Signals::NoArgSignal roomIdChanged;
+19 -15
View File
@@ -14,13 +14,16 @@ TwitchEmotes::TwitchEmotes()
// id is used for lookup
// emoteName is used for giving a name to the emote in case it doesn't exist
EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name_)
EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id,
const EmoteName &name_)
{
static QMap<QString, QString> replacements{
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"},
{"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"},
{"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("},
{"\\&lt\\;3", "&lt;3"}, {"\\:-?(o|O)", ":O"},
{"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("},
{"\\:-?\\)", ":)"}, {"\\:-?D", ":D"},
{"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
@@ -42,14 +45,14 @@ EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name
auto shared = (*cache)[id].lock();
if (!shared) {
(*cache)[id] = shared =
std::make_shared<Emote>(Emote{EmoteName{name},
ImageSet{
Image::fromUrl(getEmoteLink(id, "1.0"), 1),
Image::fromUrl(getEmoteLink(id, "2.0"), 0.5),
Image::fromUrl(getEmoteLink(id, "3.0"), 0.25),
},
Tooltip{name}, Url{}});
(*cache)[id] = shared = std::make_shared<Emote>(
Emote{EmoteName{name},
ImageSet{
Image::fromUrl(getEmoteLink(id, "1.0"), 1),
Image::fromUrl(getEmoteLink(id, "2.0"), 0.5),
Image::fromUrl(getEmoteLink(id, "3.0"), 0.25),
},
Tooltip{name}, Url{}});
}
return shared;
@@ -57,8 +60,9 @@ EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name
Url TwitchEmotes::getEmoteLink(const EmoteId &id, const QString &emoteScale)
{
return {
QString(TWITCH_EMOTE_TEMPLATE).replace("{id}", id.string).replace("{scale}", emoteScale)};
return {QString(TWITCH_EMOTE_TEMPLATE)
.replace("{id}", id.string)
.replace("{scale}", emoteScale)};
}
AccessGuard<std::unordered_map<EmoteName, EmotePtr>> TwitchEmotes::accessAll()
+4 -2
View File
@@ -11,7 +11,8 @@
#include "providers/twitch/TwitchEmotes.hpp"
#include "util/ConcurrentMap.hpp"
#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
#define TWITCH_EMOTE_TEMPLATE \
"https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
namespace chatterino {
@@ -26,7 +27,8 @@ public:
private:
UniqueAccess<std::unordered_map<EmoteName, EmotePtr>> twitchEmotes_;
UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<Emote>>> twitchEmotesCache_;
UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<Emote>>>
twitchEmotesCache_;
};
} // namespace chatterino
+158 -98
View File
@@ -20,9 +20,9 @@
namespace chatterino {
TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel,
const Communi::IrcPrivateMessage *_ircMessage,
const MessageParseArgs &_args)
TwitchMessageBuilder::TwitchMessageBuilder(
Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage,
const MessageParseArgs &_args)
: channel(_channel)
, twitchChannel(dynamic_cast<TwitchChannel *>(_channel))
, ircMessage(_ircMessage)
@@ -35,10 +35,9 @@ TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel,
this->usernameColor_ = app->themes->messages.textColors.system;
}
TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel,
const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args, QString content,
bool isAction)
TwitchMessageBuilder::TwitchMessageBuilder(
Channel *_channel, const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args, QString content, bool isAction)
: channel(_channel)
, twitchChannel(dynamic_cast<TwitchChannel *>(_channel))
, ircMessage(_ircMessage)
@@ -58,17 +57,21 @@ bool TwitchMessageBuilder::isIgnored() const
// TODO(pajlada): Do we need to check if the phrase is valid first?
for (const auto &phrase : app->ignores->phrases.getVector()) {
if (phrase.isMatch(this->originalMessage_)) {
Log("Blocking message because it contains ignored phrase {}", phrase.getPattern());
Log("Blocking message because it contains ignored phrase {}",
phrase.getPattern());
return true;
}
}
if (app->settings->enableTwitchIgnoredUsers && this->tags.contains("user-id")) {
if (app->settings->enableTwitchIgnoredUsers &&
this->tags.contains("user-id")) {
auto sourceUserID = this->tags.value("user-id").toString();
for (const auto &user : app->accounts->twitch.getCurrent()->getIgnores()) {
for (const auto &user :
app->accounts->twitch.getCurrent()->getIgnores()) {
if (sourceUserID == user.id) {
Log("Blocking message because it's from blocked user {}", user.name);
Log("Blocking message because it's from blocked user {}",
user.name);
return true;
}
}
@@ -162,8 +165,9 @@ MessagePtr TwitchMessageBuilder::build()
this->appendTwitchEmote(ircMessage, emote, twitchEmotes);
}
std::sort(twitchEmotes.begin(), twitchEmotes.end(),
[](const auto &a, const auto &b) { return a.first < b.first; });
std::sort(
twitchEmotes.begin(), twitchEmotes.end(),
[](const auto &a, const auto &b) { return a.first < b.first; });
}
// words
@@ -176,17 +180,20 @@ MessagePtr TwitchMessageBuilder::build()
return this->getMessage();
}
void TwitchMessageBuilder::addWords(const QStringList &words,
const std::vector<std::pair<int, EmotePtr>> &twitchEmotes)
void TwitchMessageBuilder::addWords(
const QStringList &words,
const std::vector<std::pair<int, EmotePtr>> &twitchEmotes)
{
auto i = int();
auto currentTwitchEmote = twitchEmotes.begin();
for (const auto &word : words) {
// check if it's a twitch emote twitch emote
if (currentTwitchEmote != twitchEmotes.end() && currentTwitchEmote->first == i) {
if (currentTwitchEmote != twitchEmotes.end() &&
currentTwitchEmote->first == i) {
auto emoteImage = currentTwitchEmote->second;
this->emplace<EmoteElement>(emoteImage, MessageElement::TwitchEmote);
this->emplace<EmoteElement>(emoteImage,
MessageElement::TwitchEmote);
i += word.length() + 1;
currentTwitchEmote++;
@@ -196,9 +203,12 @@ void TwitchMessageBuilder::addWords(const QStringList &words,
// split words
for (auto &variant : getApp()->emotes->emojis.parse(word)) {
boost::apply_visitor(/*overloaded{[&](EmotePtr arg) { this->addTextOrEmoji(arg); },
[&](const QString &arg) { this->addTextOrEmoji(arg); }}*/
[&](auto &&arg) { this->addTextOrEmoji(arg); }, variant);
boost::apply_visitor(/*overloaded{[&](EmotePtr arg) {
this->addTextOrEmoji(arg); },
[&](const QString &arg) {
this->addTextOrEmoji(arg); }}*/
[&](auto &&arg) { this->addTextOrEmoji(arg); },
variant);
}
for (int j = 0; j < word.size(); j++) {
@@ -240,14 +250,15 @@ void TwitchMessageBuilder::addTextOrEmoji(const QString &string_)
// Actually just text
auto linkString = this->matchLink(string);
auto link = Link();
auto textColor =
this->action_ ? MessageColor(this->usernameColor_) : MessageColor(MessageColor::Text);
auto textColor = this->action_ ? MessageColor(this->usernameColor_)
: MessageColor(MessageColor::Text);
if (linkString.isEmpty()) {
if (string.startsWith('@')) {
this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
FontStyle::ChatMediumBold);
this->emplace<TextElement>(string, TextElement::NonBoldUsername, textColor);
this->emplace<TextElement>(string, TextElement::BoldUsername,
textColor, FontStyle::ChatMediumBold);
this->emplace<TextElement>(string, TextElement::NonBoldUsername,
textColor);
} else {
this->emplace<TextElement>(string, TextElement::Text, textColor);
}
@@ -260,22 +271,26 @@ void TwitchMessageBuilder::addTextOrEmoji(const QString &string_)
auto match = domainRegex.match(string);
if (match.isValid()) {
lowercaseLinkString = string.mid(0, match.capturedStart(1)) +
match.captured(1).toLower() + string.mid(match.capturedEnd(1));
match.captured(1).toLower() +
string.mid(match.capturedEnd(1));
} else {
lowercaseLinkString = string;
}
link = Link(Link::Url, linkString);
textColor = MessageColor(MessageColor::Link);
this->emplace<TextElement>(lowercaseLinkString, TextElement::LowercaseLink, textColor)
this->emplace<TextElement>(lowercaseLinkString,
TextElement::LowercaseLink, textColor)
->setLink(link);
this->emplace<TextElement>(string, TextElement::OriginalLink, textColor)
->setLink(link);
this->emplace<TextElement>(string, TextElement::OriginalLink, textColor)->setLink(link);
}
// if (!linkString.isEmpty()) {
// if (getApp()->settings->lowercaseLink) {
// QRegularExpression httpRegex("\\bhttps?://",
// QRegularExpression::CaseInsensitiveOption); QRegularExpression ftpRegex("\\bftps?://",
// QRegularExpression::CaseInsensitiveOption); QRegularExpression
// ftpRegex("\\bftps?://",
// QRegularExpression::CaseInsensitiveOption); QRegularExpression
// getDomain("\\/\\/([^\\/]*)"); QString tempString = string;
@@ -291,7 +306,8 @@ void TwitchMessageBuilder::addTextOrEmoji(const QString &string_)
// textColor = MessageColor(MessageColor::Link);
//}
// if (string.startsWith('@')) {
// this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
// this->emplace<TextElement>(string, TextElement::BoldUsername,
// textColor,
// FontStyle::ChatMediumBold) //
// ->setLink(link);
// this->emplace<TextElement>(string, TextElement::NonBoldUsername,
@@ -334,7 +350,8 @@ void TwitchMessageBuilder::appendChannelName()
QString channelName("#" + this->channel->getName());
Link link(Link::Url, this->channel->getName() + "\n" + this->messageID);
this->emplace<TextElement>(channelName, MessageElement::ChannelName, MessageColor::System) //
this->emplace<TextElement>(channelName, MessageElement::ChannelName,
MessageColor::System) //
->setLink(link);
}
@@ -355,7 +372,8 @@ void TwitchMessageBuilder::parseUsername()
// display name
// auto displayNameVariant = this->tags.value("display-name");
// if (displayNameVariant.isValid()) {
// this->userName = displayNameVariant.toString() + " (" + this->userName + ")";
// this->userName = displayNameVariant.toString() + " (" +
// this->userName + ")";
// }
this->message_->loginName = this->userName;
@@ -371,9 +389,11 @@ void TwitchMessageBuilder::appendUsername()
auto iterator = this->tags.find("display-name");
if (iterator != this->tags.end()) {
QString displayName = parseTagString(iterator.value().toString()).trimmed();
QString displayName =
parseTagString(iterator.value().toString()).trimmed();
if (QString::compare(displayName, this->userName, Qt::CaseInsensitive) == 0) {
if (QString::compare(displayName, this->userName,
Qt::CaseInsensitive) == 0) {
username = displayName;
this->message_->displayName = displayName;
@@ -391,7 +411,8 @@ void TwitchMessageBuilder::appendUsername()
QString usernameText;
pajlada::Settings::Setting<int> usernameDisplayMode(
"/appearance/messages/usernameDisplayMode", UsernameDisplayMode::UsernameAndLocalizedName);
"/appearance/messages/usernameDisplayMode",
UsernameDisplayMode::UsernameAndLocalizedName);
switch (usernameDisplayMode.getValue()) {
case UsernameDisplayMode::Username: {
@@ -418,10 +439,12 @@ void TwitchMessageBuilder::appendUsername()
if (this->args.isSentWhisper) {
// TODO(pajlada): Re-implement
// userDisplayString += IrcManager::getInstance().getUser().getUserName();
// userDisplayString +=
// IrcManager::getInstance().getUser().getUserName();
} else if (this->args.isReceivedWhisper) {
// Sender username
this->emplace<TextElement>(usernameText, MessageElement::Text, this->usernameColor_,
this->emplace<TextElement>(usernameText, MessageElement::Text,
this->usernameColor_,
FontStyle::ChatMediumBold)
->setLink({Link::UserInfo, this->userName});
@@ -429,7 +452,8 @@ void TwitchMessageBuilder::appendUsername()
// Separator
this->emplace<TextElement>("->", MessageElement::Text,
app->themes->messages.textColors.system, FontStyle::ChatMedium);
app->themes->messages.textColors.system,
FontStyle::ChatMedium);
QColor selfColor = currentUser->color;
if (!selfColor.isValid()) {
@@ -437,14 +461,16 @@ void TwitchMessageBuilder::appendUsername()
}
// Your own username
this->emplace<TextElement>(currentUser->getUserName() + ":", MessageElement::Text,
selfColor, FontStyle::ChatMediumBold);
this->emplace<TextElement>(currentUser->getUserName() + ":",
MessageElement::Text, selfColor,
FontStyle::ChatMediumBold);
} else {
if (!this->action_) {
usernameText += ":";
}
this->emplace<TextElement>(usernameText, MessageElement::Text, this->usernameColor_,
this->emplace<TextElement>(usernameText, MessageElement::Text,
this->usernameColor_,
FontStyle::ChatMediumBold)
->setLink({Link::UserInfo, this->userName});
}
@@ -470,7 +496,8 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
// update the media player url if necessary
QUrl highlightSoundUrl;
if (app->settings->customHighlightSound) {
highlightSoundUrl = QUrl::fromLocalFile(app->settings->pathHighlightSound.getValue());
highlightSoundUrl =
QUrl::fromLocalFile(app->settings->pathHighlightSound.getValue());
} else {
highlightSoundUrl = QUrl("qrc:/sounds/ping2.wav");
}
@@ -483,12 +510,15 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
// TODO: This vector should only be rebuilt upon highlights being changed
// fourtf: should be implemented in the HighlightsController
std::vector<HighlightPhrase> activeHighlights = app->highlights->phrases.getVector();
std::vector<HighlightPhrase> userHighlights = app->highlights->highlightedUsers.getVector();
std::vector<HighlightPhrase> activeHighlights =
app->highlights->phrases.getVector();
std::vector<HighlightPhrase> userHighlights =
app->highlights->highlightedUsers.getVector();
if (app->settings->enableHighlightsSelf && currentUsername.size() > 0) {
HighlightPhrase selfHighlight(currentUsername, app->settings->enableHighlightTaskbar,
app->settings->enableHighlightSound, false);
HighlightPhrase selfHighlight(
currentUsername, app->settings->enableHighlightTaskbar,
app->settings->enableHighlightSound, false);
activeHighlights.emplace_back(std::move(selfHighlight));
}
@@ -514,15 +544,17 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
}
if (playSound && doAlert) {
// Break if no further action can be taken from other highlights
// This might change if highlights can have custom colors/sounds/actions
// Break if no further action can be taken from other
// highlights This might change if highlights can have
// custom colors/sounds/actions
break;
}
}
}
for (const HighlightPhrase &userHighlight : userHighlights) {
if (userHighlight.isMatch(this->ircMessage->nick())) {
Log("Highlight because user {} sent a message", this->ircMessage->nick());
Log("Highlight because user {} sent a message",
this->ircMessage->nick());
doHighlight = true;
if (userHighlight.getAlert()) {
@@ -534,8 +566,8 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
}
if (playSound && doAlert) {
// Break if no further action can be taken from other usernames
// Mostly used for regex stuff
// Break if no further action can be taken from other
// usernames Mostly used for regex stuff
break;
}
}
@@ -544,12 +576,14 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
this->setHighlight(doHighlight);
if (!isPastMsg) {
if (playSound && (!hasFocus || app->settings->highlightAlwaysPlaySound)) {
if (playSound &&
(!hasFocus || app->settings->highlightAlwaysPlaySound)) {
player->play();
}
if (doAlert) {
QApplication::alert(getApp()->windows->getMainWindow().window(), 2500);
QApplication::alert(getApp()->windows->getMainWindow().window(),
2500);
}
}
@@ -559,9 +593,9 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
}
}
void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessage,
const QString &emote,
std::vector<std::pair<int, EmotePtr>> &vec)
void TwitchMessageBuilder::appendTwitchEmote(
const Communi::IrcMessage *ircMessage, const QString &emote,
std::vector<std::pair<int, EmotePtr>> &vec)
{
auto app = getApp();
if (!emote.contains(':')) {
@@ -588,13 +622,16 @@ void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessa
auto start = coords.at(0).toInt();
auto end = coords.at(1).toInt();
if (start >= end || start < 0 || end > this->originalMessage_.length()) {
if (start >= end || start < 0 ||
end > this->originalMessage_.length()) {
return;
}
auto name = EmoteName{this->originalMessage_.mid(start, end - start + 1)};
auto name =
EmoteName{this->originalMessage_.mid(start, end - start + 1)};
vec.push_back(std::make_pair(start, app->emotes->twitch.getOrCreateEmote(id, name)));
vec.push_back(std::make_pair(
start, app->emotes->twitch.getOrCreateEmote(id, name)));
}
}
@@ -605,11 +642,13 @@ Outcome TwitchMessageBuilder::tryAppendEmote(const EmoteName &name)
if ((emote = getApp()->emotes->bttv.getGlobalEmote(name))) {
flags = MessageElement::BttvEmote;
} else if (twitchChannel && (emote = this->twitchChannel->getBttvEmote(name))) {
} else if (twitchChannel &&
(emote = this->twitchChannel->getBttvEmote(name))) {
flags = MessageElement::BttvEmote;
} else if ((emote = getApp()->emotes->ffz.getGlobalEmote(name))) {
flags = MessageElement::FfzEmote;
} else if (twitchChannel && (emote = this->twitchChannel->getFfzEmote(name))) {
} else if (twitchChannel &&
(emote = this->twitchChannel->getFfzEmote(name))) {
flags = MessageElement::FfzEmote;
}
@@ -622,7 +661,8 @@ Outcome TwitchMessageBuilder::tryAppendEmote(const EmoteName &name)
}
// fourtf: this is ugly
// maybe put the individual badges into a map instead of this mess
// maybe put the individual badges into a map instead of this
//mess
void TwitchMessageBuilder::appendTwitchBadges()
{
auto app = getApp();
@@ -653,9 +693,10 @@ void TwitchMessageBuilder::appendTwitchBadges()
// Try to fetch channel-specific bit badge
try {
if (twitchChannel)
if (const auto &badge =
this->twitchChannel->getTwitchBadge("bits", cheerAmount)) {
this->emplace<EmoteElement>(badge.get(), MessageElement::BadgeVanity)
if (const auto &badge = this->twitchChannel->getTwitchBadge(
"bits", cheerAmount)) {
this->emplace<EmoteElement>(badge.get(),
MessageElement::BadgeVanity)
->setTooltip(tooltip);
continue;
}
@@ -665,62 +706,72 @@ void TwitchMessageBuilder::appendTwitchBadges()
// Use default bit badge
// try {
// const auto &badge = app->resources->badgeSets.at("bits").versions.at(cheerAmount);
// this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
// const auto &badge =
// app->resources->badgeSets.at("bits").versions.at(cheerAmount);
// this->emplace<ImageElement>(badge.badgeImage1x,
// MessageElement::BadgeVanity)
// ->setTooltip(tooltip);
//} catch (const std::out_of_range &) {
// Log("No default bit badge for version {} found", cheerAmount);
// continue;
//}
} else if (badge == "staff/1") {
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.staff),
MessageElement::BadgeGlobalAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.staff),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Staff");
} else if (badge == "admin/1") {
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.admin),
MessageElement::BadgeGlobalAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.admin),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Admin");
} else if (badge == "global_mod/1") {
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.globalmod),
MessageElement::BadgeGlobalAuthority)
this->emplace<ImageElement>(Image::fromNonOwningPixmap(
&app->resources->twitch.globalmod),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Global Moderator");
} else if (badge == "moderator/1") {
// TODO: Implement custom FFZ moderator badge
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.moderator),
MessageElement::BadgeChannelAuthority)
this->emplace<ImageElement>(Image::fromNonOwningPixmap(
&app->resources->twitch.moderator),
MessageElement::BadgeChannelAuthority)
->setTooltip("Twitch Channel Moderator");
} else if (badge == "turbo/1") {
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.turbo),
MessageElement::BadgeGlobalAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.turbo),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Turbo Subscriber");
} else if (badge == "broadcaster/1") {
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.broadcaster),
Image::fromNonOwningPixmap(
&app->resources->twitch.broadcaster),
MessageElement::BadgeChannelAuthority)
->setTooltip("Twitch Broadcaster");
} else if (badge == "premium/1") {
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.prime),
MessageElement::BadgeVanity)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.prime),
MessageElement::BadgeVanity)
->setTooltip("Twitch Prime Subscriber");
} else if (badge.startsWith("partner/")) {
int index = badge.midRef(8).toInt();
switch (index) {
case 1: {
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.verified),
Image::fromNonOwningPixmap(
&app->resources->twitch.verified),
MessageElement::BadgeVanity)
->setTooltip("Twitch Verified");
} break;
default: {
printf("[TwitchMessageBuilder] Unhandled partner badge index: %d\n", index);
printf("[TwitchMessageBuilder] Unhandled partner badge "
"index: %d\n",
index);
} break;
}
} else if (badge.startsWith("subscriber/")) {
// if (channelResources.loaded == false) {
// // qDebug() << "Channel resources are not loaded, can't add the
// subscriber
// // qDebug() << "Channel resources are not loaded,
// can't add the subscriber
// // badge";
// continue;
// }
@@ -752,7 +803,8 @@ void TwitchMessageBuilder::appendTwitchBadges()
// this->emplace<ImageElement>(badgeVersion.badgeImage1x,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
// ->setTooltip("Twitch " +
// QString::fromStdString(badgeVersion.title));
} else {
// if (!app->resources->dynamicBadgesLoaded) {
// // Do nothing
@@ -762,11 +814,12 @@ void TwitchMessageBuilder::appendTwitchBadges()
// QStringList parts = badge.split('/');
// if (parts.length() != 2) {
// qDebug() << "Bad number of parts: " << parts.length() << " in " << parts;
// continue;
// qDebug() << "Bad number of parts: " << parts.length() << " in
// " << parts; continue;
//}
// MessageElement::Flags badgeType = MessageElement::Flags::BadgeVanity;
// MessageElement::Flags badgeType =
// MessageElement::Flags::BadgeVanity;
// std::string badgeSetKey = parts[0].toStdString();
// std::string versionKey = parts[1].toStdString();
@@ -777,11 +830,14 @@ void TwitchMessageBuilder::appendTwitchBadges()
// try {
// auto &badgeVersion = badgeSet.versions.at(versionKey);
// this->emplace<ImageElement>(badgeVersion.badgeImage1x, badgeType)
// ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
// this->emplace<ImageElement>(badgeVersion.badgeImage1x,
// badgeType)
// ->setTooltip("Twitch " +
// QString::fromStdString(badgeVersion.title));
// } catch (const std::exception &e) {
// qDebug() << "Exception caught:" << e.what()
// << "when trying to fetch badge version " << versionKey.c_str();
// << "when trying to fetch badge version " <<
// versionKey.c_str();
// }
//} catch (const std::exception &e) {
// qDebug() << "No badge set with key" << badgeSetKey.c_str()
@@ -804,7 +860,8 @@ void TwitchMessageBuilder::appendChatterinoBadges()
// const auto badge = it->second;
// this->emplace<ImageElement>(badge->image, MessageElement::BadgeChatterino)
// this->emplace<ImageElement>(badge->image,
// MessageElement::BadgeChatterino)
// ->setTooltip(QString::fromStdString(badge->tooltip));
}
@@ -830,7 +887,8 @@ Outcome TwitchMessageBuilder::tryParseCheermote(const QString &string)
// auto savedIt = cheermoteSet.cheermotes.end();
// // Fetch cheermote that matches our numBits
// for (auto it = cheermoteSet.cheermotes.begin(); it != cheermoteSet.cheermotes.end();
// for (auto it = cheermoteSet.cheermotes.begin(); it !=
// cheermoteSet.cheermotes.end();
// ++it) {
// if (numBits >= it->minBits) {
// savedIt = it;
@@ -840,15 +898,17 @@ Outcome TwitchMessageBuilder::tryParseCheermote(const QString &string)
// }
// if (savedIt == cheermoteSet.cheermotes.end()) {
// Log("Error getting a cheermote from a cheermote set for the bit amount {}",
// Log("Error getting a cheermote from a cheermote set for the
// bit amount {}",
// numBits);
// return Failure;
// }
// const auto &cheermote = *savedIt;
// this->emplace<EmoteElement>(cheermote.animatedEmote, EmoteElement::BitsAnimated);
// this->emplace<TextElement>(amount, EmoteElement::Text, cheermote.color);
// this->emplace<EmoteElement>(cheermote.animatedEmote,
// EmoteElement::BitsAnimated); this->emplace<TextElement>(amount,
// EmoteElement::Text, cheermote.color);
// return Success;
// }
@@ -25,10 +25,13 @@ public:
TwitchMessageBuilder() = delete;
explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage,
explicit TwitchMessageBuilder(Channel *_channel,
const Communi::IrcPrivateMessage *_ircMessage,
const MessageParseArgs &_args);
explicit TwitchMessageBuilder(Channel *_channel, const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args, QString content, bool isAction);
explicit TwitchMessageBuilder(Channel *_channel,
const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args,
QString content, bool isAction);
Channel *channel;
TwitchChannel *twitchChannel;
@@ -50,7 +53,8 @@ private:
void appendUsername();
void parseHighlights(bool isPastMsg);
void appendTwitchEmote(const Communi::IrcMessage *ircMessage, const QString &emote,
void appendTwitchEmote(const Communi::IrcMessage *ircMessage,
const QString &emote,
std::vector<std::pair<int, EmotePtr>> &vec);
Outcome tryAppendEmote(const EmoteName &name);
+21 -11
View File
@@ -9,7 +9,8 @@ namespace chatterino {
namespace {
template <typename Type>
inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out)
inline bool ReadValue(const rapidjson::Value &object, const char *key,
Type &out)
{
if (!object.HasMember(key)) {
return false;
@@ -27,7 +28,8 @@ inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out
}
template <>
inline bool ReadValue<QString>(const rapidjson::Value &object, const char *key, QString &out)
inline bool ReadValue<QString>(const rapidjson::Value &object, const char *key,
QString &out)
{
if (!object.HasMember(key)) {
return false;
@@ -45,7 +47,8 @@ inline bool ReadValue<QString>(const rapidjson::Value &object, const char *key,
}
template <>
inline bool ReadValue<std::vector<QString>>(const rapidjson::Value &object, const char *key,
inline bool ReadValue<std::vector<QString>>(const rapidjson::Value &object,
const char *key,
std::vector<QString> &out)
{
if (!object.HasMember(key)) {
@@ -70,7 +73,8 @@ inline bool ReadValue<std::vector<QString>>(const rapidjson::Value &object, cons
}
// Parse a single cheermote set (or "action") from the twitch api
inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Value &action)
inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set,
const rapidjson::Value &action)
{
if (!action.IsObject()) {
return false;
@@ -160,13 +164,15 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu
continue;
}
const rapidjson::Value &imageBackgroundStates = imageBackgroundValue.value;
const rapidjson::Value &imageBackgroundStates =
imageBackgroundValue.value;
if (!imageBackgroundStates.IsObject()) {
continue;
}
// Read each key which represents a background
for (const auto &imageBackgroundState : imageBackgroundStates.GetObject()) {
for (const auto &imageBackgroundState :
imageBackgroundStates.GetObject()) {
QString state = imageBackgroundState.name.GetString();
bool stateExists = false;
for (const auto &_state : set.states) {
@@ -180,13 +186,15 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu
continue;
}
const rapidjson::Value &imageScalesValue = imageBackgroundState.value;
const rapidjson::Value &imageScalesValue =
imageBackgroundState.value;
if (!imageScalesValue.IsObject()) {
continue;
}
// Read each key which represents a scale
for (const auto &imageScaleValue : imageScalesValue.GetObject()) {
for (const auto &imageScaleValue :
imageScalesValue.GetObject()) {
QString scale = imageScaleValue.name.GetString();
bool scaleExists = false;
for (const auto &_scale : set.scales) {
@@ -200,7 +208,8 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu
continue;
}
const rapidjson::Value &imageScaleURLValue = imageScaleValue.value;
const rapidjson::Value &imageScaleURLValue =
imageScaleValue.value;
if (!imageScaleURLValue.IsString()) {
continue;
}
@@ -230,8 +239,9 @@ inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Valu
}
} // namespace
// Look through the results of https://api.twitch.tv/kraken/bits/actions?channel_id=11148817 for
// cheermote sets or "Actions" as they are called in the API
// Look through the results of
// https://api.twitch.tv/kraken/bits/actions?channel_id=11148817 for cheermote
// sets or "Actions" as they are called in the API
std::vector<JSONCheermoteSet> ParseCheermoteSets(const rapidjson::Document &d)
{
std::vector<JSONCheermoteSet> sets;
@@ -25,7 +25,8 @@ struct JSONCheermoteSet {
QString color;
// Background State Scale
std::map<QString, std::map<QString, std::map<QString, ImagePtr>>> images;
std::map<QString, std::map<QString, std::map<QString, ImagePtr>>>
images;
};
std::vector<CheermoteTier> tiers;
+36 -21
View File
@@ -29,8 +29,10 @@ TwitchServer::TwitchServer()
this->pubsub = new PubSub;
// getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) { this->connect(); },
// this->signalHolder_, false);
// getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) {
// this->connect(); },
// this->signalHolder_,
// false);
}
void TwitchServer::initialize(Settings &settings, Paths &paths)
@@ -39,11 +41,13 @@ void TwitchServer::initialize(Settings &settings, Paths &paths)
[this]() { postToThread([this] { this->connect(); }); });
}
void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead, bool isWrite)
void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead,
bool isWrite)
{
this->singleConnection_ = isRead == isWrite;
std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent();
std::shared_ptr<TwitchAccount> account =
getApp()->accounts->twitch.getCurrent();
qDebug() << "logging in as" << account->getUserName();
@@ -62,9 +66,12 @@ void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead,
connection->setPassword(oauthToken);
}
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership"));
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/commands"));
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/tags"));
connection->sendCommand(
Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership"));
connection->sendCommand(
Communi::IrcCommand::createCapability("REQ", "twitch.tv/commands"));
connection->sendCommand(
Communi::IrcCommand::createCapability("REQ", "twitch.tv/tags"));
connection->setHost("irc.chat.twitch.tv");
connection->setPort(6667);
@@ -74,9 +81,10 @@ std::shared_ptr<Channel> TwitchServer::createChannel(const QString &channelName)
{
TwitchChannel *channel = new TwitchChannel(channelName);
channel->sendMessageSignal.connect([this, channel](auto &chan, auto &msg, bool &sent) {
this->onMessageSendRequested(channel, msg, sent);
});
channel->sendMessageSignal.connect(
[this, channel](auto &chan, auto &msg, bool &sent) {
this->onMessageSendRequested(channel, msg, sent);
});
return std::shared_ptr<Channel>(channel);
}
@@ -113,7 +121,8 @@ void TwitchServer::messageReceived(Communi::IrcMessage *message)
} else if (command == "MODE") {
handler.handleModeMessage(message);
} else if (command == "NOTICE") {
handler.handleNoticeMessage(static_cast<Communi::IrcNoticeMessage *>(message));
handler.handleNoticeMessage(
static_cast<Communi::IrcNoticeMessage *>(message));
} else if (command == "JOIN") {
handler.handleJoinMessage(message);
} else if (command == "PART") {
@@ -133,7 +142,8 @@ void TwitchServer::writeConnectionMessageReceived(Communi::IrcMessage *message)
}
}
std::shared_ptr<Channel> TwitchServer::getCustomChannel(const QString &channelName)
std::shared_ptr<Channel> TwitchServer::getCustomChannel(
const QString &channelName)
{
if (channelName == "/whispers") {
return this->whispersChannel;
@@ -146,7 +156,8 @@ std::shared_ptr<Channel> TwitchServer::getCustomChannel(const QString &channelNa
return nullptr;
}
void TwitchServer::forEachChannelAndSpecialChannels(std::function<void(ChannelPtr)> func)
void TwitchServer::forEachChannelAndSpecialChannels(
std::function<void(ChannelPtr)> func)
{
this->forEachChannel(func);
@@ -154,7 +165,8 @@ void TwitchServer::forEachChannelAndSpecialChannels(std::function<void(ChannelPt
func(this->mentionsChannel);
}
std::shared_ptr<Channel> TwitchServer::getChannelOrEmptyByID(const QString &channelId)
std::shared_ptr<Channel> TwitchServer::getChannelOrEmptyByID(
const QString &channelId)
{
std::lock_guard<std::mutex> lock(this->channelMutex);
@@ -184,8 +196,8 @@ bool TwitchServer::hasSeparateWriteConnection() const
// return getSettings()->twitchSeperateWriteConnection;
}
void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString &message,
bool &sent)
void TwitchServer::onMessageSendRequested(TwitchChannel *channel,
const QString &message, bool &sent)
{
sent = false;
@@ -193,17 +205,19 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString
std::lock_guard<std::mutex> guard(this->lastMessageMutex_);
// std::queue<std::chrono::steady_clock::time_point>
auto &lastMessage =
channel->hasModRights() ? this->lastMessageMod_ : this->lastMessagePleb_;
auto &lastMessage = channel->hasModRights() ? this->lastMessageMod_
: this->lastMessagePleb_;
size_t maxMessageCount = channel->hasModRights() ? 99 : 19;
auto minMessageOffset = (channel->hasModRights() ? 100ms : 1100ms);
auto now = std::chrono::steady_clock::now();
// check if you are sending messages too fast
if (!lastMessage.empty() && lastMessage.back() + minMessageOffset > now) {
if (!lastMessage.empty() &&
lastMessage.back() + minMessageOffset > now) {
if (this->lastErrorTimeSpeed_ + 30s < now) {
auto errorMessage = Message::createSystemMessage("sending messages too fast");
auto errorMessage =
Message::createSystemMessage("sending messages too fast");
channel->addMessage(errorMessage);
@@ -220,7 +234,8 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString
// check if you are sending too many messages
if (lastMessage.size() >= maxMessageCount) {
if (this->lastErrorTimeAmount_ + 30s < now) {
auto errorMessage = Message::createSystemMessage("sending too many messages");
auto errorMessage =
Message::createSystemMessage("sending too many messages");
channel->addMessage(errorMessage);
+10 -5
View File
@@ -40,19 +40,24 @@ public:
protected:
virtual void initializeConnection(IrcConnection *connection, bool isRead,
bool isWrite) override;
virtual std::shared_ptr<Channel> createChannel(const QString &channelName) override;
virtual std::shared_ptr<Channel> createChannel(
const QString &channelName) override;
virtual void privateMessageReceived(Communi::IrcPrivateMessage *message) override;
virtual void privateMessageReceived(
Communi::IrcPrivateMessage *message) override;
virtual void messageReceived(Communi::IrcMessage *message) override;
virtual void writeConnectionMessageReceived(Communi::IrcMessage *message) override;
virtual void writeConnectionMessageReceived(
Communi::IrcMessage *message) override;
virtual std::shared_ptr<Channel> getCustomChannel(const QString &channelname) override;
virtual std::shared_ptr<Channel> getCustomChannel(
const QString &channelname) override;
virtual QString cleanChannelName(const QString &dirtyChannelName) override;
virtual bool hasSeparateWriteConnection() const override;
private:
void onMessageSendRequested(TwitchChannel *channel, const QString &message, bool &sent);
void onMessageSendRequested(TwitchChannel *channel, const QString &message,
bool &sent);
std::mutex lastMessageMutex_;
std::queue<std::chrono::steady_clock::time_point> lastMessagePleb_;
+4 -2
View File
@@ -36,7 +36,8 @@ namespace Settings {
template <>
struct Deserialize<chatterino::TwitchUser> {
static chatterino::TwitchUser get(const rapidjson::Value &value, bool *error = nullptr)
static chatterino::TwitchUser get(const rapidjson::Value &value,
bool *error = nullptr)
{
using namespace chatterino;
@@ -44,7 +45,8 @@ struct Deserialize<chatterino::TwitchUser> {
if (!value.IsObject()) {
PAJLADA_REPORT_ERROR(error)
PAJLADA_THROW_EXCEPTION("Deserialized rapidjson::Value is wrong type");
PAJLADA_THROW_EXCEPTION(
"Deserialized rapidjson::Value is wrong type");
return user;
}