this commit is too big

This commit is contained in:
fourtf
2018-08-02 14:23:27 +02:00
parent 3b3c5d8d75
commit c2e2dfb577
186 changed files with 3626 additions and 2656 deletions
+70 -85
View File
@@ -3,122 +3,107 @@
#include "common/NetworkRequest.hpp"
#include "debug/Log.hpp"
#include "messages/Image.hpp"
#include "messages/ImageSet.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include <QJsonArray>
#include <QThread>
namespace chatterino {
namespace {
QString getEmoteLink(QString urlTemplate, const QString &id, const QString &emoteScale)
Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale)
{
urlTemplate.detach();
return urlTemplate.replace("{{id}}", id).replace("{{image}}", emoteScale);
return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)};
}
} // namespace
void BTTVEmotes::loadGlobalEmotes()
AccessGuard<const EmoteMap> BttvEmotes::accessGlobalEmotes() const
{
QString url("https://api.betterttv.net/2/emotes");
return this->globalEmotes_.accessConst();
}
boost::optional<EmotePtr> BttvEmotes::getGlobalEmote(const EmoteName &name)
{
auto emotes = this->globalEmotes_.access();
auto it = emotes->find(name);
if (it == emotes->end()) return boost::none;
return it->second;
}
// FOURTF: never returns anything
// boost::optional<EmotePtr> BttvEmotes::getEmote(const EmoteId &id)
//{
// auto cache = this->channelEmoteCache_.access();
// auto it = cache->find(id);
//
// if (it != cache->end()) {
// auto shared = it->second.lock();
// if (shared) {
// return shared;
// }
// }
//
// return boost::none;
//}
void BttvEmotes::loadGlobalEmotes()
{
auto request = NetworkRequest(QString(globalEmoteApiUrl));
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([this](auto result) {
auto root = result.parseJson();
auto emotes = root.value("emotes").toArray();
request.onSuccess([this](auto result) -> Outcome {
// if (auto shared = weak.lock()) {
auto currentEmotes = this->globalEmotes_.access();
QString urlTemplate = "https:" + root.value("urlTemplate").toString();
auto pair = this->parseGlobalEmotes(result.parseJson(), *currentEmotes);
std::vector<QString> codes;
for (const QJsonValue &emote : emotes) {
QString id = emote.toObject().value("id").toString();
QString code = emote.toObject().value("code").toString();
EmoteData emoteData;
emoteData.image1x = new Image(getEmoteLink(urlTemplate, id, "1x"), 1, code,
code + "<br />Global BTTV Emote");
emoteData.image2x = new Image(getEmoteLink(urlTemplate, id, "2x"), 0.5, code,
code + "<br />Global BTTV Emote");
emoteData.image3x = new Image(getEmoteLink(urlTemplate, id, "3x"), 0.25, code,
code + "<br />Global BTTV Emote");
emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id;
this->globalEmotes.insert(code, emoteData);
codes.push_back(code);
if (pair.first) {
*currentEmotes = std::move(pair.second);
}
this->globalEmoteCodes = codes;
return true;
return pair.first;
// }
return Failure;
});
request.execute();
}
void BTTVEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> _map)
std::pair<Outcome, EmoteMap> BttvEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot,
const EmoteMap &currentEmotes)
{
printf("[BTTVEmotes] Reload BTTV Channel Emotes for channel %s\n", qPrintable(channelName));
auto emotes = EmoteMap();
auto jsonEmotes = jsonRoot.value("emotes").toArray();
auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString());
QString url("https://api.betterttv.net/2/channels/" + channelName);
for (const QJsonValue &jsonEmote : jsonEmotes) {
auto id = EmoteId{jsonEmote.toObject().value("id").toString()};
auto name = EmoteName{jsonEmote.toObject().value("code").toString()};
Log("Request bttv channel emotes for {}", channelName);
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}});
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([this, channelName, _map](auto result) {
auto rootNode = result.parseJson();
auto map = _map.lock();
if (_map.expired()) {
return false;
auto it = currentEmotes.find(name);
if (it != currentEmotes.end() && *it->second == emote) {
// reuse old shared_ptr if nothing changed
emotes[name] = it->second;
} else {
emotes[name] = std::make_shared<Emote>(std::move(emote));
}
}
map->clear();
auto emotesNode = rootNode.value("emotes").toArray();
QString linkTemplate = "https:" + rootNode.value("urlTemplate").toString();
std::vector<QString> codes;
for (const QJsonValue &emoteNode : emotesNode) {
QJsonObject emoteObject = emoteNode.toObject();
QString id = emoteObject.value("id").toString();
QString code = emoteObject.value("code").toString();
// emoteObject.value("imageType").toString();
auto emote = this->channelEmoteCache_.getOrAdd(id, [&] {
EmoteData emoteData;
QString link = linkTemplate;
link.detach();
emoteData.image1x = new Image(link.replace("{{id}}", id).replace("{{image}}", "1x"),
1, code, code + "<br />Channel BTTV Emote");
link = linkTemplate;
link.detach();
emoteData.image2x = new Image(link.replace("{{id}}", id).replace("{{image}}", "2x"),
0.5, code, code + "<br />Channel BTTV Emote");
link = linkTemplate;
link.detach();
emoteData.image3x = new Image(link.replace("{{id}}", id).replace("{{image}}", "3x"),
0.25, code, code + "<br />Channel BTTV Emote");
emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id;
return emoteData;
});
this->channelEmotes.insert(code, emote);
map->insert(code, emote);
codes.push_back(code);
}
this->channelEmoteCodes[channelName] = codes;
return true;
});
request.execute();
return {Success, std::move(emotes)};
}
} // namespace chatterino
+17 -12
View File
@@ -1,27 +1,32 @@
#pragma once
#include "common/Emotemap.hpp"
#include "common/SimpleSignalVector.hpp"
#include "util/ConcurrentMap.hpp"
#include <memory>
#include <map>
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "messages/EmoteCache.hpp"
namespace chatterino {
class BTTVEmotes
class BttvEmotes final : std::enable_shared_from_this<BttvEmotes>
{
public:
EmoteMap globalEmotes;
SimpleSignalVector<QString> globalEmoteCodes;
static constexpr const char *globalEmoteApiUrl = "https://api.betterttv.net/2/emotes";
EmoteMap channelEmotes;
std::map<QString, SimpleSignalVector<QString>> channelEmoteCodes;
public:
// BttvEmotes();
AccessGuard<const EmoteMap> accessGlobalEmotes() const;
boost::optional<EmotePtr> getGlobalEmote(const EmoteName &name);
boost::optional<EmotePtr> getEmote(const EmoteId &id);
void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> channelEmoteMap);
private:
EmoteMap channelEmoteCache_;
std::pair<Outcome, EmoteMap> parseGlobalEmotes(const QJsonObject &jsonRoot,
const EmoteMap &currentEmotes);
UniqueAccess<EmoteMap> globalEmotes_;
// UniqueAccess<WeakEmoteIdMap> channelEmoteCache_;
};
} // namespace chatterino
@@ -0,0 +1,76 @@
#include "LoadBttvChannelEmote.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include "common/Common.hpp"
#include "common/NetworkRequest.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
namespace chatterino {
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)
{
auto request = NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
auto pair = bttvParseChannelEmotes(result.parseJson());
if (pair.first == Success) callback(std::move(pair.second));
return pair.first;
});
request.execute();
}
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(const QJsonObject &jsonRoot)
{
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());
for (auto jsonEmote_ : jsonEmotes) {
auto jsonEmote = jsonEmote_.toObject();
auto id = EmoteId{jsonEmote.value("id").toString()};
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 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));
}
}
return {Success, std::move(emotes)};
}
static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale)
{
urlTemplate.detach();
return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)};
}
} // namespace chatterino
@@ -0,0 +1,14 @@
#pragma once
#include <functional>
class QString;
namespace chatterino {
class EmoteMap;
constexpr const char *bttvChannelEmoteApiUrl = "https://api.betterttv.net/2/channels/";
void loadBttvChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback);
} // namespace chatterino
@@ -0,0 +1,50 @@
#include "ChatterinoBadges.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include "common/NetworkRequest.hpp"
namespace chatterino {
ChatterinoBadges::ChatterinoBadges()
{
}
boost::optional<EmotePtr> ChatterinoBadges::getBadge(const UserName &username)
{
return this->badges.access()->get(username);
}
void ChatterinoBadges::loadChatterinoBadges()
{
static QString url("https://fourtf.com/chatterino/badges.json");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) {
auto jsonRoot = result.parseJson();
auto badges = this->badges.access();
auto replacement = badges->makeReplacment();
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{}};
for (auto jsonUser : jsonBadge.value("users").toArray()) {
replacement.add(UserName{jsonUser.toString()}, std::move(emote));
}
}
replacement.apply();
return Success;
});
req.execute();
}
} // namespace chatterino
@@ -0,0 +1,25 @@
#pragma once
#include <boost/optional.hpp>
#include <unordered_map>
#include "common/Common.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "messages/EmoteCache.hpp"
namespace chatterino {
class ChatterinoBadges
{
public:
ChatterinoBadges();
boost::optional<EmotePtr> getBadge(const UserName &username);
private:
void loadChatterinoBadges();
UniqueAccess<EmoteCache<UserName>> badges;
};
} // namespace chatterino
+16 -8
View File
@@ -4,7 +4,12 @@
#include "debug/Log.hpp"
#include "singletons/Settings.hpp"
#include <rapidjson/error/en.h>
#include <rapidjson/error/error.h>
#include <rapidjson/rapidjson.h>
#include <QFile>
#include <boost/variant.hpp>
#include <memory>
namespace chatterino {
@@ -146,7 +151,7 @@ void Emojis::loadEmojis()
emojiData->shortCodes[0] + "_" + toneNameIt->second);
this->emojiShortCodeToEmoji_.insert(variationEmojiData->shortCodes[0],
variationEmojiData);
variationEmojiData);
this->shortCodes.push_back(variationEmojiData->shortCodes[0]);
this->emojiFirstByte_[variationEmojiData->value.at(0)].append(variationEmojiData);
@@ -260,14 +265,16 @@ void Emojis::loadEmojiSet()
urlPrefix = it->second;
}
QString url = urlPrefix + code + ".png";
emoji->emoteData.image1x =
new Image(url, 0.35, emoji->value, ":" + emoji->shortCodes[0] + ":<br/>Emoji");
emoji->emote = std::make_shared<Emote>(
Emote{EmoteName{emoji->value}, ImageSet{Image::fromUrl({url}, 0.35)},
Tooltip{":" + emoji->shortCodes[0] + ":<br/>Emoji"}, Url{}});
});
});
}
void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, 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;
for (auto i = 0; i < text.length(); ++i) {
@@ -327,12 +334,11 @@ void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, con
if (charactersFromLastParsedEmoji > 0) {
// Add characters inbetween emojis
parsedWords.emplace_back(
EmoteData(), text.mid(lastParsedEmojiEndIndex, charactersFromLastParsedEmoji));
result.emplace_back(text.mid(lastParsedEmojiEndIndex, charactersFromLastParsedEmoji));
}
// Push the emoji as a word to parsedWords
parsedWords.push_back(std::tuple<EmoteData, QString>(matchedEmoji->emoteData, QString()));
result.emplace_back(matchedEmoji->emote);
lastParsedEmojiEndIndex = currentParsedEmojiEndIndex;
@@ -341,8 +347,10 @@ void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, con
if (lastParsedEmojiEndIndex < text.length()) {
// Add remaining characters
parsedWords.emplace_back(EmoteData(), text.mid(lastParsedEmojiEndIndex));
result.emplace_back(text.mid(lastParsedEmojiEndIndex));
}
return result;
}
QString Emojis::replaceShortCodes(const QString &text)
+6 -3
View File
@@ -2,12 +2,15 @@
#include "common/Emotemap.hpp"
#include "common/SimpleSignalVector.hpp"
#include "messages/Emote.hpp"
#include "util/ConcurrentMap.hpp"
#include <QMap>
#include <QRegularExpression>
#include <boost/variant.hpp>
#include <map>
#include <set>
#include <vector>
namespace chatterino {
@@ -26,7 +29,7 @@ struct EmojiData {
std::vector<EmojiData> variations;
EmoteData emoteData;
EmotePtr emote;
};
using EmojiMap = ConcurrentMap<QString, std::shared_ptr<EmojiData>>;
@@ -36,7 +39,7 @@ class Emojis
public:
void initialize();
void load();
void parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, const QString &text);
std::vector<boost::variant<EmotePtr, QString>> parse(const QString &text);
EmojiMap emojis;
std::vector<QString> shortCodes;
+116 -90
View File
@@ -1,142 +1,168 @@
#include "providers/ffz/FfzEmotes.hpp"
#include <QJsonArray>
#include "common/NetworkRequest.hpp"
#include "debug/Log.hpp"
#include "messages/Image.hpp"
namespace chatterino {
namespace {
QString getEmoteLink(const QJsonObject &urls, const QString &emoteScale)
Url getEmoteLink(const QJsonObject &urls, const QString &emoteScale)
{
auto emote = urls.value(emoteScale);
if (emote.isUndefined()) {
return "";
return {""};
}
assert(emote.isString());
return "https:" + emote.toString();
return {"https:" + emote.toString()};
}
void fillInEmoteData(const QJsonObject &urls, const QString &code, const QString &tooltip,
EmoteData &emoteData)
void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, const QString &tooltip,
Emote &emoteData)
{
QString url1x = getEmoteLink(urls, "1");
QString url2x = getEmoteLink(urls, "2");
QString url3x = getEmoteLink(urls, "4");
auto url1x = getEmoteLink(urls, "1");
auto url2x = getEmoteLink(urls, "2");
auto url3x = getEmoteLink(urls, "4");
assert(!url1x.isEmpty());
emoteData.image1x = new Image(url1x, 1, code, tooltip);
if (!url2x.isEmpty()) {
emoteData.image2x = new Image(url2x, 0.5, code, tooltip);
}
if (!url3x.isEmpty()) {
emoteData.image3x = new Image(url3x, 0.25, code, tooltip);
}
//, code, tooltip
emoteData.name = name;
emoteData.images =
ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), Image::fromUrl(url3x, 0.25)};
emoteData.tooltip = {tooltip};
}
} // namespace
void FFZEmotes::loadGlobalEmotes()
AccessGuard<const EmoteCache<EmoteName>> FfzEmotes::accessGlobalEmotes() const
{
return this->globalEmotes_.accessConst();
}
boost::optional<EmotePtr> FfzEmotes::getEmote(const EmoteId &id)
{
auto cache = this->channelEmoteCache_.access();
auto it = cache->find(id);
if (it != cache->end()) {
auto shared = it->second.lock();
if (shared) {
return shared;
}
}
return boost::none;
}
boost::optional<EmotePtr> FfzEmotes::getGlobalEmote(const EmoteName &name)
{
return this->globalEmotes_.access()->get(name);
}
void FfzEmotes::loadGlobalEmotes()
{
QString url("https://api.frankerfacez.com/v1/set/global");
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([this](auto result) {
auto root = result.parseJson();
auto sets = root.value("sets").toObject();
std::vector<QString> codes;
for (const QJsonValue &set : sets) {
auto emoticons = set.toObject().value("emoticons").toArray();
for (const QJsonValue &emote : emoticons) {
QJsonObject object = emote.toObject();
QString code = object.value("name").toString();
int id = object.value("id").toInt();
QJsonObject urls = object.value("urls").toObject();
EmoteData emoteData;
fillInEmoteData(urls, code, code + "<br/>Global FFZ Emote", emoteData);
emoteData.pageLink =
QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
this->globalEmotes.insert(code, emoteData);
codes.push_back(code);
}
this->globalEmoteCodes = codes;
}
return true;
});
request.onSuccess(
[this](auto result) -> Outcome { return this->parseGlobalEmotes(result.parseJson()); });
request.execute();
}
void FFZEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> _map)
Outcome FfzEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot)
{
printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", qPrintable(channelName));
auto jsonSets = jsonRoot.value("sets").toObject();
auto emotes = this->globalEmotes_.access();
auto replacement = emotes->makeReplacment();
QString url("https://api.frankerfacez.com/v1/room/" + channelName);
for (auto jsonSet : jsonSets) {
auto jsonEmotes = jsonSet.toObject().value("emoticons").toArray();
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([this, channelName, _map](auto result) {
auto rootNode = result.parseJson();
auto map = _map.lock();
for (auto jsonEmoteValue : jsonEmotes) {
auto jsonEmote = jsonEmoteValue.toObject();
if (_map.expired()) {
return false;
auto name = EmoteName{jsonEmote.value("name").toString()};
auto id = EmoteId{jsonEmote.value("id").toString()};
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)};
replacement.add(name, emote);
}
}
map->clear();
return Success;
}
auto setsNode = rootNode.value("sets").toObject();
void FfzEmotes::loadChannelEmotes(const QString &channelName,
std::function<void(EmoteMap &&)> callback)
{
// printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", qPrintable(channelName));
std::vector<QString> codes;
for (const QJsonValue &setNode : setsNode) {
auto emotesNode = setNode.toObject().value("emoticons").toArray();
// QString url("https://api.frankerfacez.com/v1/room/" + channelName);
for (const QJsonValue &emoteNode : emotesNode) {
QJsonObject emoteObject = emoteNode.toObject();
// NetworkRequest request(url);
// request.setCaller(QThread::currentThread());
// request.setTimeout(3000);
// request.onSuccess([this, channelName, _map](auto result) -> Outcome {
// return this->parseChannelEmotes(result.parseJson());
//});
// margins
int id = emoteObject.value("id").toInt();
QString code = emoteObject.value("name").toString();
// request.execute();
}
QJsonObject urls = emoteObject.value("urls").toObject();
Outcome parseChannelEmotes(const QJsonObject &jsonRoot)
{
// auto rootNode = result.parseJson();
// auto map = _map.lock();
auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, &urls] {
EmoteData emoteData;
fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote", emoteData);
emoteData.pageLink =
QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
// if (_map.expired()) {
// return false;
//}
return emoteData;
});
// map->clear();
this->channelEmotes.insert(code, emote);
map->insert(code, emote);
codes.push_back(code);
}
// auto setsNode = rootNode.value("sets").toObject();
this->channelEmoteCodes[channelName] = codes;
}
// std::vector<QString> codes;
// for (const QJsonValue &setNode : setsNode) {
// auto emotesNode = setNode.toObject().value("emoticons").toArray();
return true;
});
// for (const QJsonValue &emoteNode : emotesNode) {
// QJsonObject emoteObject = emoteNode.toObject();
request.execute();
// // margins
// int id = emoteObject.value("id").toInt();
// QString code = emoteObject.value("name").toString();
// QJsonObject urls = emoteObject.value("urls").toObject();
// auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, &urls] {
// EmoteData emoteData;
// 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;
// });
// this->channelEmotes.insert(code, emote);
// map->insert(code, emote);
// codes.push_back(code);
// }
// this->channelEmoteCodes[channelName] = codes;
//}
return Success;
}
} // namespace chatterino
+22 -13
View File
@@ -1,27 +1,36 @@
#pragma once
#include "common/Emotemap.hpp"
#include "common/SimpleSignalVector.hpp"
#include "util/ConcurrentMap.hpp"
#include <memory>
#include <map>
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "messages/EmoteCache.hpp"
namespace chatterino {
class FFZEmotes
class FfzEmotes final : std::enable_shared_from_this<FfzEmotes>
{
public:
EmoteMap globalEmotes;
SimpleSignalVector<QString> globalEmoteCodes;
static constexpr const char *globalEmoteApiUrl = "https://api.frankerfacez.com/v1/set/global";
static constexpr const char *channelEmoteApiUrl = "https://api.betterttv.net/2/channels/";
EmoteMap channelEmotes;
std::map<QString, SimpleSignalVector<QString>> channelEmoteCodes;
public:
// FfzEmotes();
static std::shared_ptr<FfzEmotes> create();
AccessGuard<const EmoteCache<EmoteName>> accessGlobalEmotes() const;
boost::optional<EmotePtr> getGlobalEmote(const EmoteName &name);
boost::optional<EmotePtr> getEmote(const EmoteId &id);
void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> channelEmoteMap);
void loadChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback);
private:
ConcurrentMap<int, EmoteData> channelEmoteCache_;
protected:
Outcome parseGlobalEmotes(const QJsonObject &jsonRoot);
Outcome parseChannelEmotes(const QJsonObject &jsonRoot);
UniqueAccess<EmoteCache<EmoteName>> globalEmotes_;
UniqueAccess<WeakEmoteIdMap> channelEmoteCache_;
};
} // namespace chatterino
+2 -5
View File
@@ -54,12 +54,9 @@ void AbstractIrcServer::connect()
std::lock_guard<std::mutex> lock2(this->channelMutex);
for (std::weak_ptr<Channel> &weak : this->channels.values()) {
std::shared_ptr<Channel> chan = weak.lock();
if (!chan) {
continue;
if (auto channel = std::shared_ptr<Channel>(weak.lock())) {
this->readConnection_->sendRaw("JOIN #" + channel->getName());
}
this->readConnection_->sendRaw("JOIN #" + chan->name);
}
this->writeConnection_->open();
@@ -94,8 +94,6 @@ void IrcMessageHandler::handleRoomStateMessage(Communi::IrcMessage *message)
auto roomId = it.value().toString();
twitchChannel->setRoomId(roomId);
app->resources->loadChannelData(roomId);
}
// Room modes
+7 -6
View File
@@ -4,6 +4,7 @@
#include "debug/Log.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include <QJsonArray>
#include <cassert>
namespace chatterino {
@@ -36,32 +37,32 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback, cons
request.setCaller(caller);
request.makeAuthorizedV5(getDefaultClientID());
request.onSuccess([successCallback](auto result) {
request.onSuccess([successCallback](auto result) -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray()) {
Log("API Error while getting user id, users is not an array");
return false;
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 1) {
Log("API Error while getting user id, users array size is not 1");
return false;
return Failure;
}
if (!users[0].isObject()) {
Log("API Error while getting user id, first user is not an object");
return false;
return Failure;
}
auto firstUser = users[0].toObject();
auto id = firstUser.value("_id");
if (!id.isString()) {
Log("API Error: while getting user id, first user object `_id` key is not a "
"string");
return false;
return Failure;
}
successCallback(id.toString());
return true;
return Success;
});
request.execute();
+169 -22
View File
@@ -1,13 +1,45 @@
#include "providers/twitch/TwitchAccount.hpp"
#include <QThread>
#include "Application.hpp"
#include "common/NetworkRequest.hpp"
#include "debug/Log.hpp"
#include "providers/twitch/PartialTwitchUser.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include "singletons/Emotes.hpp"
#include "util/RapidjsonHelpers.hpp"
namespace chatterino {
namespace {
EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode)
{
auto cleanCode = dirtyEmoteCode.string;
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"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
auto it = emoteNameReplacements.find(dirtyEmoteCode.string);
if (it != emoteNameReplacements.end()) {
cleanCode = it.value();
}
cleanCode.replace("&lt;", "<");
cleanCode.replace("&gt;", ">");
return {cleanCode};
}
} // namespace
TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken,
const QString &oauthClient, const QString &userID)
: Account(ProviderId::Twitch)
@@ -78,20 +110,20 @@ void TwitchAccount::loadIgnores()
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject()) {
return false;
return Failure;
}
auto blocksIt = document.FindMember("blocks");
if (blocksIt == document.MemberEnd()) {
return false;
return Failure;
}
const auto &blocks = blocksIt->value;
if (!blocks.IsArray()) {
return false;
return Failure;
}
{
@@ -116,7 +148,7 @@ void TwitchAccount::loadIgnores()
}
}
return true;
return Success;
});
req.execute();
@@ -148,25 +180,25 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
return true;
});
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject()) {
onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user " + targetName);
return false;
return Failure;
}
auto userIt = document.FindMember("user");
if (userIt == document.MemberEnd()) {
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (missing user) " + targetName);
return false;
return Failure;
}
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser)) {
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (invalid user) " + targetName);
return false;
return Failure;
}
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
@@ -177,12 +209,12 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
existingUser.update(ignoredUser);
onFinished(IgnoreResult_AlreadyIgnored,
"User " + targetName + " is already ignored");
return false;
return Failure;
}
}
onFinished(IgnoreResult_Success, "Successfully ignored user " + targetName);
return true;
return Success;
});
req.execute();
@@ -217,7 +249,7 @@ void TwitchAccount::unignoreByID(
return true;
});
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
TwitchUser ignoredUser;
ignoredUser.id = targetUserID;
@@ -228,7 +260,7 @@ void TwitchAccount::unignoreByID(
}
onFinished(UnignoreResult_Success, "Successfully unignored user " + targetName);
return true;
return Success;
});
req.execute();
@@ -254,10 +286,10 @@ void TwitchAccount::checkFollow(const QString targetUserID,
return true;
});
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
onFinished(FollowResult_Following);
return true;
return Success;
});
req.execute();
@@ -274,10 +306,10 @@ void TwitchAccount::followUser(const QString userID, std::function<void()> succe
request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
// TODO: Properly check result of follow request
request.onSuccess([successCallback](auto result) {
request.onSuccess([successCallback](auto result) -> Outcome {
successCallback();
return true;
return Success;
});
request.execute();
@@ -301,10 +333,10 @@ void TwitchAccount::unfollowUser(const QString userID, std::function<void()> suc
return true;
});
request.onSuccess([successCallback](const auto &document) {
request.onSuccess([successCallback](const auto &document) -> Outcome {
successCallback();
return true;
return Success;
});
request.execute();
@@ -317,7 +349,7 @@ std::set<TwitchUser> TwitchAccount::getIgnores() const
return this->ignores_;
}
void TwitchAccount::loadEmotes(std::function<void(const rapidjson::Document &)> cb)
void TwitchAccount::loadEmotes()
{
Log("Loading Twitch emotes for user {}", this->getUserName());
@@ -346,11 +378,126 @@ void TwitchAccount::loadEmotes(std::function<void(const rapidjson::Document &)>
return true;
});
req.onSuccess([=](auto result) {
cb(result.parseRapidJson());
req.onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson());
return Success;
});
req.execute();
}
AccessGuard<const TwitchAccount::TwitchAccountEmoteData> TwitchAccount::accessEmotes() const
{
return this->emotes_.accessConst();
}
void TwitchAccount::parseEmotes(const rapidjson::Document &root)
{
auto emoteData = this->emotes_.access();
emoteData->emoteSets.clear();
emoteData->allEmoteNames.clear();
auto emoticonSets = root.FindMember("emoticon_sets");
if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject()) {
Log("No emoticon_sets in load emotes response");
return;
}
for (const auto &emoteSetJSON : emoticonSets->value.GetObject()) {
auto emoteSet = std::make_shared<EmoteSet>();
emoteSet->key = emoteSetJSON.name.GetString();
this->loadEmoteSetData(emoteSet);
for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) {
if (!emoteJSON.IsObject()) {
Log("Emote value was invalid");
return;
}
uint64_t idNumber;
if (!rj::getSafe(emoteJSON, "id", idNumber)) {
Log("No ID key found in Emote value");
return;
}
EmoteName code;
if (!rj::getSafe(emoteJSON, "code", code)) {
Log("No code key found in Emote value");
return;
}
auto id = EmoteId{QString::number(idNumber)};
auto cleanCode = cleanUpCode(code);
emoteSet->emotes.emplace_back(TwitchEmote{id, cleanCode});
emoteData->allEmoteNames.push_back(cleanCode);
auto emote = getApp()->emotes->twitch.getOrCreateEmote(id, code);
emoteData->emotes.emplace(code, emote);
}
emoteData->emoteSets.emplace_back(emoteSet);
}
};
void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
{
if (!emoteSet) {
Log("null emote set sent");
return;
}
auto staticSetIt = this->staticEmoteSets.find(emoteSet->key);
if (staticSetIt != this->staticEmoteSets.end()) {
const auto &staticSet = staticSetIt->second;
emoteSet->channelName = staticSet.channelName;
emoteSet->text = staticSet.text;
return;
}
NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
"/");
req.setUseQuickLoadCache(true);
req.onError([](int errorCode) -> bool {
Log("Error code {} while loading emote set data", errorCode);
return true;
});
req.onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson();
if (!root.IsObject()) {
return Failure;
}
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName)) {
return Failure;
}
if (!rj::getSafe(root, "type", type)) {
return Failure;
}
Log("Loaded twitch emote set data for {}!", emoteSet->key);
if (type == "sub") {
emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName);
} else {
emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName);
}
emoteSet->channelName = channelName;
return Success;
});
req.execute();
}
+32 -1
View File
@@ -1,6 +1,8 @@
#pragma once
#include "common/UniqueAccess.hpp"
#include "controllers/accounts/Account.hpp"
#include "messages/Emote.hpp"
#include "providers/twitch/TwitchUser.hpp"
#include <rapidjson/document.h>
@@ -33,6 +35,28 @@ enum FollowResult {
class TwitchAccount : public Account
{
public:
struct TwitchEmote {
EmoteId id;
EmoteName name;
};
struct EmoteSet {
QString key;
QString channelName;
QString text;
std::vector<TwitchEmote> emotes;
};
std::map<QString, EmoteSet> staticEmoteSets;
struct TwitchAccountEmoteData {
std::vector<std::shared_ptr<EmoteSet>> emoteSets;
std::vector<EmoteName> allEmoteNames;
EmoteMap emotes;
};
TwitchAccount(const QString &username, const QString &oauthToken_, const QString &oauthClient_,
const QString &_userID);
@@ -70,11 +94,15 @@ public:
std::set<TwitchUser> getIgnores() const;
void loadEmotes(std::function<void(const rapidjson::Document &)> cb);
void loadEmotes();
AccessGuard<const TwitchAccountEmoteData> accessEmotes() const;
QColor color;
private:
void parseEmotes(const rapidjson::Document &document);
void loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet);
QString oauthClient_;
QString oauthToken_;
QString userName_;
@@ -83,6 +111,9 @@ private:
mutable std::mutex ignoresMutex_;
std::set<TwitchUser> ignores_;
// std::map<UserId, TwitchAccountEmoteData> emotes;
UniqueAccess<TwitchAccountEmoteData> emotes_;
};
} // namespace chatterino
+6 -6
View File
@@ -16,23 +16,23 @@ void TwitchApi::findUserId(const QString user, std::function<void(QString)> succ
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(getDefaultClientID());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable {
request.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray()) {
Log("API Error while getting user id, users is not an array");
successCallback("");
return false;
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 1) {
Log("API Error while getting user id, users array size is not 1");
successCallback("");
return false;
return Failure;
}
if (!users[0].isObject()) {
Log("API Error while getting user id, first user is not an object");
successCallback("");
return false;
return Failure;
}
auto firstUser = users[0].toObject();
auto id = firstUser.value("_id");
@@ -40,10 +40,10 @@ void TwitchApi::findUserId(const QString user, std::function<void(QString)> succ
Log("API Error: while getting user id, first user object `_id` key is not a "
"string");
successCallback("");
return false;
return Failure;
}
successCallback(id.toString());
return true;
return Success;
});
request.execute();
+58
View File
@@ -0,0 +1,58 @@
#include "TwitchBadges.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include "common/NetworkRequest.hpp"
namespace chatterino {
TwitchBadges::TwitchBadges()
{
}
void TwitchBadges::initialize(Settings &settings, Paths &paths)
{
this->loadTwitchBadges();
}
void TwitchBadges::loadTwitchBadges()
{
static QString url("https://badges.twitch.tv/v1/badges/global/display?language=en");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) -> Outcome {
auto root = result.parseJson();
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();
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));
}
}
return Success;
});
req.execute();
}
} // namespace chatterino
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <QString>
#include <messages/Emote.hpp>
#include <unordered_map>
#include "util/QStringHash.hpp"
namespace chatterino {
class Settings;
class Paths;
class TwitchBadges
{
public:
TwitchBadges();
void initialize(Settings &settings, Paths &paths);
private:
void loadTwitchBadges();
std::unordered_map<QString, EmotePtr> badges;
};
} // namespace chatterino
+179 -45
View File
@@ -5,32 +5,34 @@
#include "controllers/accounts/AccountController.hpp"
#include "debug/Log.hpp"
#include "messages/Message.hpp"
#include "providers/bttv/LoadBttvChannelEmote.hpp"
#include "providers/twitch/PubsubClient.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include "providers/twitch/TwitchParseCheerEmotes.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Settings.hpp"
#include "util/PostToThread.hpp"
#include <IrcConnection>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include <QTimer>
namespace chatterino {
TwitchChannel::TwitchChannel(const QString &channelName)
: Channel(channelName, Channel::Type::Twitch)
, bttvEmotes_(new EmoteMap)
, ffzEmotes_(new EmoteMap)
TwitchChannel::TwitchChannel(const QString &name)
: Channel(name, Channel::Type::Twitch)
, subscriptionUrl_("https://www.twitch.tv/subs/" + name)
, channelUrl_("https://twitch.tv/" + name)
, popoutPlayerUrl_("https://player.twitch.tv/?channel=" + name)
, mod_(false)
{
Log("[TwitchChannel:{}] Opened", this->name);
Log("[TwitchChannel:{}] Opened", name);
this->refreshChannelEmotes();
// this->refreshChannelEmotes();
// this->refreshViewerList();
this->managedConnect(getApp()->accounts->twitch.currentUserChanged,
@@ -38,13 +40,17 @@ TwitchChannel::TwitchChannel(const QString &channelName)
// pubsub
this->userStateChanged.connect([=] { this->refreshPubsub(); });
this->roomIdChanged.connect([=] { this->refreshPubsub(); });
this->managedConnect(getApp()->accounts->twitch.currentUserChanged,
[=] { this->refreshPubsub(); });
this->refreshPubsub();
// room id loaded -> refresh live status
this->roomIdChanged.connect([this]() { this->refreshLiveStatus(); });
this->roomIdChanged.connect([this]() {
this->refreshPubsub();
this->refreshLiveStatus();
this->loadBadges();
this->loadCheerEmotes();
});
// timers
QObject::connect(&this->chattersListTimer_, &QTimer::timeout,
@@ -68,7 +74,7 @@ TwitchChannel::TwitchChannel(const QString &channelName)
bool TwitchChannel::isEmpty() const
{
return this->name.isEmpty();
return this->getName().isEmpty();
}
bool TwitchChannel::canSendMessage() const
@@ -78,12 +84,15 @@ bool TwitchChannel::canSendMessage() const
void TwitchChannel::refreshChannelEmotes()
{
auto app = getApp();
Log("[TwitchChannel:{}] Reloading channel emotes", this->name);
app->emotes->bttv.loadChannelEmotes(this->name, this->bttvEmotes_);
app->emotes->ffz.loadChannelEmotes(this->name, this->ffzEmotes_);
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)
@@ -99,7 +108,7 @@ void TwitchChannel::sendMessage(const QString &message)
return;
}
Log("[TwitchChannel:{}] Send message: {}", this->name, message);
Log("[TwitchChannel:{}] Send message: {}", this->getName(), message);
// Do last message processing
QString parsedMessage = app->emotes->emojis.replaceShortCodes(message);
@@ -119,7 +128,7 @@ void TwitchChannel::sendMessage(const QString &message)
}
bool messageSent = false;
this->sendMessageSignal.invoke(this->name, parsedMessage, messageSent);
this->sendMessageSignal.invoke(this->getName(), parsedMessage, messageSent);
if (messageSent) {
qDebug() << "sent";
@@ -145,7 +154,7 @@ bool TwitchChannel::isBroadcaster() const
{
auto app = getApp();
return this->name == app->accounts->twitch.getCurrent()->getUserName();
return this->getName() == app->accounts->twitch.getCurrent()->getUserName();
}
void TwitchChannel::addRecentChatter(const std::shared_ptr<Message> &message)
@@ -243,14 +252,32 @@ const AccessGuard<TwitchChannel::StreamStatus> TwitchChannel::accessStreamStatus
return this->streamStatus_.access();
}
const EmoteMap &TwitchChannel::getFfzEmotes() const
boost::optional<EmotePtr> TwitchChannel::getBttvEmote(const EmoteName &name) const
{
return *this->ffzEmotes_;
auto emotes = this->bttvEmotes_.access();
auto it = emotes->find(name);
if (it == emotes->end()) return boost::none;
return it->second;
}
const EmoteMap &TwitchChannel::getBttvEmotes() const
boost::optional<EmotePtr> TwitchChannel::getFfzEmote(const EmoteName &name) const
{
return *this->bttvEmotes_;
auto emotes = this->bttvEmotes_.access();
auto it = emotes->find(name);
if (it == emotes->end()) return boost::none;
return it->second;
}
AccessGuard<const EmoteMap> TwitchChannel::accessBttvEmotes() const
{
return this->bttvEmotes_.accessConst();
}
AccessGuard<const EmoteMap> TwitchChannel::accessFfzEmotes() const
{
return this->ffzEmotes_.accessConst();
}
const QString &TwitchChannel::getSubscriptionUrl()
@@ -289,12 +316,12 @@ void TwitchChannel::refreshLiveStatus()
auto roomID = this->getRoomId();
if (roomID.isEmpty()) {
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->name);
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->getName());
this->setLive(false);
return;
}
Log("[TwitchChannel:{}] Refreshing live status", this->name);
Log("[TwitchChannel:{}] Refreshing live status", this->getName());
QString url("https://api.twitch.tv/kraken/streams/" + roomID);
@@ -315,16 +342,16 @@ void TwitchChannel::refreshLiveStatus()
// request.execute();
}
bool TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
{
if (!document.IsObject()) {
Log("[TwitchChannel:refreshLiveStatus] root is not an object");
return false;
return Failure;
}
if (!document.HasMember("stream")) {
Log("[TwitchChannel:refreshLiveStatus] Missing stream in root");
return false;
return Failure;
}
const auto &stream = document["stream"];
@@ -332,21 +359,21 @@ bool TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
if (!stream.IsObject()) {
// Stream is offline (stream is most likely null)
this->setLive(false);
return false;
return Failure;
}
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 false;
return Failure;
}
const rapidjson::Value &streamChannel = stream["channel"];
if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) {
Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel");
return false;
return Failure;
}
// Stream is live
@@ -384,7 +411,7 @@ bool TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
// Signal all listeners that the stream status has been updated
this->liveStatusChanged.invoke();
return true;
return Success;
}
void TwitchChannel::loadRecentMessages()
@@ -396,24 +423,20 @@ void TwitchChannel::loadRecentMessages()
request.makeAuthorizedV5(getDefaultClientID());
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = this->weak_from_this()](auto result) {
// channel still exists?
request.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared) return false;
if (!shared) return Failure;
// parse json
return this->parseRecentMessages(result.parseJson());
});
request.execute();
}
bool TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
Outcome TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
{
QJsonArray jsonMessages = jsonRoot.value("messages").toArray();
if (jsonMessages.empty()) {
return false;
}
if (jsonMessages.empty()) return Failure;
std::vector<MessagePtr> messages;
@@ -434,7 +457,7 @@ bool TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
this->addMessagesAtStart(messages);
return true;
return Success;
}
void TwitchChannel::refreshPubsub()
@@ -460,13 +483,13 @@ void TwitchChannel::refreshViewerList()
}
// get viewer list
NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->name + "/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) {
request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome {
// channel still exists?
auto shared = weak.lock();
if (!shared) return false;
if (!shared) return Failure;
return this->parseViewerList(result.parseJson());
});
@@ -474,7 +497,7 @@ void TwitchChannel::refreshViewerList()
request.execute();
}
bool TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
Outcome TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
{
static QStringList categories = {"moderators", "staff", "admins", "global_mods", "viewers"};
@@ -487,7 +510,118 @@ bool TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
}
}
return true;
return Success;
}
void TwitchChannel::loadBadges()
{
auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" + this->getRoomId() +
"/display?language=en"};
NetworkRequest req(url.string);
req.setCaller(QThread::currentThread());
req.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared) return Failure;
auto badgeSets = this->badgeSets_.access();
auto jsonRoot = result.parseJson();
auto _ = jsonRoot["badge_sets"].toObject();
for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end(); jsonBadgeSet++) {
auto &versions = (*badgeSets)[jsonBadgeSet.key()];
auto _ = jsonBadgeSet->toObject()["versions"].toObject();
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()}});
versions.emplace(jsonVersion_.key(), emote);
};
}
return Success;
});
req.execute();
}
void TwitchChannel::loadCheerEmotes()
{
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());
for (auto &set : cheerEmoteSets) {
auto cheerEmoteSet = CheerEmoteSet();
cheerEmoteSet.regex = QRegularExpression("^" + set.prefix.toLower() + "([1-9][0-9]*)$");
for (auto &tier : set.tiers) {
CheerEmote cheerEmote;
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
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);
}
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;
});
request.execute();
}
boost::optional<EmotePtr> TwitchChannel::getTwitchBadge(const QString &set,
const QString &version) const
{
auto badgeSets = this->badgeSets_.access();
auto it = badgeSets->find(set);
if (it != badgeSets->end()) {
auto it2 = it->second.find(version);
if (it2 != it->second.end()) {
return it2->second;
}
}
return boost::none;
}
} // namespace chatterino
+34 -7
View File
@@ -6,12 +6,14 @@
#include "common/Common.hpp"
#include "common/MutexValue.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "singletons/Emotes.hpp"
#include "util/ConcurrentMap.hpp"
#include <pajlada/signals/signalholder.hpp>
#include <mutex>
#include <unordered_map>
namespace chatterino {
@@ -68,12 +70,16 @@ public:
void setRoomModes(const RoomModes &roomModes_);
const AccessGuard<StreamStatus> accessStreamStatus() const;
const EmoteMap &getFfzEmotes() const;
const EmoteMap &getBttvEmotes() const;
boost::optional<EmotePtr> getBttvEmote(const EmoteName &name) const;
boost::optional<EmotePtr> getFfzEmote(const EmoteName &name) const;
AccessGuard<const EmoteMap> accessBttvEmotes() const;
AccessGuard<const EmoteMap> accessFfzEmotes() const;
const QString &getSubscriptionUrl();
const QString &getChannelUrl();
const QString &getPopoutPlayerUrl();
boost::optional<EmotePtr> getTwitchBadge(const QString &set, const QString &version) const;
// Signals
pajlada::Signals::NoArgSignal roomIdChanged;
pajlada::Signals::NoArgSignal liveStatusChanged;
@@ -86,26 +92,43 @@ private:
QString localizedName;
};
struct CheerEmote {
// a Cheermote indicates one tier
QColor color;
int minBits;
EmotePtr animatedEmote;
EmotePtr staticEmote;
};
struct CheerEmoteSet {
QRegularExpression regex;
std::vector<CheerEmote> cheerEmotes;
};
explicit TwitchChannel(const QString &channelName);
// Methods
void refreshLiveStatus();
bool parseLiveStatus(const rapidjson::Document &document);
Outcome parseLiveStatus(const rapidjson::Document &document);
void refreshPubsub();
void refreshViewerList();
bool parseViewerList(const QJsonObject &jsonRoot);
Outcome parseViewerList(const QJsonObject &jsonRoot);
void loadRecentMessages();
bool parseRecentMessages(const QJsonObject &jsonRoot);
Outcome parseRecentMessages(const QJsonObject &jsonRoot);
void setLive(bool newLiveStatus);
void loadBadges();
void loadCheerEmotes();
// Twitch data
UniqueAccess<StreamStatus> streamStatus_;
UniqueAccess<UserState> userState_;
UniqueAccess<RoomModes> roomModes_;
const std::shared_ptr<EmoteMap> bttvEmotes_;
const std::shared_ptr<EmoteMap> ffzEmotes_;
UniqueAccess<EmoteMap> bttvEmotes_;
UniqueAccess<EmoteMap> ffzEmotes_;
const QString subscriptionUrl_;
const QString channelUrl_;
const QString popoutPlayerUrl_;
@@ -118,6 +141,10 @@ private:
UniqueAccess<QStringList> partedUsers_;
bool partedUsersMergeQueued_ = false;
// "subscribers": { "0": ... "3": ... "6": ...
UniqueAccess<std::map<QString, std::map<QString, EmotePtr>>> badgeSets_;
std::vector<CheerEmoteSet> cheerEmoteSets_;
// --
QByteArray messageSuffix_;
QString lastSentMessage_;
+36 -200
View File
@@ -6,228 +6,64 @@
#include "messages/Image.hpp"
#include "util/RapidjsonHelpers.hpp"
#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
namespace chatterino {
namespace {
QString getEmoteLink(const QString &id, const QString &emoteScale)
{
QString value = TWITCH_EMOTE_TEMPLATE;
value.detach();
return value.replace("{id}", id).replace("{scale}", emoteScale);
}
QString cleanUpCode(const QString &dirtyEmoteCode)
{
QString cleanCode = dirtyEmoteCode;
// clang-format off
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"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
// clang-format on
auto it = emoteNameReplacements.find(dirtyEmoteCode);
if (it != emoteNameReplacements.end()) {
cleanCode = it.value();
}
cleanCode.replace("&lt;", "<");
cleanCode.replace("&gt;", ">");
return cleanCode;
}
} // namespace
TwitchEmotes::TwitchEmotes()
{
{
EmoteSet emoteSet;
emoteSet.key = "19194";
emoteSet.text = "Twitch Prime Emotes";
this->staticEmoteSets[emoteSet.key] = std::move(emoteSet);
}
{
EmoteSet emoteSet;
emoteSet.key = "0";
emoteSet.text = "Twitch Global Emotes";
this->staticEmoteSets[emoteSet.key] = std::move(emoteSet);
}
}
// id is used for lookup
// emoteName is used for giving a name to the emote in case it doesn't exist
EmoteData TwitchEmotes::getEmoteById(const QString &id, const QString &emoteName)
EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name_)
{
QString _emoteName = emoteName;
_emoteName.replace("<", "&lt;");
_emoteName.replace(">", "&gt;");
// clang-format off
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"}, {"\\;-?\\)", ";)"},
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"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
// clang-format on
auto it = emoteNameReplacements.find(_emoteName);
if (it != emoteNameReplacements.end()) {
_emoteName = it.value();
auto name = name_.string;
name.detach();
// replace < >
name.replace("<", "&lt;");
name.replace(">", "&gt;");
// replace regexes
auto it = replacements.find(name);
if (it != replacements.end()) {
name = it.value();
}
return twitchEmoteFromCache_.getOrAdd(id, [&emoteName, &_emoteName, &id] {
EmoteData newEmoteData;
auto cleanCode = cleanUpCode(emoteName);
newEmoteData.image1x =
new Image(getEmoteLink(id, "1.0"), 1, emoteName, _emoteName + "<br/>Twitch Emote");
newEmoteData.image1x->setCopyString(cleanCode);
// search in cache or create new emote
auto cache = this->twitchEmotesCache_.access();
auto shared = (*cache)[id].lock();
newEmoteData.image2x =
new Image(getEmoteLink(id, "2.0"), .5, emoteName, _emoteName + "<br/>Twitch Emote");
newEmoteData.image2x->setCopyString(cleanCode);
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{}});
}
newEmoteData.image3x =
new Image(getEmoteLink(id, "3.0"), .25, emoteName, _emoteName + "<br/>Twitch Emote");
newEmoteData.image3x->setCopyString(cleanCode);
return newEmoteData;
});
return shared;
}
void TwitchEmotes::refresh(const std::shared_ptr<TwitchAccount> &user)
Url TwitchEmotes::getEmoteLink(const EmoteId &id, const QString &emoteScale)
{
const auto &roomID = user->getUserId();
TwitchAccountEmoteData &emoteData = this->emotes[roomID];
if (emoteData.filled) {
Log("Emotes are already loaded for room id {}", roomID);
return;
}
auto loadEmotes = [=, &emoteData](const rapidjson::Document &root) {
emoteData.emoteSets.clear();
emoteData.emoteCodes.clear();
auto emoticonSets = root.FindMember("emoticon_sets");
if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject()) {
Log("No emoticon_sets in load emotes response");
return;
}
for (const auto &emoteSetJSON : emoticonSets->value.GetObject()) {
auto emoteSet = std::make_shared<EmoteSet>();
emoteSet->key = emoteSetJSON.name.GetString();
this->loadSetData(emoteSet);
for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) {
if (!emoteJSON.IsObject()) {
Log("Emote value was invalid");
return;
}
QString id, code;
uint64_t idNumber;
if (!rj::getSafe(emoteJSON, "id", idNumber)) {
Log("No ID key found in Emote value");
return;
}
if (!rj::getSafe(emoteJSON, "code", code)) {
Log("No code key found in Emote value");
return;
}
id = QString::number(idNumber);
auto cleanCode = cleanUpCode(code);
emoteSet->emotes.emplace_back(id, cleanCode);
emoteData.emoteCodes.push_back(cleanCode);
EmoteData emote = this->getEmoteById(id, code);
emoteData.emotes.insert(code, emote);
}
emoteData.emoteSets.emplace_back(emoteSet);
}
emoteData.filled = true;
};
user->loadEmotes(loadEmotes);
return {
QString(TWITCH_EMOTE_TEMPLATE).replace("{id}", id.string).replace("{scale}", emoteScale)};
}
void TwitchEmotes::loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet)
AccessGuard<std::unordered_map<EmoteName, EmotePtr>> TwitchEmotes::accessAll()
{
if (!emoteSet) {
Log("null emote set sent");
return;
}
auto staticSetIt = this->staticEmoteSets.find(emoteSet->key);
if (staticSetIt != this->staticEmoteSets.end()) {
const auto &staticSet = staticSetIt->second;
emoteSet->channelName = staticSet.channelName;
emoteSet->text = staticSet.text;
return;
}
NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
"/");
req.setUseQuickLoadCache(true);
req.onError([](int errorCode) -> bool {
Log("Error code {} while loading emote set data", errorCode);
return true;
});
req.onSuccess([emoteSet](auto result) -> bool {
auto root = result.parseRapidJson();
if (!root.IsObject()) {
return false;
}
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName)) {
return false;
}
if (!rj::getSafe(root, "type", type)) {
return false;
}
Log("Loaded twitch emote set data for {}!", emoteSet->key);
if (type == "sub") {
emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName);
} else {
emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName);
}
emoteSet->channelName = channelName;
return true;
});
req.execute();
return this->twitchEmotes_.access();
}
} // namespace chatterino
+11 -50
View File
@@ -1,14 +1,17 @@
#pragma once
#include <QString>
#include <unordered_map>
#include "common/Emotemap.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "providers/twitch/EmoteValue.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "providers/twitch/TwitchEmotes.hpp"
#include "util/ConcurrentMap.hpp"
#include <map>
#include <QString>
#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
namespace chatterino {
@@ -17,55 +20,13 @@ class TwitchEmotes
public:
TwitchEmotes();
EmoteData getEmoteById(const QString &id, const QString &emoteName);
/// Twitch emotes
void refresh(const std::shared_ptr<TwitchAccount> &user);
struct TwitchEmote {
TwitchEmote(const QString &_id, const QString &_code)
: id(_id)
, code(_code)
{
}
// i.e. "403921"
QString id;
// i.e. "forsenE"
QString code;
};
struct EmoteSet {
QString key;
QString channelName;
QString text;
std::vector<TwitchEmote> emotes;
};
std::map<QString, EmoteSet> staticEmoteSets;
struct TwitchAccountEmoteData {
std::vector<std::shared_ptr<EmoteSet>> emoteSets;
std::vector<QString> emoteCodes;
EmoteMap emotes;
bool filled = false;
};
// Key is the user ID
std::map<QString, TwitchAccountEmoteData> emotes;
EmotePtr getOrCreateEmote(const EmoteId &id, const EmoteName &name);
Url getEmoteLink(const EmoteId &id, const QString &emoteScale);
AccessGuard<std::unordered_map<EmoteName, EmotePtr>> accessAll();
private:
void loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet);
// emote code
ConcurrentMap<QString, EmoteValue *> twitchEmotes_;
// emote id
ConcurrentMap<QString, EmoteData> twitchEmoteFromCache_;
UniqueAccess<std::unordered_map<EmoteName, EmotePtr>> twitchEmotes_;
UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<Emote>>> twitchEmotesCache_;
};
} // namespace chatterino
+259 -253
View File
@@ -16,6 +16,7 @@
#include <QApplication>
#include <QDebug>
#include <QMediaPlayer>
#include <boost/variant.hpp>
namespace chatterino {
@@ -83,7 +84,7 @@ MessagePtr TwitchMessageBuilder::build()
// PARSING
this->parseUsername();
if (this->userName == this->channel->name) {
if (this->userName == this->channel->getName()) {
this->senderIsBroadcaster = true;
}
@@ -143,14 +144,15 @@ MessagePtr TwitchMessageBuilder::build()
// highlights
this->parseHighlights(isPastMsg);
QString bits;
// QString bits;
auto iterator = this->tags.find("bits");
if (iterator != this->tags.end()) {
bits = iterator.value().toString();
this->hasBits_ = true;
// bits = iterator.value().toString();
}
// twitch emotes
std::vector<std::pair<long, EmoteData>> twitchEmotes;
std::vector<std::pair<int, EmotePtr>> twitchEmotes;
iterator = this->tags.find("emotes");
if (iterator != this->tags.end()) {
@@ -164,113 +166,117 @@ MessagePtr TwitchMessageBuilder::build()
[](const auto &a, const auto &b) { return a.first < b.first; });
}
auto currentTwitchEmote = twitchEmotes.begin();
// words
QStringList splits = this->originalMessage_.split(' ');
long int i = 0;
this->addWords(splits, twitchEmotes);
for (QString split : splits) {
MessageColor textColor =
this->action_ ? MessageColor(this->usernameColor_) : MessageColor(MessageColor::Text);
this->message_->searchText = this->userName + ": " + this->originalMessage_;
// twitch emote
return this->getMessage();
}
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) {
auto emoteImage = currentTwitchEmote->second;
this->emplace<EmoteElement>(emoteImage, MessageElement::TwitchEmote);
i += split.length() + 1;
currentTwitchEmote = std::next(currentTwitchEmote);
i += word.length() + 1;
currentTwitchEmote++;
continue;
}
// split words
std::vector<std::tuple<EmoteData, QString>> parsed;
// Parse emojis and take all non-emojis and put them in parsed as full text-words
app->emotes->emojis.parse(parsed, split);
for (const auto &tuple : parsed) {
const EmoteData &emoteData = std::get<0>(tuple);
if (!emoteData.isValid()) { // is text
QString string = std::get<1>(tuple);
if (!bits.isEmpty() && this->tryParseCheermote(string)) {
// This string was parsed as a cheermote
continue;
}
// TODO: Implement ignored emotes
// Format of ignored emotes:
// Emote name: "forsenPuke" - if string in ignoredEmotes
// Will match emote regardless of source (i.e. bttv, ffz)
// Emote source + name: "bttv:nyanPls"
if (this->tryAppendEmote(string)) {
// Successfully appended an emote
continue;
}
// Actually just text
QString linkString = this->matchLink(string);
Link link;
if (linkString.isEmpty()) {
link = Link();
} else {
if (app->settings->lowercaseLink) {
QRegularExpression httpRegex("\\bhttps?://",
QRegularExpression::CaseInsensitiveOption);
QRegularExpression ftpRegex("\\bftps?://",
QRegularExpression::CaseInsensitiveOption);
QRegularExpression getDomain("\\/\\/([^\\/]*)");
QString tempString = string;
if (!string.contains(httpRegex)) {
if (!string.contains(ftpRegex)) {
tempString.insert(0, "http://");
}
}
QString domain = getDomain.match(tempString).captured(1);
string.replace(domain, domain.toLower());
}
link = Link(Link::Url, linkString);
textColor = MessageColor(MessageColor::Link);
}
if (string.startsWith('@')) {
this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
FontStyle::ChatMediumBold) //
->setLink(link);
this->emplace<TextElement>(string, TextElement::NonBoldUsername, textColor) //
->setLink(link);
} else {
this->emplace<TextElement>(string, TextElement::Text, textColor) //
->setLink(link);
}
} else { // is emoji
this->emplace<EmoteElement>(emoteData, EmoteElement::EmojiAll);
}
for (auto &variant : getApp()->emotes->emojis.parse(word)) {
// if (std::holds_alternative<QString>(variant)) {
// this->addTextOrEmoji(std::get<1>(variant));
// } else {
// // this->addTextOrEmoji(std::get<EmotePtr>(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 < split.size(); j++) {
for (int j = 0; j < word.size(); j++) {
i++;
if (split.at(j).isHighSurrogate()) {
if (word.at(j).isHighSurrogate()) {
j++;
}
}
i++;
}
}
this->message_->searchText = this->userName + ": " + this->originalMessage_;
void TwitchMessageBuilder::addTextOrEmoji(EmotePtr emote)
{
this->emplace<EmoteElement>(emote, EmoteElement::EmojiAll);
}
return this->getMessage();
void TwitchMessageBuilder::addTextOrEmoji(const QString &string_)
{
auto string = QString(string_);
if (this->hasBits_ && this->tryParseCheermote(string)) {
// This string was parsed as a cheermote
return;
}
// TODO: Implement ignored emotes
// Format of ignored emotes:
// Emote name: "forsenPuke" - if string in ignoredEmotes
// Will match emote regardless of source (i.e. bttv, ffz)
// Emote source + name: "bttv:nyanPls"
if (this->tryAppendEmote({string})) {
// Successfully appended an emote
return;
}
// Actually just text
auto linkString = this->matchLink(string);
auto link = Link();
auto textColor =
this->action_ ? MessageColor(this->usernameColor_) : MessageColor(MessageColor::Text);
if (!linkString.isEmpty()) {
if (getApp()->settings->lowercaseLink) {
QRegularExpression httpRegex("\\bhttps?://", QRegularExpression::CaseInsensitiveOption);
QRegularExpression ftpRegex("\\bftps?://", QRegularExpression::CaseInsensitiveOption);
QRegularExpression getDomain("\\/\\/([^\\/]*)");
QString tempString = string;
if (!string.contains(httpRegex)) {
if (!string.contains(ftpRegex)) {
tempString.insert(0, "http://");
}
}
QString domain = getDomain.match(tempString).captured(1);
string.replace(domain, domain.toLower());
}
link = Link(Link::Url, linkString);
textColor = MessageColor(MessageColor::Link);
}
if (string.startsWith('@')) {
this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
FontStyle::ChatMediumBold) //
->setLink(link);
this->emplace<TextElement>(string, TextElement::NonBoldUsername,
textColor) //
->setLink(link);
} else {
this->emplace<TextElement>(string, TextElement::Text, textColor) //
->setLink(link);
}
}
void TwitchMessageBuilder::parseMessageID()
@@ -301,8 +307,8 @@ void TwitchMessageBuilder::parseRoomID()
void TwitchMessageBuilder::appendChannelName()
{
QString channelName("#" + this->channel->name);
Link link(Link::Url, this->channel->name + "\n" + this->messageID);
QString channelName("#" + this->channel->getName());
Link link(Link::Url, this->channel->getName() + "\n" + this->messageID);
this->emplace<TextElement>(channelName, MessageElement::ChannelName, MessageColor::System) //
->setLink(link);
@@ -531,71 +537,64 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessage,
const QString &emote,
std::vector<std::pair<long int, EmoteData>> &vec)
std::vector<std::pair<int, EmotePtr>> &vec)
{
auto app = getApp();
if (!emote.contains(':')) {
return;
}
QStringList parameters = emote.split(':');
auto parameters = emote.split(':');
if (parameters.length() < 2) {
return;
}
const auto &id = parameters.at(0);
auto id = EmoteId{parameters.at(0)};
QStringList occurences = parameters.at(1).split(',');
auto occurences = parameters.at(1).split(',');
for (QString occurence : occurences) {
QStringList coords = occurence.split('-');
auto coords = occurence.split('-');
if (coords.length() < 2) {
return;
}
int start = coords.at(0).toInt();
int end = coords.at(1).toInt();
auto start = coords.at(0).toInt();
auto end = coords.at(1).toInt();
if (start >= end || start < 0 || end > this->originalMessage_.length()) {
return;
}
QString name = this->originalMessage_.mid(start, end - start + 1);
auto name = EmoteName{this->originalMessage_.mid(start, end - start + 1)};
vec.push_back(
std::pair<long int, EmoteData>(start, app->emotes->twitch.getEmoteById(id, name)));
vec.push_back(std::make_pair(start, app->emotes->twitch.getOrCreateEmote(id, name)));
}
}
bool TwitchMessageBuilder::tryAppendEmote(QString &emoteString)
Outcome TwitchMessageBuilder::tryAppendEmote(const EmoteName &name)
{
auto app = getApp();
EmoteData emoteData;
auto flags = MessageElement::Flags::None;
auto emote = boost::optional<EmotePtr>{};
auto appendEmote = [&](MessageElement::Flags flags) {
this->emplace<EmoteElement>(emoteData, flags);
return true;
};
if (app->emotes->bttv.globalEmotes.tryGet(emoteString, emoteData)) {
// BTTV Global Emote
return appendEmote(MessageElement::BttvEmote);
} else if (this->twitchChannel != nullptr &&
this->twitchChannel->getBttvEmotes().tryGet(emoteString, emoteData)) {
// BTTV Channel Emote
return appendEmote(MessageElement::BttvEmote);
} else if (app->emotes->ffz.globalEmotes.tryGet(emoteString, emoteData)) {
// FFZ Global Emote
return appendEmote(MessageElement::FfzEmote);
} else if (this->twitchChannel != nullptr &&
this->twitchChannel->getFfzEmotes().tryGet(emoteString, emoteData)) {
// FFZ Channel Emote
return appendEmote(MessageElement::FfzEmote);
if ((emote = getApp()->emotes->bttv.getGlobalEmote(name))) {
flags = MessageElement::BttvEmote;
} 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))) {
flags = MessageElement::FfzEmote;
}
return false;
if (emote) {
this->emplace<EmoteElement>(emote.get(), flags);
return Success;
}
return Failure;
}
// fourtf: this is ugly
@@ -604,8 +603,6 @@ void TwitchMessageBuilder::appendTwitchBadges()
{
auto app = getApp();
const auto &channelResources = app->resources->channels[this->roomID_];
auto iterator = this->tags.find("badges");
if (iterator == this->tags.end()) {
@@ -621,68 +618,75 @@ void TwitchMessageBuilder::appendTwitchBadges()
}
if (badge.startsWith("bits/")) {
if (!app->resources->dynamicBadgesLoaded) {
// Do nothing
continue;
}
// if (!app->resources->dynamicBadgesLoaded) {
// // Do nothing
// continue;
// }
QString cheerAmountQS = badge.mid(5);
std::string versionKey = cheerAmountQS.toStdString();
QString tooltip = QString("Twitch cheer ") + cheerAmountQS;
QString cheerAmount = badge.mid(5);
QString tooltip = QString("Twitch cheer ") + cheerAmount;
// Try to fetch channel-specific bit badge
try {
const auto &badge = channelResources.badgeSets.at("bits").versions.at(versionKey);
this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
->setTooltip(tooltip);
continue;
if (twitchChannel)
if (const auto &badge =
this->twitchChannel->getTwitchBadge("bits", cheerAmount)) {
this->emplace<EmoteElement>(badge.get(), MessageElement::BadgeVanity)
->setTooltip(tooltip);
continue;
}
} catch (const std::out_of_range &) {
// Channel does not contain a special bit badge for this version
}
// Use default bit badge
try {
const auto &badge = app->resources->badgeSets.at("bits").versions.at(versionKey);
this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
->setTooltip(tooltip);
} catch (const std::out_of_range &) {
Log("No default bit badge for version {} found", versionKey);
continue;
}
// try {
// 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>(app->resources->badgeStaff,
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.staff),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Staff");
} else if (badge == "admin/1") {
this->emplace<ImageElement>(app->resources->badgeAdmin,
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.admin),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Admin");
} else if (badge == "global_mod/1") {
this->emplace<ImageElement>(app->resources->badgeGlobalModerator,
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>(app->resources->badgeModerator,
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>(app->resources->badgeTurbo,
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.turbo),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Turbo Subscriber");
} else if (badge == "broadcaster/1") {
this->emplace<ImageElement>(app->resources->badgeBroadcaster,
MessageElement::BadgeChannelAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.broadcaster),
MessageElement::BadgeChannelAuthority)
->setTooltip("Twitch Broadcaster");
} else if (badge == "premium/1") {
this->emplace<ImageElement>(app->resources->badgePremium, 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>(app->resources->badgeVerified,
MessageElement::BadgeVanity)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.verified),
MessageElement::BadgeVanity)
->setTooltip("Twitch Verified");
} break;
default: {
@@ -690,140 +694,142 @@ void TwitchMessageBuilder::appendTwitchBadges()
} break;
}
} else if (badge.startsWith("subscriber/")) {
if (channelResources.loaded == false) {
// qDebug() << "Channel resources are not loaded, can't add the subscriber badge";
continue;
}
// if (channelResources.loaded == false) {
// // qDebug() << "Channel resources are not loaded, can't add the
// subscriber
// // badge";
// continue;
// }
auto badgeSetIt = channelResources.badgeSets.find("subscriber");
if (badgeSetIt == channelResources.badgeSets.end()) {
// Fall back to default badge
this->emplace<ImageElement>(app->resources->badgeSubscriber,
MessageElement::BadgeSubscription)
->setTooltip("Twitch Subscriber");
continue;
}
// auto badgeSetIt = channelResources.badgeSets.find("subscriber");
// if (badgeSetIt == channelResources.badgeSets.end()) {
// // Fall back to default badge
// this->emplace<ImageElement>(app->resources->badgeSubscriber,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch Subscriber");
// continue;
//}
const auto &badgeSet = badgeSetIt->second;
// const auto &badgeSet = badgeSetIt->second;
std::string versionKey = badge.mid(11).toStdString();
// std::string versionKey = badge.mid(11).toStdString();
auto badgeVersionIt = badgeSet.versions.find(versionKey);
// auto badgeVersionIt = badgeSet.versions.find(versionKey);
if (badgeVersionIt == badgeSet.versions.end()) {
// Fall back to default badge
this->emplace<ImageElement>(app->resources->badgeSubscriber,
MessageElement::BadgeSubscription)
->setTooltip("Twitch Subscriber");
continue;
}
// if (badgeVersionIt == badgeSet.versions.end()) {
// // Fall back to default badge
// this->emplace<ImageElement>(app->resources->badgeSubscriber,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch Subscriber");
// continue;
//}
auto &badgeVersion = badgeVersionIt->second;
// auto &badgeVersion = badgeVersionIt->second;
this->emplace<ImageElement>(badgeVersion.badgeImage1x,
MessageElement::BadgeSubscription)
->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
// this->emplace<ImageElement>(badgeVersion.badgeImage1x,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
} else {
if (!app->resources->dynamicBadgesLoaded) {
// Do nothing
continue;
}
// if (!app->resources->dynamicBadgesLoaded) {
// // Do nothing
// continue;
//}
QStringList parts = badge.split('/');
// QStringList parts = badge.split('/');
if (parts.length() != 2) {
qDebug() << "Bad number of parts: " << parts.length() << " in " << parts;
continue;
}
// if (parts.length() != 2) {
// 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();
// std::string badgeSetKey = parts[0].toStdString();
// std::string versionKey = parts[1].toStdString();
try {
auto &badgeSet = app->resources->badgeSets.at(badgeSetKey);
// try {
// auto &badgeSet = app->resources->badgeSets.at(badgeSetKey);
try {
auto &badgeVersion = badgeSet.versions.at(versionKey);
// try {
// auto &badgeVersion = badgeSet.versions.at(versionKey);
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();
}
} catch (const std::exception &e) {
qDebug() << "No badge set with key" << badgeSetKey.c_str()
<< ". Exception: " << e.what();
}
// 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();
// }
//} catch (const std::exception &e) {
// qDebug() << "No badge set with key" << badgeSetKey.c_str()
// << ". Exception: " << e.what();
//}
}
}
}
void TwitchMessageBuilder::appendChatterinoBadges()
{
auto app = getApp();
// auto app = getApp();
auto &badges = app->resources->chatterinoBadges;
auto it = badges.find(this->userName.toStdString());
// auto &badges = app->resources->chatterinoBadges;
// auto it = badges.find(this->userName.toStdString());
if (it == badges.end()) {
return;
}
// if (it == badges.end()) {
// return;
// }
const auto badge = it->second;
// const auto badge = it->second;
this->emplace<ImageElement>(badge->image, MessageElement::BadgeChatterino)
->setTooltip(QString::fromStdString(badge->tooltip));
// this->emplace<ImageElement>(badge->image, MessageElement::BadgeChatterino)
// ->setTooltip(QString::fromStdString(badge->tooltip));
}
bool TwitchMessageBuilder::tryParseCheermote(const QString &string)
Outcome TwitchMessageBuilder::tryParseCheermote(const QString &string)
{
auto app = getApp();
// Try to parse custom cheermotes
const auto &channelResources = app->resources->channels[this->roomID_];
if (channelResources.loaded) {
for (const auto &cheermoteSet : channelResources.cheermoteSets) {
auto match = cheermoteSet.regex.match(string);
if (!match.hasMatch()) {
continue;
}
QString amount = match.captured(1);
bool ok = false;
int numBits = amount.toInt(&ok);
if (!ok) {
Log("Error parsing bit amount in tryParseCheermote");
return false;
}
// auto app = getApp();
//// Try to parse custom cheermotes
// const auto &channelResources = app->resources->channels[this->roomID_];
// if (channelResources.loaded) {
// for (const auto &cheermoteSet : channelResources.cheermoteSets) {
// auto match = cheermoteSet.regex.match(string);
// if (!match.hasMatch()) {
// continue;
// }
// QString amount = match.captured(1);
// bool ok = false;
// int numBits = amount.toInt(&ok);
// if (!ok) {
// Log("Error parsing bit amount in tryParseCheermote");
// return Failure;
// }
auto savedIt = cheermoteSet.cheermotes.end();
// auto savedIt = cheermoteSet.cheermotes.end();
// Fetch cheermote that matches our numBits
for (auto it = cheermoteSet.cheermotes.begin(); it != cheermoteSet.cheermotes.end();
++it) {
if (numBits >= it->minBits) {
savedIt = it;
} else {
break;
}
}
// // Fetch cheermote that matches our numBits
// for (auto it = cheermoteSet.cheermotes.begin(); it != cheermoteSet.cheermotes.end();
// ++it) {
// if (numBits >= it->minBits) {
// savedIt = it;
// } else {
// break;
// }
// }
if (savedIt == cheermoteSet.cheermotes.end()) {
Log("Error getting a cheermote from a cheermote set for the bit amount {}",
numBits);
return false;
}
// if (savedIt == cheermoteSet.cheermotes.end()) {
// Log("Error getting a cheermote from a cheermote set for the bit amount {}",
// numBits);
// return Failure;
// }
const auto &cheermote = *savedIt;
// const auto &cheermote = *savedIt;
this->emplace<EmoteElement>(cheermote.emoteDataAnimated, 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 true;
}
}
// return Success;
// }
//}
return false;
return Failure;
}
} // namespace chatterino
@@ -51,14 +51,20 @@ private:
void parseHighlights(bool isPastMsg);
void appendTwitchEmote(const Communi::IrcMessage *ircMessage, const QString &emote,
std::vector<std::pair<long, EmoteData>> &vec);
bool tryAppendEmote(QString &emoteString);
std::vector<std::pair<int, EmotePtr>> &vec);
Outcome tryAppendEmote(const EmoteName &name);
void addWords(const QStringList &words,
const std::vector<std::pair<int, EmotePtr>> &twitchEmotes);
void addTextOrEmoji(EmotePtr emote);
void addTextOrEmoji(const QString &value);
void appendTwitchBadges();
void appendChatterinoBadges();
bool tryParseCheermote(const QString &string);
Outcome tryParseCheermote(const QString &string);
QString roomID_;
bool hasBits_ = false;
QColor usernameColor_;
const QString originalMessage_;
@@ -0,0 +1,264 @@
#include "TwitchParseCheerEmotes.hpp"
#include <rapidjson/document.h>
#include <QString>
#include <vector>
namespace chatterino {
namespace {
template <typename Type>
inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.Is<Type>()) {
return false;
}
out = value.Get<Type>();
return true;
}
template <>
inline bool ReadValue<QString>(const rapidjson::Value &object, const char *key, QString &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.IsString()) {
return false;
}
out = value.GetString();
return true;
}
template <>
inline bool ReadValue<std::vector<QString>>(const rapidjson::Value &object, const char *key,
std::vector<QString> &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.IsArray()) {
return false;
}
for (const rapidjson::Value &innerValue : value.GetArray()) {
if (!innerValue.IsString()) {
return false;
}
out.emplace_back(innerValue.GetString());
}
return true;
}
// Parse a single cheermote set (or "action") from the twitch api
inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Value &action)
{
if (!action.IsObject()) {
return false;
}
if (!ReadValue(action, "prefix", set.prefix)) {
return false;
}
if (!ReadValue(action, "scales", set.scales)) {
return false;
}
if (!ReadValue(action, "backgrounds", set.backgrounds)) {
return false;
}
if (!ReadValue(action, "states", set.states)) {
return false;
}
if (!ReadValue(action, "type", set.type)) {
return false;
}
if (!ReadValue(action, "updated_at", set.updatedAt)) {
return false;
}
if (!ReadValue(action, "priority", set.priority)) {
return false;
}
// Tiers
if (!action.HasMember("tiers")) {
return false;
}
const auto &tiersValue = action["tiers"];
if (!tiersValue.IsArray()) {
return false;
}
for (const rapidjson::Value &tierValue : tiersValue.GetArray()) {
JSONCheermoteSet::CheermoteTier tier;
if (!tierValue.IsObject()) {
return false;
}
if (!ReadValue(tierValue, "min_bits", tier.minBits)) {
return false;
}
if (!ReadValue(tierValue, "id", tier.id)) {
return false;
}
if (!ReadValue(tierValue, "color", tier.color)) {
return false;
}
// Images
if (!tierValue.HasMember("images")) {
return false;
}
const auto &imagesValue = tierValue["images"];
if (!imagesValue.IsObject()) {
return false;
}
// Read images object
for (const auto &imageBackgroundValue : imagesValue.GetObject()) {
QString background = imageBackgroundValue.name.GetString();
bool backgroundExists = false;
for (const auto &bg : set.backgrounds) {
if (background == bg) {
backgroundExists = true;
break;
}
}
if (!backgroundExists) {
continue;
}
const rapidjson::Value &imageBackgroundStates = imageBackgroundValue.value;
if (!imageBackgroundStates.IsObject()) {
continue;
}
// Read each key which represents a background
for (const auto &imageBackgroundState : imageBackgroundStates.GetObject()) {
QString state = imageBackgroundState.name.GetString();
bool stateExists = false;
for (const auto &_state : set.states) {
if (state == _state) {
stateExists = true;
break;
}
}
if (!stateExists) {
continue;
}
const rapidjson::Value &imageScalesValue = imageBackgroundState.value;
if (!imageScalesValue.IsObject()) {
continue;
}
// Read each key which represents a scale
for (const auto &imageScaleValue : imageScalesValue.GetObject()) {
QString scale = imageScaleValue.name.GetString();
bool scaleExists = false;
for (const auto &_scale : set.scales) {
if (scale == _scale) {
scaleExists = true;
break;
}
}
if (!scaleExists) {
continue;
}
const rapidjson::Value &imageScaleURLValue = imageScaleValue.value;
if (!imageScaleURLValue.IsString()) {
continue;
}
QString url = imageScaleURLValue.GetString();
bool ok = false;
qreal scaleNumber = scale.toFloat(&ok);
if (!ok) {
continue;
}
qreal chatterinoScale = 1 / scaleNumber;
auto image = Image::fromUrl({url}, chatterinoScale);
// TODO(pajlada): Fill in name and tooltip
tier.images[background][state][scale] = image;
}
}
}
set.tiers.emplace_back(tier);
}
return true;
}
} // 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
std::vector<JSONCheermoteSet> ParseCheermoteSets(const rapidjson::Document &d)
{
std::vector<JSONCheermoteSet> sets;
if (!d.IsObject()) {
return sets;
}
if (!d.HasMember("actions")) {
return sets;
}
const auto &actionsValue = d["actions"];
if (!actionsValue.IsArray()) {
return sets;
}
for (const auto &action : actionsValue.GetArray()) {
JSONCheermoteSet set;
bool res = ParseSingleCheermoteSet(set, action);
if (res) {
sets.emplace_back(set);
}
}
return sets;
}
} // namespace chatterino
@@ -0,0 +1,36 @@
#pragma once
#include <rapidjson/document.h>
#include <QString>
#include <map>
#include <vector>
#include "messages/Image.hpp"
namespace chatterino {
struct JSONCheermoteSet {
QString prefix;
std::vector<QString> scales;
std::vector<QString> backgrounds;
std::vector<QString> states;
QString type;
QString updatedAt;
int priority;
struct CheermoteTier {
int minBits;
QString id;
QString color;
// Background State Scale
std::map<QString, std::map<QString, std::map<QString, ImagePtr>>> images;
};
std::vector<CheermoteTier> tiers;
};
std::vector<JSONCheermoteSet> ParseCheermoteSets(const rapidjson::Document &d);
} // namespace chatterino
+5 -9
View File
@@ -29,22 +29,18 @@ 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(Application &app)
void TwitchServer::initialize(Settings &settings, Paths &paths)
{
this->app = &app;
app.accounts->twitch.currentUserChanged.connect(
getApp()->accounts->twitch.currentUserChanged.connect(
[this]() { postToThread([this] { this->connect(); }); });
}
void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead, bool isWrite)
{
assert(this->app);
this->singleConnection_ = isRead == isWrite;
std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent();
@@ -236,7 +232,7 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString
lastMessage.push(now);
}
this->sendMessage(channel->name, message);
this->sendMessage(channel->getName(), message);
sent = true;
}
+5 -4
View File
@@ -12,15 +12,18 @@
namespace chatterino {
class Settings;
class Paths;
class PubSub;
class TwitchServer : public AbstractIrcServer, public Singleton
class TwitchServer final : public AbstractIrcServer, public Singleton
{
public:
TwitchServer();
virtual ~TwitchServer() override = default;
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
void forEachChannelAndSpecialChannels(std::function<void(ChannelPtr)> func);
@@ -51,8 +54,6 @@ protected:
private:
void onMessageSendRequested(TwitchChannel *channel, const QString &message, bool &sent);
Application *app = nullptr;
std::mutex lastMessageMutex_;
std::queue<std::chrono::steady_clock::time_point> lastMessagePleb_;
std::queue<std::chrono::steady_clock::time_point> lastMessageMod_;