refactor: make a single MessageBuilder (#5548)

This commit is contained in:
pajlada
2024-08-24 12:18:27 +02:00
committed by GitHub
parent 5170085d7c
commit 175afa8b16
33 changed files with 2819 additions and 3014 deletions
File diff suppressed because it is too large Load Diff
+182 -7
View File
@@ -1,15 +1,25 @@
#pragma once
#include "common/Aliases.hpp"
#include "common/Outcome.hpp"
#include "messages/MessageColor.hpp"
#include "messages/MessageFlag.hpp"
#include "providers/twitch/pubsubmessages/LowTrustUsers.hpp"
#include <IrcMessage>
#include <QRegularExpression>
#include <QString>
#include <QTime>
#include <QVariant>
#include <ctime>
#include <memory>
#include <optional>
#include <unordered_map>
#include <utility>
namespace chatterino {
struct BanAction;
struct UnbanAction;
struct WarnAction;
@@ -24,6 +34,15 @@ class TextElement;
struct Emote;
using EmotePtr = std::shared_ptr<const Emote>;
class Channel;
class TwitchChannel;
class MessageThread;
class IgnorePhrase;
struct HelixVip;
using HelixModerator = HelixVip;
struct ChannelPointReward;
struct DeleteAction;
namespace linkparser {
struct Parsed;
} // namespace linkparser
@@ -67,10 +86,36 @@ struct MessageParseArgs {
QString channelPointRewardId = "";
};
struct TwitchEmoteOccurrence {
int start;
int end;
EmotePtr ptr;
EmoteName name;
bool operator==(const TwitchEmoteOccurrence &other) const
{
return std::tie(this->start, this->end, this->ptr, this->name) ==
std::tie(other.start, other.end, other.ptr, other.name);
}
};
class MessageBuilder
{
public:
/// Build a message without a base IRC message.
MessageBuilder();
/// Build a message based on an incoming IRC PRIVMSG
explicit MessageBuilder(Channel *_channel,
const Communi::IrcPrivateMessage *_ircMessage,
const MessageParseArgs &_args);
/// Build a message based on an incoming IRC message (e.g. notice)
explicit MessageBuilder(Channel *_channel,
const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args, QString content,
bool isAction);
MessageBuilder(SystemMessageTag, const QString &text,
const QTime &time = QTime::currentTime());
MessageBuilder(TimeoutMessageTag, const QString &timeoutUser,
@@ -106,7 +151,16 @@ public:
const QString &deletionLink, size_t imagesStillQueued = 0,
size_t secondsLeft = 0);
virtual ~MessageBuilder() = default;
MessageBuilder(const MessageBuilder &) = delete;
MessageBuilder(MessageBuilder &&) = delete;
MessageBuilder &operator=(const MessageBuilder &) = delete;
MessageBuilder &operator=(MessageBuilder &&) = delete;
~MessageBuilder() = default;
QString userName;
TwitchChannel *twitchChannel = nullptr;
Message *operator->();
Message &message();
@@ -117,10 +171,7 @@ public:
void addLink(const linkparser::Parsed &parsedLink, const QString &source);
template <typename T, typename... Args>
// clang-format off
// clang-format can be enabled once clang-format v11+ has been installed in CI
T *emplace(Args &&...args)
// clang-format on
{
static_assert(std::is_base_of<MessageElement, T>::value,
"T must extend MessageElement");
@@ -131,9 +182,70 @@ public:
return pointer;
}
[[nodiscard]] bool isIgnored() const;
bool isIgnoredReply() const;
void triggerHighlights();
MessagePtr build();
void setThread(std::shared_ptr<MessageThread> thread);
void setParent(MessagePtr parent);
void setMessageOffset(int offset);
void appendChannelPointRewardMessage(const ChannelPointReward &reward,
bool isMod, bool isBroadcaster);
static MessagePtr makeChannelPointRewardMessage(
const ChannelPointReward &reward, bool isMod, bool isBroadcaster);
/// Make a "CHANNEL_NAME has gone live!" message
static MessagePtr makeLiveMessage(const QString &channelName,
const QString &channelID,
MessageFlags extraFlags = {});
// Messages in normal chat for channel stuff
static MessagePtr makeOfflineSystemMessage(const QString &channelName,
const QString &channelID);
static MessagePtr makeHostingSystemMessage(const QString &channelName,
bool hostOn);
static MessagePtr makeDeletionMessageFromIRC(
const MessagePtr &originalMessage);
static MessagePtr makeDeletionMessageFromPubSub(const DeleteAction &action);
static MessagePtr makeListOfUsersMessage(QString prefix, QStringList users,
Channel *channel,
MessageFlags extraFlags = {});
static MessagePtr makeListOfUsersMessage(
QString prefix, const std::vector<HelixModerator> &users,
Channel *channel, MessageFlags extraFlags = {});
static MessagePtr buildHypeChatMessage(Communi::IrcPrivateMessage *message);
static std::pair<MessagePtr, MessagePtr> makeAutomodMessage(
const AutomodAction &action, const QString &channelName);
static MessagePtr makeAutomodInfoMessage(const AutomodInfoAction &action);
static std::pair<MessagePtr, MessagePtr> makeLowTrustUserMessage(
const PubSubLowTrustUsersMessage &action, const QString &channelName,
const TwitchChannel *twitchChannel);
static MessagePtr makeLowTrustUpdateMessage(
const PubSubLowTrustUsersMessage &action);
static std::unordered_map<QString, QString> parseBadgeInfoTag(
const QVariantMap &tags);
// Parses "badges" tag which contains a comma separated list of key-value elements
static std::vector<Badge> parseBadgeTag(const QVariantMap &tags);
static std::vector<TwitchEmoteOccurrence> parseTwitchEmotes(
const QVariantMap &tags, const QString &originalMessage,
int messageOffset);
static void processIgnorePhrases(
const std::vector<IgnorePhrase> &phrases, QString &originalMessage,
std::vector<TwitchEmoteOccurrence> &twitchEmotes);
protected:
virtual void addTextOrEmoji(EmotePtr emote);
virtual void addTextOrEmoji(const QString &value);
void addTextOrEmoji(EmotePtr emote);
void addTextOrEmoji(const QString &string_);
bool isEmpty() const;
MessageElement &back();
@@ -141,7 +253,6 @@ protected:
MessageColor textColor_ = MessageColor::Text;
private:
// Helper method that emplaces some text stylized as system text
// and then appends that text to the QString parameter "toUpdate".
// Returns the TextElement that was emplaced.
@@ -149,6 +260,70 @@ private:
QString &toUpdate);
std::shared_ptr<Message> message_;
void parse();
void parseUsernameColor();
void parseUsername();
void parseMessageID();
void parseRoomID();
// Parse & build thread information into the message
// Will read information from thread_ or from IRC tags
void parseThread();
// parseHighlights only updates the visual state of the message, but leaves the playing of alerts and sounds to the triggerHighlights function
void parseHighlights();
void appendChannelName();
void appendUsername();
Outcome tryAppendEmote(const EmoteName &name);
void addWords(const QStringList &words,
const std::vector<TwitchEmoteOccurrence> &twitchEmotes);
void appendTwitchBadges();
void appendChatterinoBadges();
void appendFfzBadges();
void appendSeventvBadges();
Outcome tryParseCheermote(const QString &string);
bool shouldAddModerationElements() const;
QString roomID_;
bool hasBits_ = false;
QString bits;
int bitsLeft{};
bool bitsStacked = false;
bool historicalMessage_ = false;
std::shared_ptr<MessageThread> thread_;
MessagePtr parent_;
/**
* Starting offset to be used on index-based operations on `originalMessage_`.
*
* For example:
* originalMessage_ = "there"
* messageOffset_ = 4
* (the irc message is "hey there")
*
* then the index 6 would resolve to 6 - 4 = 2 => 'e'
*/
int messageOffset_ = 0;
QString userId_;
bool senderIsBroadcaster{};
Channel *channel = nullptr;
const Communi::IrcMessage *ircMessage;
MessageParseArgs args;
const QVariantMap tags;
QString originalMessage_;
const bool action_{};
QColor usernameColor_ = {153, 153, 153};
bool highlightAlert_ = false;
bool highlightSound_ = false;
std::optional<QUrl> highlightSoundCustomUrl_{};
};
} // namespace chatterino
-294
View File
@@ -1,294 +0,0 @@
#include "messages/SharedMessageBuilder.hpp"
#include "Application.hpp"
#include "common/QLogging.hpp"
#include "controllers/highlights/HighlightController.hpp"
#include "controllers/ignores/IgnoreController.hpp"
#include "controllers/ignores/IgnorePhrase.hpp"
#include "controllers/nicknames/Nickname.hpp"
#include "controllers/sound/ISoundController.hpp"
#include "messages/Message.hpp"
#include "messages/MessageElement.hpp"
#include "providers/twitch/TwitchBadge.hpp"
#include "singletons/Settings.hpp"
#include "singletons/StreamerMode.hpp"
#include "singletons/WindowManager.hpp"
#include "util/Helpers.hpp"
#include <QFileInfo>
#include <optional>
namespace {
using namespace chatterino;
/**
* Gets the default sound url if the user set one,
* or the chatterino default ping sound if no url is set.
*/
QUrl getFallbackHighlightSound()
{
QString path = getSettings()->pathHighlightSound;
bool fileExists =
!path.isEmpty() && QFileInfo::exists(path) && QFileInfo(path).isFile();
if (fileExists)
{
return QUrl::fromLocalFile(path);
}
return QUrl("qrc:/sounds/ping2.wav");
}
} // namespace
namespace chatterino {
SharedMessageBuilder::SharedMessageBuilder(
Channel *_channel, const Communi::IrcPrivateMessage *_ircMessage,
const MessageParseArgs &_args)
: channel(_channel)
, ircMessage(_ircMessage)
, args(_args)
, tags(this->ircMessage->tags())
, originalMessage_(_ircMessage->content())
, action_(_ircMessage->isAction())
{
}
SharedMessageBuilder::SharedMessageBuilder(
Channel *_channel, const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args, QString content, bool isAction)
: channel(_channel)
, ircMessage(_ircMessage)
, args(_args)
, tags(this->ircMessage->tags())
, originalMessage_(content)
, action_(isAction)
{
}
void SharedMessageBuilder::parse()
{
this->parseUsernameColor();
if (this->action_)
{
this->textColor_ = this->usernameColor_;
this->message().flags.set(MessageFlag::Action);
}
this->parseUsername();
this->message().flags.set(MessageFlag::Collapsed);
}
// "foo/bar/baz,tri/hard" can be a valid badge-info tag
// In that case, valid map content should be 'split by slash' only once:
// {"foo": "bar/baz", "tri": "hard"}
std::pair<QString, QString> SharedMessageBuilder::slashKeyValue(
const QString &kvStr)
{
return {
// part before first slash (index 0 of section)
kvStr.section('/', 0, 0),
// part after first slash (index 1 of section)
kvStr.section('/', 1, -1),
};
}
std::vector<Badge> SharedMessageBuilder::parseBadgeTag(const QVariantMap &tags)
{
std::vector<Badge> b;
auto badgesIt = tags.constFind("badges");
if (badgesIt == tags.end())
{
return b;
}
auto badges = badgesIt.value().toString().split(',', Qt::SkipEmptyParts);
for (const QString &badge : badges)
{
if (!badge.contains('/'))
{
continue;
}
auto pair = SharedMessageBuilder::slashKeyValue(badge);
b.emplace_back(Badge{pair.first, pair.second});
}
return b;
}
bool SharedMessageBuilder::isIgnored() const
{
return isIgnoredMessage({
/*.message = */ this->originalMessage_,
});
}
void SharedMessageBuilder::parseUsernameColor()
{
if (getSettings()->colorizeNicknames)
{
this->usernameColor_ = getRandomColor(this->ircMessage->nick());
}
}
void SharedMessageBuilder::parseUsername()
{
// username
this->userName = this->ircMessage->nick();
this->message().loginName = this->userName;
}
void SharedMessageBuilder::parseHighlights()
{
if (getSettings()->isBlacklistedUser(this->message().loginName))
{
// Do nothing. We ignore highlights from this user.
return;
}
auto badges = SharedMessageBuilder::parseBadgeTag(this->tags);
auto [highlighted, highlightResult] = getApp()->getHighlights()->check(
this->args, badges, this->message().loginName, this->originalMessage_,
this->message().flags);
if (!highlighted)
{
return;
}
// This message triggered one or more highlights, act upon the highlight result
this->message().flags.set(MessageFlag::Highlighted);
this->highlightAlert_ = highlightResult.alert;
this->highlightSound_ = highlightResult.playSound;
this->highlightSoundCustomUrl_ = highlightResult.customSoundUrl;
this->message().highlightColor = highlightResult.color;
if (highlightResult.showInMentions)
{
this->message().flags.set(MessageFlag::ShowInMentions);
}
}
void SharedMessageBuilder::appendChannelName()
{
QString channelName("#" + this->channel->getName());
Link link(Link::JumpToChannel, this->channel->getName());
this->emplace<TextElement>(channelName, MessageElementFlag::ChannelName,
MessageColor::System)
->setLink(link);
}
void SharedMessageBuilder::triggerHighlights()
{
SharedMessageBuilder::triggerHighlights(
this->channel->getName(), this->highlightSound_,
this->highlightSoundCustomUrl_, this->highlightAlert_);
}
void SharedMessageBuilder::triggerHighlights(
const QString &channelName, bool playSound,
const std::optional<QUrl> &customSoundUrl, bool windowAlert)
{
if (getApp()->getStreamerMode()->isEnabled() &&
getSettings()->streamerModeMuteMentions)
{
// We are in streamer mode with muting mention sounds enabled. Do nothing.
return;
}
if (getSettings()->isMutedChannel(channelName))
{
// Do nothing. Pings are muted in this channel.
return;
}
const bool hasFocus = (QApplication::focusWidget() != nullptr);
const bool resolveFocus =
!hasFocus || getSettings()->highlightAlwaysPlaySound;
if (playSound && resolveFocus)
{
// TODO(C++23): optional or_else
QUrl soundUrl;
if (customSoundUrl)
{
soundUrl = *customSoundUrl;
}
else
{
soundUrl = getFallbackHighlightSound();
}
getApp()->getSound()->play(soundUrl);
}
if (windowAlert)
{
getApp()->getWindows()->sendAlert();
}
}
QString SharedMessageBuilder::stylizeUsername(const QString &username,
const Message &message)
{
const QString &localizedName = message.localizedName;
bool hasLocalizedName = !localizedName.isEmpty();
// The full string that will be rendered in the chat widget
QString usernameText;
switch (getSettings()->usernameDisplayMode.getValue())
{
case UsernameDisplayMode::Username: {
usernameText = username;
}
break;
case UsernameDisplayMode::LocalizedName: {
if (hasLocalizedName)
{
usernameText = localizedName;
}
else
{
usernameText = username;
}
}
break;
default:
case UsernameDisplayMode::UsernameAndLocalizedName: {
if (hasLocalizedName)
{
usernameText = username + "(" + localizedName + ")";
}
else
{
usernameText = username;
}
}
break;
}
if (auto nicknameText = getSettings()->matchNickname(usernameText))
{
usernameText = *nicknameText;
}
return usernameText;
}
} // namespace chatterino
-84
View File
@@ -1,84 +0,0 @@
#pragma once
#include "common/Aliases.hpp"
#include "common/Outcome.hpp"
#include "messages/MessageBuilder.hpp"
#include <IrcMessage>
#include <QColor>
#include <QUrl>
#include <optional>
namespace chatterino {
class Badge;
class Channel;
class SharedMessageBuilder : public MessageBuilder
{
public:
SharedMessageBuilder() = delete;
explicit SharedMessageBuilder(Channel *_channel,
const Communi::IrcPrivateMessage *_ircMessage,
const MessageParseArgs &_args);
explicit SharedMessageBuilder(Channel *_channel,
const Communi::IrcMessage *_ircMessage,
const MessageParseArgs &_args,
QString content, bool isAction);
QString userName;
[[nodiscard]] virtual bool isIgnored() const;
// triggerHighlights triggers any alerts or sounds parsed by parseHighlights
virtual void triggerHighlights();
virtual MessagePtr build() = 0;
static std::pair<QString, QString> slashKeyValue(const QString &kvStr);
// Parses "badges" tag which contains a comma separated list of key-value elements
static std::vector<Badge> parseBadgeTag(const QVariantMap &tags);
static QString stylizeUsername(const QString &username,
const Message &message);
protected:
virtual void parse();
virtual void parseUsernameColor();
virtual void parseUsername();
virtual Outcome tryAppendEmote(const EmoteName &name)
{
(void)name;
return Failure;
}
// parseHighlights only updates the visual state of the message, but leaves the playing of alerts and sounds to the triggerHighlights function
virtual void parseHighlights();
static void triggerHighlights(const QString &channelName, bool playSound,
const std::optional<QUrl> &customSoundUrl,
bool windowAlert);
void appendChannelName();
Channel *channel;
const Communi::IrcMessage *ircMessage;
MessageParseArgs args;
const QVariantMap tags;
QString originalMessage_;
const bool action_{};
QColor usernameColor_ = {153, 153, 153};
bool highlightAlert_ = false;
bool highlightSound_ = false;
std::optional<QUrl> highlightSoundCustomUrl_{};
};
} // namespace chatterino