mirror-chatterino2/src/twitch/twitchmessagebuilder.cpp

513 lines
19 KiB
C++
Raw Normal View History

2017-06-11 09:31:45 +02:00
#include "twitch/twitchmessagebuilder.hpp"
#include "colorscheme.hpp"
#include "emotemanager.hpp"
#include "ircmanager.hpp"
#include "resources.hpp"
#include "windowmanager.hpp"
2017-04-12 17:46:44 +02:00
2017-04-14 17:52:22 +02:00
using namespace chatterino::messages;
2017-04-12 17:46:44 +02:00
2017-04-14 17:52:22 +02:00
namespace chatterino {
namespace twitch {
2017-07-02 18:12:11 +02:00
TwitchMessageBuilder::TwitchMessageBuilder(Channel *_channel, Resources &_resources,
EmoteManager &_emoteManager,
WindowManager &_windowManager,
const Communi::IrcPrivateMessage *_ircMessage,
const messages::MessageParseArgs &_args)
: channel(_channel)
, resources(_resources)
, windowManager(_windowManager)
, colorScheme(this->windowManager.colorScheme)
, emoteManager(_emoteManager)
, ircMessage(_ircMessage)
, args(_args)
, tags(this->ircMessage->tags())
, usernameColor(this->colorScheme.SystemMessageColor)
2017-04-12 17:46:44 +02:00
{
}
2017-07-02 18:12:11 +02:00
SharedMessage TwitchMessageBuilder::parse()
2017-04-12 17:46:44 +02:00
{
// The timestamp is always appended to the builder
// Whether or not will be rendered is decided/checked later
2017-07-02 18:12:11 +02:00
this->appendTimestamp();
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
this->parseMessageID();
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
this->parseRoomID();
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
this->appendModerationButtons();
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
this->parseTwitchBadges();
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
if (this->args.includeChannelName) {
this->parseChannelName();
2017-04-12 17:46:44 +02:00
}
2017-07-02 18:12:11 +02:00
this->parseUsername();
2017-04-12 17:46:44 +02:00
// highlights
// TODO: implement this xD
// bits
QString bits = "";
2017-07-02 18:12:11 +02:00
auto iterator = this->tags.find("bits");
if (iterator != this->tags.end()) {
2017-04-12 17:46:44 +02:00
bits = iterator.value().toString();
}
// twitch emotes
std::vector<std::pair<long, EmoteData>> twitchEmotes;
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
iterator = this->tags.find("emotes");
if (iterator != this->tags.end()) {
QStringList emoteString = iterator.value().toString().split('/');
2017-04-12 17:46:44 +02:00
for (QString emote : emoteString) {
2017-07-02 18:12:11 +02:00
this->appendTwitchEmote(ircMessage, emote, twitchEmotes, emoteManager);
2017-04-12 17:46:44 +02:00
}
struct {
bool operator()(const std::pair<long, EmoteData> &lhs,
const std::pair<long, EmoteData> &rhs)
2017-04-12 17:46:44 +02:00
{
2017-07-02 18:12:11 +02:00
return lhs.first < rhs.first;
2017-04-12 17:46:44 +02:00
}
} customLess;
std::sort(twitchEmotes.begin(), twitchEmotes.end(), customLess);
}
auto currentTwitchEmote = twitchEmotes.begin();
// words
2017-07-02 18:12:11 +02:00
QColor textColor = ircMessage->isAction() ? this->usernameColor : this->colorScheme.Text;
2017-04-12 17:46:44 +02:00
2017-06-06 21:18:05 +02:00
const QString &originalMessage = ircMessage->content();
2017-07-02 18:12:11 +02:00
this->originalMessage = originalMessage;
2017-06-06 21:18:05 +02:00
QStringList splits = originalMessage.split(' ');
2017-04-12 17:46:44 +02:00
long int i = 0;
for (QString split : splits) {
// twitch emote
if (currentTwitchEmote != twitchEmotes.end() && currentTwitchEmote->first == i) {
2017-07-02 18:12:11 +02:00
this->appendWord(
Word(currentTwitchEmote->second.image, Word::TwitchEmoteImage,
currentTwitchEmote->second.image->getName(),
currentTwitchEmote->second.image->getName() + QString("\nTwitch Emote")));
2017-07-02 18:12:11 +02:00
this->appendWord(
Word(currentTwitchEmote->second.image->getName(), Word::TwitchEmoteText, textColor,
currentTwitchEmote->second.image->getName(),
currentTwitchEmote->second.image->getName() + QString("\nTwitch Emote")));
2017-04-12 17:46:44 +02:00
i += split.length() + 1;
currentTwitchEmote = std::next(currentTwitchEmote);
continue;
}
// split words
std::vector<std::tuple<EmoteData, QString>> parsed;
2017-04-12 17:46:44 +02:00
2017-07-02 17:37:17 +02:00
// Parse emojis and take all non-emojis and put them in parsed as full text-words
emoteManager.parseEmojis(parsed, split);
2017-04-12 17:46:44 +02:00
for (const auto &tuple : parsed) {
const EmoteData &emoteData = std::get<0>(tuple);
2017-04-12 17:46:44 +02:00
if (emoteData.image == nullptr) { // is text
2017-04-12 17:46:44 +02:00
QString string = std::get<1>(tuple);
static QRegularExpression cheerRegex("cheer[1-9][0-9]*");
// cheers
if (!bits.isEmpty() && string.length() >= 6 && cheerRegex.match(string).isValid()) {
auto cheer = string.mid(5).toInt();
QString color;
QColor bitsColor;
if (cheer >= 10000) {
color = "red";
bitsColor = QColor::fromHslF(0, 1, 0.5);
} else if (cheer >= 5000) {
color = "blue";
bitsColor = QColor::fromHslF(0.61, 1, 0.4);
} else if (cheer >= 1000) {
color = "green";
bitsColor = QColor::fromHslF(0.5, 1, 0.5);
} else if (cheer >= 100) {
color = "purple";
bitsColor = QColor::fromHslF(0.8, 1, 0.5);
} else {
color = "gray";
bitsColor = QColor::fromHslF(0.5f, 0.5f, 0.5f);
}
QString bitsLinkAnimated =
QString("http://static-cdn.jtvnw.net/bits/dark/animated/" + color + "/1");
QString bitsLink =
QString("http://static-cdn.jtvnw.net/bits/dark/static/" + color + "/1");
LazyLoadedImage *imageAnimated = emoteManager.miscImageCache.getOrAdd(
2017-07-02 18:12:11 +02:00
bitsLinkAnimated, [this, &bitsLinkAnimated] {
return new LazyLoadedImage(this->emoteManager, this->windowManager,
bitsLinkAnimated);
});
2017-07-02 18:12:11 +02:00
LazyLoadedImage *image =
emoteManager.miscImageCache.getOrAdd(bitsLink, [this, &bitsLink] {
2017-07-02 18:12:11 +02:00
return new LazyLoadedImage(this->emoteManager, this->windowManager,
bitsLink);
});
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
this->appendWord(Word(imageAnimated, Word::BitsAnimated, QString("cheer"),
QString("Twitch Cheer"),
Link(Link::Url, QString("https://blog.twitch.tv/"
"introducing-cheering-celebrate-"
"together-da62af41fac6"))));
this->appendWord(Word(image, Word::BitsStatic, QString("cheer"),
QString("Twitch Cheer"),
Link(Link::Url, QString("https://blog.twitch.tv/"
"introducing-cheering-celebrate-"
"together-da62af41fac6"))));
this->appendWord(Word(QString("x" + string.mid(5)), Word::BitsAmount, bitsColor,
QString(string.mid(5)), QString("Twitch Cheer"),
Link(Link::Url, QString("https://blog.twitch.tv/"
"introducing-cheering-celebrate-"
"together-da62af41fac6"))));
2017-04-12 17:46:44 +02:00
continue;
}
// bttv / ffz emotes
EmoteData emoteData;
2017-04-12 17:46:44 +02:00
// 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 (emoteManager.getBTTVEmotes().tryGet(string, emoteData) ||
this->channel->getBTTVChannelEmotes().tryGet(string, emoteData) ||
emoteManager.getFFZEmotes().tryGet(string, emoteData) ||
this->channel->getFFZChannelEmotes().tryGet(string, emoteData) ||
emoteManager.getChatterinoEmotes().tryGet(string, emoteData)) {
this->appendWord(Word(emoteData.image, Word::BttvEmoteImage,
emoteData.image->getName(), emoteData.image->getTooltip(),
Link(Link::Url, emoteData.image->getUrl())));
2017-04-12 17:46:44 +02:00
continue;
}
// actually just a word
2017-07-02 18:12:11 +02:00
QString link = this->matchLink(string);
2017-04-12 17:46:44 +02:00
2017-07-02 18:12:11 +02:00
this->appendWord(Word(string, Word::Text, textColor, string, QString(),
link.isEmpty() ? Link() : Link(Link::Url, link)));
2017-04-12 17:46:44 +02:00
} else { // is emoji
static QString emojiTooltip("Emoji");
this->appendWord(Word(emoteData.image, Word::EmojiImage, emoteData.image->getName(),
emojiTooltip));
Word(emoteData.image->getName(), Word::EmojiText, textColor,
emoteData.image->getName(), emojiTooltip);
2017-04-12 17:46:44 +02:00
}
}
i += split.length() + 1;
}
// TODO: Implement this xD
// if (!isReceivedWhisper &&
// AppSettings.HighlightIgnoredUsers.ContainsKey(Username))
// {
// HighlightTab = false;
// }
2017-07-02 18:12:11 +02:00
return this->build();
}
void TwitchMessageBuilder::parseMessageID()
{
auto iterator = this->tags.find("id");
if (iterator != this->tags.end()) {
this->messageID = iterator.value().toString();
}
2017-04-12 17:46:44 +02:00
}
2017-07-02 18:12:11 +02:00
void TwitchMessageBuilder::parseRoomID()
{
auto iterator = this->tags.find("room-id");
if (iterator != std::end(this->tags)) {
this->roomID = iterator.value().toString().toStdString();
if (this->channel->roomID.empty()) {
this->channel->roomID = this->roomID;
}
}
}
void TwitchMessageBuilder::parseChannelName()
{
QString channelName("#" + this->channel->getName());
this->appendWord(Word(channelName, Word::Misc, this->colorScheme.SystemMessageColor,
QString(channelName), QString(),
Link(Link::Url, this->channel->getName() + "\n" + this->messageID)));
}
void TwitchMessageBuilder::parseUsername()
{
auto iterator = this->tags.find("color");
if (iterator != this->tags.end()) {
this->usernameColor = QColor(iterator.value().toString());
}
// username
this->userName = ircMessage->nick();
if (this->userName.isEmpty()) {
this->userName = this->tags.value(QLatin1String("login")).toString();
}
QString displayName;
iterator = this->tags.find("display-name");
if (iterator == this->tags.end()) {
displayName = this->userName;
} else {
displayName = iterator.value().toString();
}
bool hasLocalizedName = QString::compare(displayName, ircMessage->account()) == 0;
QString userDisplayString =
displayName + (hasLocalizedName ? (" (" + ircMessage->account() + ")") : QString());
if (this->args.isSentWhisper) {
// TODO(pajlada): Re-implement
// userDisplayString += IrcManager::getInstance().getUser().getUserName();
}
if (this->args.isReceivedWhisper) {
// TODO(pajlada): Re-implement
// userDisplayString += " -> " + IrcManager::getInstance().getUser().getUserName();
}
if (!ircMessage->isAction()) {
userDisplayString += ": ";
}
this->appendWord(Word(userDisplayString, Word::Username, this->usernameColor, userDisplayString,
QString(), Link(Link::UserInfo, this->userName)));
}
void TwitchMessageBuilder::appendModerationButtons()
{
// mod buttons
static QString buttonBanTooltip("Ban user");
static QString buttonTimeoutTooltip("Timeout user");
2017-07-02 18:12:11 +02:00
this->appendWord(Word(this->resources.buttonBan, Word::ButtonBan, QString(), buttonBanTooltip,
Link(Link::UserBan, ircMessage->account())));
2017-07-02 18:12:11 +02:00
this->appendWord(Word(this->resources.buttonTimeout, Word::ButtonTimeout, QString(),
buttonTimeoutTooltip, Link(Link::UserTimeout, ircMessage->account())));
}
void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcPrivateMessage *ircMessage,
const QString &emote,
std::vector<std::pair<long int, EmoteData>> &vec,
EmoteManager &emoteManager)
{
if (!emote.contains(':')) {
return;
}
QStringList parameters = emote.split(':');
if (parameters.length() < 2) {
return;
}
long int id = std::stol(parameters.at(0).toStdString(), nullptr, 10);
QStringList occurences = parameters.at(1).split(',');
for (QString occurence : occurences) {
QStringList coords = occurence.split('-');
if (coords.length() < 2) {
return;
}
long int start = std::stol(coords.at(0).toStdString(), nullptr, 10);
long int end = std::stol(coords.at(1).toStdString(), nullptr, 10);
if (start >= end || start < 0 || end > ircMessage->content().length()) {
return;
}
QString name = ircMessage->content().mid(start, end - start + 1);
vec.push_back(
std::pair<long int, EmoteData>(start, emoteManager.getTwitchEmoteById(id, name)));
}
}
2017-07-02 18:12:11 +02:00
void TwitchMessageBuilder::parseTwitchBadges()
{
2017-07-02 18:12:11 +02:00
const auto &channelResources = this->resources.channels[this->roomID];
auto iterator = this->tags.find("badges");
if (iterator == this->tags.end()) {
// No badges in this message
return;
}
QStringList badges = iterator.value().toString().split(',');
for (QString badge : badges) {
if (badge.isEmpty()) {
continue;
}
if (badge.startsWith("bits/")) {
2017-07-02 18:12:11 +02:00
if (!this->resources.dynamicBadgesLoaded) {
2017-06-15 23:13:01 +02:00
// Do nothing
continue;
}
QString cheerAmountQS = badge.mid(5);
std::string versionKey = cheerAmountQS.toStdString();
2017-06-15 23:13:01 +02:00
2017-06-16 08:03:13 +02:00
try {
2017-07-02 18:12:11 +02:00
auto &badgeSet = this->resources.badgeSets.at("bits");
2017-06-16 08:03:13 +02:00
try {
auto &badgeVersion = badgeSet.versions.at(versionKey);
2017-06-16 08:03:13 +02:00
appendWord(
Word(badgeVersion.badgeImage1x, Word::BadgeVanity, QString(),
2017-06-16 08:03:13 +02:00
QString("Twitch " + QString::fromStdString(badgeVersion.title))));
} catch (const std::exception &e) {
qDebug() << "Exception caught:" << e.what()
<< "when trying to fetch badge version " << versionKey.c_str();
2017-06-16 08:03:13 +02:00
}
} catch (const std::exception &e) {
qDebug() << "No badge set with key"
<< "bits"
<< ". Exception: " << e.what();
2017-06-16 08:03:13 +02:00
}
} else if (badge == "staff/1") {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeStaff, Word::BadgeGlobalAuthority, QString(),
QString("Twitch Staff")));
} else if (badge == "admin/1") {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeAdmin, Word::BadgeGlobalAuthority, QString(),
QString("Twitch Admin")));
} else if (badge == "global_mod/1") {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeGlobalModerator, Word::BadgeGlobalAuthority,
QString(), QString("Global Moderator")));
} else if (badge == "moderator/1") {
// TODO: Implement custom FFZ moderator badge
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeModerator, Word::BadgeChannelAuthority, QString(),
QString("Channel Moderator"))); // custom badge
} else if (badge == "turbo/1") {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeTurbo, Word::BadgeVanity, QString(),
QString("Turbo Subscriber")));
} else if (badge == "broadcaster/1") {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeBroadcaster, Word::BadgeChannelAuthority,
QString(), QString("Channel Broadcaster")));
} else if (badge == "premium/1") {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgePremium, Word::BadgeVanity, QString(),
QString("Twitch Prime")));
} else if (badge.startsWith("partner/")) {
int index = badge.midRef(8).toInt();
switch (index) {
case 1: {
2017-07-02 18:12:11 +02:00
appendWord(Word(this->resources.badgeVerified, Word::BadgeVanity, QString(),
"Twitch Verified"));
} break;
default: {
printf("[TwitchMessageBuilder] Unhandled partner badge index: %d\n", index);
} break;
}
} else if (badge.startsWith("subscriber/")) {
2017-07-02 15:11:33 +02:00
if (channelResources.loaded == false) {
qDebug() << "Channel resources are not loaded, can't add the subscriber badge";
continue;
}
try {
const auto &badgeSet = channelResources.badgeSets.at("subscriber");
std::string versionKey = badge.mid(11).toStdString();
try {
auto &badgeVersion = badgeSet.versions.at(versionKey);
appendWord(
Word(badgeVersion.badgeImage1x, Word::Type::BadgeSubscription, QString(),
QString("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 channel badge set with key `subscriber`. Exception: " << e.what();
}
2017-07-02 15:11:33 +02:00
} else {
2017-07-02 18:12:11 +02:00
if (!this->resources.dynamicBadgesLoaded) {
// Do nothing
continue;
}
QStringList parts = badge.split('/');
if (parts.length() != 2) {
qDebug() << "Bad number of parts: " << parts.length() << " in " << parts;
continue;
}
Word::Type badgeType = Word::Type::BadgeVanity;
std::string badgeSetKey = parts[0].toStdString();
std::string versionKey = parts[1].toStdString();
try {
2017-07-02 18:12:11 +02:00
auto &badgeSet = this->resources.badgeSets.at(badgeSetKey);
try {
auto &badgeVersion = badgeSet.versions.at(versionKey);
appendWord(
Word(badgeVersion.badgeImage1x, badgeType, QString(),
QString("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();
}
}
}
}
2017-04-12 17:46:44 +02:00
// bool
// sortTwitchEmotes(const std::pair<long int, LazyLoadedImage *> &a,
// const std::pair<long int, LazyLoadedImage *> &b)
//{
// return a.first < b.first;
//}
} // namespace twitch
} // namespace chatterino