This commit is contained in:
nerix 2024-10-27 13:01:07 +01:00 committed by GitHub
commit a62b986fbd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 565 additions and 731 deletions

View file

@ -114,6 +114,7 @@
- Dev: Refactored static `MessageBuilder` helpers to standalone functions. (#5652)
- Dev: Decoupled reply parsing from `MessageBuilder`. (#5660, #5668)
- Dev: Refactored IRC message building. (#5663)
- Dev: Unified parsing of historic and live IRC messages. (#5678)
## 2.5.1

View file

@ -39,6 +39,7 @@ set(SOURCE_FILES
common/WindowDescriptors.cpp
common/WindowDescriptors.hpp
common/enums/MessageContext.hpp
common/enums/MessageOverflow.hpp
common/network/NetworkCommon.cpp
@ -281,6 +282,9 @@ set(SOURCE_FILES
messages/MessageElement.cpp
messages/MessageElement.hpp
messages/MessageFlag.hpp
messages/MessageSimilarity.cpp
messages/MessageSimilarity.hpp
messages/MessageSink.hpp
messages/MessageThread.cpp
messages/MessageThread.hpp
@ -526,6 +530,8 @@ set(SOURCE_FILES
util/Twitch.hpp
util/TypeName.hpp
util/Variant.hpp
util/VectorMessageSink.cpp
util/VectorMessageSink.hpp
util/WidgetHelpers.cpp
util/WidgetHelpers.hpp
util/WindowsHelper.cpp

View file

@ -3,7 +3,9 @@
#include "Application.hpp"
#include "messages/Message.hpp"
#include "messages/MessageBuilder.hpp"
#include "messages/MessageSimilarity.hpp"
#include "providers/twitch/IrcMessageHandler.hpp"
#include "providers/twitch/TwitchIrcServer.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Logging.hpp"
#include "singletons/Settings.hpp"
@ -121,10 +123,10 @@ void Channel::addSystemMessage(const QString &contents)
this->addMessage(msg, MessageContext::Original);
}
void Channel::addOrReplaceTimeout(MessagePtr message)
void Channel::addOrReplaceTimeout(MessagePtr message, QTime now)
{
addOrReplaceChannelTimeout(
this->getMessageSnapshot(), std::move(message), QTime::currentTime(),
this->getMessageSnapshot(), std::move(message), now,
[this](auto /*idx*/, auto msg, auto replacement) {
this->replaceMessage(msg, replacement);
},
@ -287,10 +289,15 @@ void Channel::clearMessages()
}
MessagePtr Channel::findMessage(QString messageID)
{
return this->findMessageByID(messageID);
}
MessagePtr Channel::findMessageByID(QStringView messageID)
{
MessagePtr res;
if (auto msg = this->messages_.rfind([&messageID](const MessagePtr &msg) {
if (auto msg = this->messages_.rfind([messageID](const MessagePtr &msg) {
return msg->id == messageID;
});
msg)
@ -301,6 +308,19 @@ MessagePtr Channel::findMessage(QString messageID)
return res;
}
void Channel::applySimilarityFilters(const MessagePtr &message) const
{
setSimilarityFlags(message, this->messages_.getSnapshot());
}
MessageSinkTraits Channel::sinkTraits() const
{
return {
MessageSinkTrait::AddMentionsToGlobalChannel,
MessageSinkTrait::RequiresKnownChannelPointReward,
};
}
bool Channel::canSendMessage() const
{
return false;

View file

@ -1,8 +1,10 @@
#pragma once
#include "common/enums/MessageContext.hpp"
#include "controllers/completion/TabCompletionModel.hpp"
#include "messages/LimitedQueue.hpp"
#include "messages/MessageFlag.hpp"
#include "messages/MessageSink.hpp"
#include <magic_enum/magic_enum.hpp>
#include <pajlada/signals/signal.hpp>
@ -26,15 +28,7 @@ enum class TimeoutStackStyle : int {
Default = DontStackBeyondUserMessage,
};
/// Context of the message being added to a channel
enum class MessageContext {
/// This message is the original
Original,
/// This message is a repost of a message that has already been added in a channel
Repost,
};
class Channel : public std::enable_shared_from_this<Channel>
class Channel : public std::enable_shared_from_this<Channel>, public MessageSink
{
public:
// This is for Lua. See scripts/make_luals_meta.py
@ -55,7 +49,7 @@ public:
};
explicit Channel(const QString &name, Type type);
virtual ~Channel();
~Channel() override;
// SIGNALS
pajlada::Signals::Signal<const QString &, const QString &, bool &>
@ -85,8 +79,9 @@ public:
// overridingFlags can be filled in with flags that should be used instead
// of the message's flags. This is useful in case a flag is specific to a
// type of split
void addMessage(MessagePtr message, MessageContext context,
std::optional<MessageFlags> overridingFlags = std::nullopt);
void addMessage(
MessagePtr message, MessageContext context,
std::optional<MessageFlags> overridingFlags = std::nullopt) final;
void addMessagesAtStart(const std::vector<MessagePtr> &messages_);
void addSystemMessage(const QString &contents);
@ -94,8 +89,8 @@ public:
/// Inserts the given messages in order by Message::serverReceivedTime.
void fillInMissingMessages(const std::vector<MessagePtr> &messages);
void addOrReplaceTimeout(MessagePtr message);
void disableAllMessages();
void addOrReplaceTimeout(MessagePtr message, QTime now) final;
void disableAllMessages() final;
void replaceMessage(MessagePtr message, MessagePtr replacement);
void replaceMessage(size_t index, MessagePtr replacement);
void deleteMessage(QString messageID);
@ -104,9 +99,14 @@ public:
void clearMessages();
MessagePtr findMessage(QString messageID);
MessagePtr findMessageByID(QStringView messageID) final;
bool hasMessages() const;
void applySimilarityFilters(const MessagePtr &message) const final;
MessageSinkTraits sinkTraits() const final;
// CHANNEL INFO
virtual bool canSendMessage() const;
virtual bool isWritable() const; // whether split input will be usable

View file

@ -0,0 +1,13 @@
#pragma once
namespace chatterino {
/// Context of the message being added to a channel
enum class MessageContext {
/// This message is the original
Original,
/// This message is a repost of a message that has already been added in a channel
Repost,
};
} // namespace chatterino

View file

@ -0,0 +1,51 @@
#include "messages/MessageSimilarity.hpp"
#include <algorithm>
#include <vector>
namespace chatterino::similarity::detail {
float relativeSimilarity(QStringView str1, QStringView str2)
{
using SizeType = QStringView::size_type;
// Longest Common Substring Problem
std::vector<std::vector<int>> tree(str1.size(),
std::vector<int>(str2.size(), 0));
int z = 0;
for (SizeType i = 0; i < str1.size(); ++i)
{
for (SizeType j = 0; j < str2.size(); ++j)
{
if (str1[i] == str2[j])
{
if (i == 0 || j == 0)
{
tree[i][j] = 1;
}
else
{
tree[i][j] = tree[i - 1][j - 1] + 1;
}
z = std::max(tree[i][j], z);
}
else
{
tree[i][j] = 0;
}
}
}
// ensure that no div by 0
if (z == 0)
{
return 0.F;
}
auto div = std::max<>({static_cast<SizeType>(1), str1.size(), str2.size()});
return float(z) / float(div);
}
} // namespace chatterino::similarity::detail

View file

@ -0,0 +1,73 @@
#pragma once
#include "Application.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "messages/Message.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "singletons/Settings.hpp"
#include <ranges>
namespace chatterino::similarity::detail {
float relativeSimilarity(QStringView str1, QStringView str2);
float inMessages(const MessagePtr &msg,
const std::ranges::bidirectional_range auto &messages)
{
float similarityPercent = 0.0F;
for (const auto &prevMsg :
messages | std::views::reverse |
std::views::take(getSettings()->hideSimilarMaxMessagesToCheck))
{
if (prevMsg->parseTime.secsTo(QTime::currentTime()) >=
getSettings()->hideSimilarMaxDelay)
{
break;
}
if (getSettings()->hideSimilarBySameUser &&
msg->loginName != prevMsg->loginName)
{
continue;
}
similarityPercent = std::max(
similarityPercent,
relativeSimilarity(msg->messageText, prevMsg->messageText));
}
return similarityPercent;
}
} // namespace chatterino::similarity::detail
namespace chatterino {
void setSimilarityFlags(const MessagePtr &message,
const std::ranges::bidirectional_range auto &messages)
{
if (getSettings()->similarityEnabled)
{
bool isMyself =
message->loginName ==
getApp()->getAccounts()->twitch.getCurrent()->getUserName();
bool hideMyself = getSettings()->hideSimilarMyself;
if (isMyself && !hideMyself)
{
return;
}
if (similarity::detail::inMessages(message, messages) >
getSettings()->similarityPercentage)
{
message->flags.set(MessageFlag::Similar);
if (getSettings()->colorSimilarDisabled)
{
message->flags.set(MessageFlag::Disabled);
}
}
}
}
} // namespace chatterino

View file

@ -0,0 +1,58 @@
#pragma once
#include "common/enums/MessageContext.hpp"
#include "messages/MessageFlag.hpp"
#include <memory>
class QStringView;
class QTime;
namespace chatterino {
struct Message;
using MessagePtr = std::shared_ptr<const Message>;
enum class MessageSinkTrait : uint8_t {
None = 0,
AddMentionsToGlobalChannel = 1 << 0,
RequiresKnownChannelPointReward = 1 << 1,
};
using MessageSinkTraits = FlagsEnum<MessageSinkTrait>;
/// A generic interface for a managed buffer of `Message`s
class MessageSink
{
public:
virtual ~MessageSink() = default;
/// Add a message to this sink
///
/// @param message The message to add (non-null)
/// @param ctx The context in which this message is being added.
/// @param overridingFlags
virtual void addMessage(
MessagePtr message, MessageContext ctx,
std::optional<MessageFlags> overridingFlags = std::nullopt) = 0;
/// Adds a timeout message or merges it into an existing one
virtual void addOrReplaceTimeout(MessagePtr clearchatMessage,
QTime now) = 0;
/// Flags all messages as `Disabled`
virtual void disableAllMessages() = 0;
/// Searches for similar messages and flags this message as similar
/// (based on the current settings).
virtual void applySimilarityFilters(const MessagePtr &message) const = 0;
/// @brief Searches for a message by an ID
///
/// If there is no message found, an empty shared-pointer is returned.
virtual MessagePtr findMessageByID(QStringView id) = 0;
///
virtual MessageSinkTraits sinkTraits() const = 0;
};
} // namespace chatterino

View file

@ -3,7 +3,9 @@
#include "common/Env.hpp"
#include "messages/MessageBuilder.hpp"
#include "providers/twitch/IrcMessageHandler.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include "util/Helpers.hpp"
#include "util/VectorMessageSink.hpp"
#include <QJsonArray>
#include <QUrlQuery>
@ -40,7 +42,13 @@ std::vector<Communi::IrcMessage *> parseRecentMessages(
std::vector<MessagePtr> buildRecentMessages(
std::vector<Communi::IrcMessage *> &messages, Channel *channel)
{
std::vector<MessagePtr> allBuiltMessages;
VectorMessageSink sink({}, MessageFlag::RecentMessage);
auto *twitchChannel = dynamic_cast<TwitchChannel *>(channel);
if (!twitchChannel)
{
return {};
}
for (auto *message : messages)
{
@ -58,24 +66,16 @@ std::vector<MessagePtr> buildRecentMessages(
auto msg = makeSystemMessage(
QLocale().toString(msgDate, QLocale::LongFormat),
QTime(0, 0));
msg->flags.set(MessageFlag::RecentMessage);
allBuiltMessages.emplace_back(msg);
sink.addMessage(msg, MessageContext::Original);
}
}
auto builtMessages = IrcMessageHandler::parseMessageWithReply(
channel, message, allBuiltMessages);
for (const auto &builtMessage : builtMessages)
{
builtMessage->flags.set(MessageFlag::RecentMessage);
allBuiltMessages.emplace_back(builtMessage);
}
IrcMessageHandler::parseMessageInto(message, sink, twitchChannel);
message->deleteLater();
}
return allBuiltMessages;
return std::move(sink).takeMessages();
}
// Returns the URL to be used for querying the Recent Messages API for the

File diff suppressed because it is too large Load diff

View file

@ -16,6 +16,7 @@ struct Message;
using MessagePtr = std::shared_ptr<const Message>;
class TwitchChannel;
class TwitchMessageBuilder;
class MessageSink;
struct ClearChatMessage {
MessagePtr message;
@ -33,30 +34,35 @@ public:
* Parse an IRC message into 0 or more Chatterino messages
* Takes previously loaded messages into consideration to add reply contexts
**/
static std::vector<MessagePtr> parseMessageWithReply(
Channel *channel, Communi::IrcMessage *message,
std::vector<MessagePtr> &otherLoaded);
static void parseMessageInto(Communi::IrcMessage *message,
MessageSink &sink, TwitchChannel *channel);
void handlePrivMessage(Communi::IrcPrivateMessage *message,
ITwitchIrcServer &twitchServer);
static void parsePrivMessageInto(Communi::IrcPrivateMessage *message,
MessageSink &sink, TwitchChannel *channel);
void handleRoomStateMessage(Communi::IrcMessage *message);
void handleClearChatMessage(Communi::IrcMessage *message);
void handleClearMessageMessage(Communi::IrcMessage *message);
void handleUserStateMessage(Communi::IrcMessage *message);
void handleWhisperMessage(Communi::IrcMessage *ircMessage);
void handleWhisperMessage(Communi::IrcMessage *ircMessage);
void handleUserNoticeMessage(Communi::IrcMessage *message,
ITwitchIrcServer &twitchServer);
static void parseUserNoticeMessageInto(Communi::IrcMessage *message,
MessageSink &sink,
TwitchChannel *channel);
void handleNoticeMessage(Communi::IrcNoticeMessage *message);
void handleJoinMessage(Communi::IrcMessage *message);
void handlePartMessage(Communi::IrcMessage *message);
void addMessage(Communi::IrcMessage *message, const ChannelPtr &chan,
const QString &originalContent, ITwitchIrcServer &server,
bool isSub, bool isAction);
static void addMessage(Communi::IrcMessage *message, MessageSink &sink,
TwitchChannel *channel,
const QString &originalContent, bool isSub,
bool isAction);
private:
static float similarity(const MessagePtr &msg,

View file

@ -452,8 +452,8 @@ void TwitchChannel::addChannelPointReward(const ChannelPointReward &reward)
if (reward.id == msg.rewardID)
{
IrcMessageHandler::instance().addMessage(
msg.message.get(), shared_from_this(),
msg.originalContent, *server, false, false);
msg.message.get(), *this, this, msg.originalContent,
false, false);
return true;
}
return false;

View file

@ -312,7 +312,7 @@ void TwitchIrcServer::initialize()
postToThread([chan, action] {
MessageBuilder msg(action);
msg->flags.set(MessageFlag::PubSub);
chan->addOrReplaceTimeout(msg.release());
chan->addOrReplaceTimeout(msg.release(), QTime::currentTime());
});
});

View file

@ -0,0 +1,86 @@
#include "util/VectorMessageSink.hpp"
#include "messages/MessageSimilarity.hpp"
#include "util/ChannelHelpers.hpp"
#include <cassert>
namespace chatterino {
VectorMessageSink::VectorMessageSink(MessageSinkTraits traits,
MessageFlags additionalFlags)
: additionalFlags(additionalFlags)
, traits(traits){};
VectorMessageSink::~VectorMessageSink() = default;
void VectorMessageSink::addMessage(MessagePtr message, MessageContext ctx,
std::optional<MessageFlags> overridingFlags)
{
assert(!overridingFlags.has_value());
assert(ctx == MessageContext::Original);
message->flags.set(this->additionalFlags);
this->messages_.emplace_back(std::move(message));
}
void VectorMessageSink::addOrReplaceTimeout(MessagePtr clearchatMessage,
QTime now)
{
addOrReplaceChannelTimeout(
this->messages_, std::move(clearchatMessage), now,
[&](auto idx, auto /*msg*/, auto &&replacement) {
replacement->flags.set(this->additionalFlags);
this->messages_[idx] = replacement;
},
[&](auto &&msg) {
this->messages_.emplace_back(msg);
},
false);
}
void VectorMessageSink::disableAllMessages()
{
if (this->additionalFlags.has(MessageFlag::RecentMessage))
{
return; // don't disable recent messages
}
for (const auto &msg : this->messages_)
{
msg->flags.set(MessageFlag::Disabled);
}
}
void VectorMessageSink::applySimilarityFilters(const MessagePtr &message) const
{
setSimilarityFlags(message, this->messages_);
}
MessagePtr VectorMessageSink::findMessageByID(QStringView id)
{
for (const auto &msg : this->messages_ | std::views::reverse)
{
if (msg->id == id)
{
return msg;
}
}
return {};
}
const std::vector<MessagePtr> &VectorMessageSink::messages() const
{
return this->messages_;
}
std::vector<MessagePtr> VectorMessageSink::takeMessages() &&
{
return std::move(this->messages_);
}
MessageSinkTraits VectorMessageSink::sinkTraits() const
{
return this->traits;
}
} // namespace chatterino

View file

@ -0,0 +1,36 @@
#pragma once
#include "messages/MessageSink.hpp"
namespace chatterino {
class VectorMessageSink final : public MessageSink
{
public:
VectorMessageSink(MessageSinkTraits traits = {},
MessageFlags additionalFlags = {});
~VectorMessageSink() override;
void addMessage(
MessagePtr message, MessageContext ctx,
std::optional<MessageFlags> overridingFlags = std::nullopt) override;
void addOrReplaceTimeout(MessagePtr clearchatMessage, QTime now) override;
void disableAllMessages() override;
void applySimilarityFilters(const MessagePtr &message) const override;
MessagePtr findMessageByID(QStringView id) override;
MessageSinkTraits sinkTraits() const override;
const std::vector<MessagePtr> &messages() const;
std::vector<MessagePtr> takeMessages() &&;
private:
std::vector<MessagePtr> messages_;
MessageFlags additionalFlags;
MessageSinkTraits traits;
};
} // namespace chatterino

View file

@ -180,6 +180,7 @@
}
],
"flags": "Collapsed|Subscription",
"highlightColor": "#64c466ff",
"id": "8c26e1ab-b50c-4d9d-bc11-3fd57a941d90",
"localizedName": "",
"loginName": "supinic",

View file

@ -80,7 +80,7 @@
"trailingSpace": true,
"type": "SingleLineTextElement",
"words": [
"a"
"b"
]
},
{
@ -169,6 +169,7 @@
"localizedName": "",
"loginName": "nerixyz",
"messageText": "c",
"replyParent": "474f19ab-a1b0-410a-877a-5b0e2ae8be6d",
"replyThread": {
"replies": [
"474f19ab-a1b0-410a-877a-5b0e2ae8be6d",

View file

@ -256,6 +256,7 @@
}
],
"flags": "Collapsed|Subscription|SharedMessage",
"highlightColor": "#64c466ff",
"id": "01cd601f-bc3f-49d5-ab4b-136fa9d6ec22",
"localizedName": "",
"loginName": "lahoooo",

View file

@ -243,6 +243,7 @@
}
],
"flags": "Collapsed|Subscription",
"highlightColor": "#64c466ff",
"id": "db25007f-7a18-43eb-9379-80131e44d633",
"localizedName": "",
"loginName": "ronni",

View file

@ -27,6 +27,7 @@
#include "singletons/Emotes.hpp"
#include "Test.hpp"
#include "util/IrcHelpers.hpp"
#include "util/VectorMessageSink.hpp"
#include <IrcConnection>
#include <QDebug>
@ -572,19 +573,14 @@ TEST_P(TestIrcMessageHandlerP, Run)
{
auto channel = makeMockTwitchChannel(u"pajlada"_s, *snapshot);
std::vector<MessagePtr> prevMessages;
VectorMessageSink sink;
for (auto prevInput : snapshot->param("prevMessages").toArray())
{
auto *ircMessage = Communi::IrcMessage::fromData(
prevInput.toString().toUtf8(), nullptr);
ASSERT_NE(ircMessage, nullptr);
auto builtMessages = IrcMessageHandler::parseMessageWithReply(
channel.get(), ircMessage, prevMessages);
for (const auto &builtMessage : builtMessages)
{
prevMessages.emplace_back(builtMessage);
}
IrcMessageHandler::parseMessageInto(ircMessage, sink, channel.get());
delete ircMessage;
}
@ -592,13 +588,13 @@ TEST_P(TestIrcMessageHandlerP, Run)
Communi::IrcMessage::fromData(snapshot->inputUtf8(), nullptr);
ASSERT_NE(ircMessage, nullptr);
auto builtMessages = IrcMessageHandler::parseMessageWithReply(
channel.get(), ircMessage, prevMessages);
auto firstAddedMsg = sink.messages().size();
IrcMessageHandler::parseMessageInto(ircMessage, sink, channel.get());
QJsonArray got;
for (const auto &msg : builtMessages)
for (auto i = firstAddedMsg; i < sink.messages().size(); i++)
{
got.append(msg->toJson());
got.append(sink.messages()[i]->toJson());
}
delete ircMessage;