Compare commits

...

23 commits

Author SHA1 Message Date
nerix 59f50f3e13
Merge 35823a5bd9 into 6ceb987e7e 2024-11-10 21:53:30 +01:00
nerix 6ceb987e7e
fix: update channel-view when pausing (#5707) 2024-11-10 19:51:45 +01:00
nerix 35823a5bd9
Merge branch 'master' into experiment/device-auth 2024-11-09 14:34:30 +01:00
dependabot[bot] fc8d27b7e2
chore(deps): bump ZedThree/clang-tidy-review from 0.19.0 to 0.20.0 (#5701) 2024-11-09 13:46:22 +01:00
Nerixyz 082b5b2223
inc 2024-11-09 13:20:11 +01:00
Nerixyz 5877c60478
tidy 2024-11-09 12:55:47 +01:00
Nerixyz 77ea204be0
link 2024-11-09 12:50:11 +01:00
Nerixyz 5fcb033167
Merge remote-tracking branch 'upstream/master' into experiment/device-auth 2024-11-09 11:01:58 +01:00
pajlada 5b1ce32a4e
fix: don't spam debug output about 7TV CreateEmoteSet (#5700) 2024-11-06 15:07:33 +01:00
nerix f3a5f81fa0
deps: use upstream qtkeychain (#5697) 2024-11-05 22:11:14 +01:00
pajlada 46c1f18ae7
feat: add setting to hide blocked term automod messages (#5690) 2024-11-05 21:04:45 +01:00
Felanbird d92b24b8a1
chore: standardize references to FrankerFaceZ & BetterTTV in settings (#5698) 2024-11-05 19:53:43 +00:00
Brian e68f205e04
chore: Specify qtkeychain branch to chatterino-cmake (#5695) 2024-11-05 10:13:20 +01:00
Brian 03cdd98c2e
chore: clarify Lua submodule version (#5693) 2024-11-04 09:49:32 +01:00
nerix 68304272a2
fix: handle multiline selection starting at trailing space (#5691) 2024-11-03 19:23:53 +01:00
nerix d3000ba597
feat: show warning before blocking followed channel (#5615) 2024-11-03 12:29:57 +00:00
nerix 8220a1fbd4
feat: make usernames in USERNOTICEs clickable (#5686) 2024-11-03 11:17:16 +00:00
pajlada 403fc6d3c4
fix: ensure timer doesn't run if the QuickSwitcherPopup is dead (#5687) 2024-11-03 10:49:00 +00:00
nerix 4b725c4d6b
fix(7TV): ignore entitlement.reset (#5685) 2024-11-02 22:32:49 +01:00
hemirt db8047ea7b
highlight tabs only on unviewed messages (#5649) 2024-11-02 13:21:56 +00:00
Nerixyz 738cddeb6b
fix: formatting and changelog 2024-10-27 21:38:40 +01:00
Nerixyz 8241ea003c
fix: compilations 2024-10-27 21:12:36 +01:00
Nerixyz 62cf21c24a
experiment: initial device auth 2024-10-27 20:18:59 +01:00
61 changed files with 1848 additions and 423 deletions

View file

@ -41,7 +41,7 @@ jobs:
- name: clang-tidy review
timeout-minutes: 20
uses: ZedThree/clang-tidy-review@v0.19.0
uses: ZedThree/clang-tidy-review@v0.20.0
with:
build_dir: build-clang-tidy
config_file: ".clang-tidy"
@ -63,4 +63,4 @@ jobs:
libxkbcommon-x11-0, libxcb-xkb-dev, libxcb-cursor0
- name: clang-tidy-review upload
uses: ZedThree/clang-tidy-review/upload@v0.19.0
uses: ZedThree/clang-tidy-review/upload@v0.20.0

View file

@ -14,7 +14,7 @@ jobs:
if: ${{ github.event.workflow_run.conclusion == 'success' }}
steps:
- uses: ZedThree/clang-tidy-review/post@v0.19.0
- uses: ZedThree/clang-tidy-review/post@v0.20.0
with:
lgtm_comment_body: ""
num_comments_as_exitcode: false

1
.gitmodules vendored
View file

@ -38,6 +38,7 @@
[submodule "lib/lua/src"]
path = lib/lua/src
url = https://github.com/lua/lua
branch = v5.4
[submodule "tools/crash-handler"]
path = tools/crash-handler
url = https://github.com/Chatterino/crash-handler

View file

@ -34,9 +34,15 @@
- Minor: Moderators can now see which mods start and cancel raids. (#5563)
- Minor: The emote popup now reloads when Twitch emotes are reloaded. (#5580)
- Minor: Added `--login <username>` CLI argument to specify which account to start logged in as. (#5626)
- Minor: When blocking a channel, Chatterino will now warn you about that action. (#5615)
- Minor: Indicate when subscriptions and resubscriptions are for multiple months. (#5642)
- Minor: Added a setting to control whether or not to show "Blocked Term" automod messages. (#5690)
- Minor: Proxy URL information is now included in the `/debug-env` command. (#5648)
- Minor: Make raid entry message usernames clickable. (#5651)
- Minor: Tabs unhighlight when their content is read in other tabs. (#5649)
- Minor: Made usernames in bits and sub messages clickable. (#5686)
- Minor: Mentions of FrankerFaceZ and BetterTTV in settings are standardized as such. (#5698)
- Minor: Added support for the "Device code grant flow" for authentication. (#5680)
- Bugfix: Fixed tab move animation occasionally failing to start after closing a tab. (#5426, #5612)
- Bugfix: If a network request errors with 200 OK, Qt's error code is now reported instead of the HTTP status. (#5378)
- Bugfix: Fixed restricted users usernames not being clickable. (#5405)
@ -54,6 +60,7 @@
- Bugfix: Fixed event emotes not showing up in autocomplete and popups. (#5239, #5580, #5582, #5632)
- Bugfix: Fixed tab visibility being controllable in the emote popup. (#5530)
- Bugfix: Fixed account switch not being saved if no other settings were changed. (#5558)
- Bugfix: Fixed a crash that could occur when handling the quick switcher popup really quickly. (#5687)
- Bugfix: Fixed 7TV badges being inadvertently animated. (#5674)
- Bugfix: Fixed some tooltips not being readable. (#5578)
- Bugfix: Fixed log files being locked longer than needed. (#5592)
@ -64,6 +71,8 @@
- Bugfix: Fixed emotes starting with ":" not tab-completing. (#5603)
- Bugfix: Fixed 7TV emotes messing with Qt's HTML. (#5677)
- Bugfix: Fixed incorrect messages getting replaced visually. (#5683)
- Bugfix: Fixed rendering of multi-line selection that starts at a trailing space. (#5691)
- Bugfix: Fixed pause indicator not appearing in certain cases. (#5707)
- Dev: Update Windows build from Qt 6.5.0 to Qt 6.7.1. (#5420)
- Dev: Update vcpkg build Qt from 6.5.0 to 6.7.0, boost from 1.83.0 to 1.85.0, openssl from 3.1.3 to 3.3.0. (#5422)
- Dev: Unsingletonize `ISoundController`. (#5462)
@ -112,11 +121,14 @@
- Dev: `GIFTimer` is no longer initialized in tests. (#5608)
- Dev: Emojis now use flags instead of a set of strings for capabilities. (#5616)
- Dev: Move plugins to Sol2. (#5622, #5682)
- Dev: Clarified our Lua dependency's version. (#5693)
- Dev: Specified qtkeychain dependency version. (#5695, #5697)
- Dev: Refactored static `MessageBuilder` helpers to standalone functions. (#5652)
- Dev: Decoupled reply parsing from `MessageBuilder`. (#5660, #5668)
- Dev: Refactored IRC message building. (#5663)
- Dev: Fixed some compiler warnings. (#5672)
- Dev: Unified parsing of historic and live IRC messages. (#5678)
- Dev: 7TV's `entitlement.reset` is now explicitly ignored. (#5685)
## 2.5.1

View file

@ -160,10 +160,19 @@ if (BUILD_WITH_QTKEYCHAIN)
message(FATAL_ERROR "Submodules probably not loaded, unable to find lib/qtkeychain/CMakeLists.txt")
endif()
set(_prev_testing ${BUILD_TESTING})
set(BUILD_TESTING Off)
add_subdirectory("${QTKEYCHAIN_ROOT_LIB_FOLDER}" EXCLUDE_FROM_ALL)
set(BUILD_TESTING ${_prev_testing})
if (NOT TARGET qt${MAJOR_QT_VERSION}keychain)
message(FATAL_ERROR "qt${MAJOR_QT_VERSION}keychain target was not created :@")
endif()
if (MSVC AND "${MAJOR_QT_VERSION}" STREQUAL "5")
target_compile_definitions(qt5keychain PRIVATE UNICODE)
target_compile_options(qt5keychain PRIVATE /utf-8)
set_target_properties(qt5keychain PROPERTIES CXX_STANDARD 17)
endif()
endif()
endif()

@ -1 +1 @@
Subproject commit e5b070831cf1ea3cb98c95f97fcb7439f8d79bd6
Subproject commit 73c3772d6432280df83e1ab3299c2a8f1e4ea47f

View file

@ -422,7 +422,7 @@ public:
// get followed channel
MOCK_METHOD(
void, getFollowedChannel,
(QString userID, QString broadcasterID,
(QString userID, QString broadcasterID, const QObject *caller,
ResultCallback<std::optional<HelixFollowedChannel>> successCallback,
FailureCallback<QString> failureCallback),
(override));

View file

@ -236,7 +236,9 @@ void Application::initialize(Settings &settings, const Paths &paths)
// XXX: Loading Twitch badges after Helix has been initialized, which only happens after
// the AccountController initialize has been called
this->accounts->twitch.requestCurrent([this](const auto &) {
this->twitchBadges->loadTwitchBadges();
});
#ifdef CHATTERINO_HAVE_PLUGINS
this->plugins->initialize(settings);
@ -271,7 +273,9 @@ void Application::initialize(Settings &settings, const Paths &paths)
{
this->initNm(paths);
}
this->accounts->twitch.requestCurrent([this](const auto &) {
this->twitchPubSub->initialize();
});
this->initBttvLiveUpdates();
this->initSeventvEventAPI();

View file

@ -6,6 +6,10 @@
#include <QSize>
#include <QString>
#include <memory>
#include <string>
#include <type_traits>
namespace chatterino {
void _registerSetting(std::weak_ptr<pajlada::Settings::SettingData> setting);
@ -107,7 +111,6 @@ public:
_registerSetting(this->getData());
}
template <typename T2>
EnumStringSetting<Enum> &operator=(Enum newValue)
{
this->setValue(qmagicenum::enumNameString(newValue).toLower());
@ -134,6 +137,21 @@ public:
.value_or(this->defaultValue);
}
static Enum get(const std::string &path, Enum defaultValue)
{
EnumStringSetting<Enum> setting(path, defaultValue);
return setting.getEnum();
}
static void set(const std::string &path, Enum newValue,
Enum defaultValue = static_cast<Enum>(0))
{
EnumStringSetting<Enum> setting(path, defaultValue);
setting = newValue;
}
Enum defaultValue;
using pajlada::Settings::Setting<QString>::operator==;
@ -148,6 +166,9 @@ struct IsChatterinoSettingT : std::false_type {
template <typename T>
struct IsChatterinoSettingT<ChatterinoSetting<T>> : std::true_type {
};
template <typename T>
struct IsChatterinoSettingT<EnumStringSetting<T>> : std::true_type {
};
template <typename T>
concept IsChatterinoSetting = IsChatterinoSettingT<T>::value;

View file

@ -24,7 +24,7 @@
# include "qt5keychain/keychain.h"
# endif
# else
# include "keychain.h"
# include <qtkeychain/keychain.h>
# endif
#endif

View file

@ -26,6 +26,7 @@
#include "providers/twitch/api/Helix.hpp"
#include "providers/twitch/ChannelPointReward.hpp"
#include "providers/twitch/PubSubActions.hpp"
#include "providers/twitch/pubsubmessages/AutoMod.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "providers/twitch/TwitchBadge.hpp"
#include "providers/twitch/TwitchBadges.hpp"
@ -52,6 +53,7 @@
#include <QDateTime>
#include <QDebug>
#include <QFileInfo>
#include <QStringBuilder>
#include <QTimeZone>
#include <algorithm>
@ -75,6 +77,8 @@ const QRegularExpression mentionRegex("^@" + regexHelpString);
// if findAllUsernames setting is enabled, matches strings like in the examples above, but without @ symbol at the beginning
const QRegularExpression allUsernamesMentionRegex("^" + regexHelpString);
const QRegularExpression SPACE_REGEX("\\s");
const QSet<QString> zeroWidthEmotes{
"SoSnowy", "IceCold", "SantaHat", "TopHat",
"ReinDeer", "CandyCane", "cvMask", "cvHazmat",
@ -512,7 +516,7 @@ MessageBuilder::MessageBuilder(SystemMessageTag, const QString &text,
// check system message for links
// (e.g. needed for sub ticket message in sub only mode)
const QStringList textFragments =
text.split(QRegularExpression("\\s"), Qt::SkipEmptyParts);
text.split(SPACE_REGEX, Qt::SkipEmptyParts);
for (const auto &word : textFragments)
{
auto link = linkparser::parse(word);
@ -531,33 +535,100 @@ MessageBuilder::MessageBuilder(SystemMessageTag, const QString &text,
this->message().searchText = text;
}
MessageBuilder::MessageBuilder(RaidEntryMessageTag, const QString &text,
const QString &loginName,
const QString &displayName,
MessagePtrMut MessageBuilder::makeSystemMessageWithUser(
const QString &text, const QString &loginName, const QString &displayName,
const MessageColor &userColor, const QTime &time)
: MessageBuilder()
{
this->emplace<TimestampElement>(time);
MessageBuilder builder;
builder.emplace<TimestampElement>(time);
const QStringList textFragments =
text.split(QRegularExpression("\\s"), Qt::SkipEmptyParts);
const auto textFragments = text.split(SPACE_REGEX, Qt::SkipEmptyParts);
for (const auto &word : textFragments)
{
if (word == displayName)
{
this->emplace<MentionElement>(displayName, loginName,
builder.emplace<MentionElement>(displayName, loginName,
MessageColor::System, userColor);
continue;
}
this->emplace<TextElement>(word, MessageElementFlag::Text,
builder.emplace<TextElement>(word, MessageElementFlag::Text,
MessageColor::System);
}
this->message().flags.set(MessageFlag::System);
this->message().flags.set(MessageFlag::DoNotTriggerNotification);
this->message().messageText = text;
this->message().searchText = text;
builder->flags.set(MessageFlag::System);
builder->flags.set(MessageFlag::DoNotTriggerNotification);
builder->messageText = text;
builder->searchText = text;
return builder.release();
}
MessagePtrMut MessageBuilder::makeSubgiftMessage(const QString &text,
const QVariantMap &tags,
const QTime &time)
{
MessageBuilder builder;
builder.emplace<TimestampElement>(time);
auto gifterLogin = tags.value("login").toString();
auto gifterDisplayName = tags.value("display-name").toString();
if (gifterDisplayName.isEmpty())
{
gifterDisplayName = gifterLogin;
}
MessageColor gifterColor = MessageColor::System;
if (auto colorTag = tags.value("color").value<QColor>(); colorTag.isValid())
{
gifterColor = MessageColor(colorTag);
}
auto recipientLogin =
tags.value("msg-param-recipient-user-name").toString();
if (recipientLogin.isEmpty())
{
recipientLogin = tags.value("msg-param-recipient-name").toString();
}
auto recipientDisplayName =
tags.value("msg-param-recipient-display-name").toString();
if (recipientDisplayName.isEmpty())
{
recipientDisplayName = recipientLogin;
}
const auto textFragments = text.split(SPACE_REGEX, Qt::SkipEmptyParts);
for (const auto &word : textFragments)
{
if (word == gifterDisplayName)
{
builder.emplace<MentionElement>(gifterDisplayName, gifterLogin,
MessageColor::System, gifterColor);
continue;
}
if (word.endsWith('!') &&
word.size() == recipientDisplayName.size() + 1 &&
word.startsWith(recipientDisplayName))
{
builder
.emplace<MentionElement>(recipientDisplayName, recipientLogin,
MessageColor::System,
MessageColor::System)
->setTrailingSpace(false);
builder.emplace<TextElement>(u"!"_s, MessageElementFlag::Text,
MessageColor::System);
continue;
}
builder.emplace<TextElement>(word, MessageElementFlag::Text,
MessageColor::System);
}
builder->flags.set(MessageFlag::System);
builder->flags.set(MessageFlag::DoNotTriggerNotification);
builder->messageText = text;
builder->searchText = text;
return builder.release();
}
MessageBuilder::MessageBuilder(TimeoutMessageTag, const QString &timeoutUser,
@ -1568,6 +1639,12 @@ std::pair<MessagePtr, MessagePtr> MessageBuilder::makeAutomodMessage(
{
MessageBuilder builder, builder2;
if (action.reasonCode == PubSubAutoModQueueMessage::Reason::BlockedTerm)
{
builder.message().flags.set(MessageFlag::AutoModBlockedTerm);
builder2.message().flags.set(MessageFlag::AutoModBlockedTerm);
}
//
// Builder for AutoMod message with explanation
builder.message().id = "automod_" + action.msgID;
@ -1911,6 +1988,29 @@ MessagePtr MessageBuilder::makeLowTrustUpdateMessage(
return builder.release();
}
MessagePtrMut MessageBuilder::makeAccountExpiredMessage(
const QString &expirationText)
{
auto loginPromptText = u"Try adding your account again."_s;
MessageBuilder builder;
auto text = expirationText % ' ' % loginPromptText;
builder->messageText = text;
builder->searchText = text;
builder->flags.set(MessageFlag::System,
MessageFlag::DoNotTriggerNotification);
builder.emplace<TimestampElement>();
builder.emplace<TextElement>(expirationText, MessageElementFlag::Text,
MessageColor::System);
builder
.emplace<TextElement>(loginPromptText, MessageElementFlag::Text,
MessageColor::Link)
->setLink({Link::OpenAccountsPage, {}});
return builder.release();
}
std::pair<MessagePtrMut, HighlightAlert> MessageBuilder::makeIrcMessage(
/* mutable */ Channel *channel, const Communi::IrcMessage *ircMessage,
const MessageParseArgs &args, /* mutable */ QString content,

View file

@ -52,8 +52,6 @@ namespace linkparser {
struct SystemMessageTag {
};
struct RaidEntryMessageTag {
};
struct TimeoutMessageTag {
};
struct LiveUpdatesUpdateEmoteMessageTag {
@ -69,7 +67,6 @@ struct ImageUploaderResultTag {
// NOLINTBEGIN(readability-identifier-naming)
const SystemMessageTag systemMessage{};
const RaidEntryMessageTag raidEntryMessage{};
const TimeoutMessageTag timeoutMessage{};
const LiveUpdatesUpdateEmoteMessageTag liveUpdatesUpdateEmoteMessage{};
const LiveUpdatesRemoveEmoteMessageTag liveUpdatesRemoveEmoteMessage{};
@ -109,9 +106,6 @@ public:
MessageBuilder(SystemMessageTag, const QString &text,
const QTime &time = QTime::currentTime());
MessageBuilder(RaidEntryMessageTag, const QString &text,
const QString &loginName, const QString &displayName,
const MessageColor &userColor, const QTime &time);
MessageBuilder(TimeoutMessageTag, const QString &timeoutUser,
const QString &sourceUser, const QString &systemMessageText,
int times, const QTime &time = QTime::currentTime());
@ -255,6 +249,18 @@ public:
const std::shared_ptr<MessageThread> &thread = {},
const MessagePtr &parent = {});
static MessagePtrMut makeSystemMessageWithUser(
const QString &text, const QString &loginName,
const QString &displayName, const MessageColor &userColor,
const QTime &time);
static MessagePtrMut makeSubgiftMessage(const QString &text,
const QVariantMap &tags,
const QTime &time);
static MessagePtrMut makeAccountExpiredMessage(
const QString &expirationText);
private:
struct TextState {
TwitchChannel *twitchChannel = nullptr;

View file

@ -52,6 +52,8 @@ enum class MessageFlag : std::int64_t {
Action = (1LL << 36),
/// The message is sent in a different source channel as part of a Shared Chat session
SharedMessage = (1LL << 37),
/// AutoMod message that showed up due to containing a blocked term in the channel
AutoModBlockedTerm = (1LL << 38),
};
using MessageFlags = FlagsEnum<MessageFlag>;

View file

@ -141,6 +141,9 @@ void MessageLayout::actuallyLayout(const MessageLayoutContext &ctx)
bool hideModerated = getSettings()->hideModerated;
bool hideModerationActions = getSettings()->hideModerationActions;
bool hideBlockedTermAutomodMessages =
getSettings()->showBlockedTermAutomodMessages.getEnum() ==
ShowModerationState::Never;
bool hideSimilar = getSettings()->hideSimilar;
bool hideReplies = !ctx.flags.has(MessageElementFlag::RepliedMessage);
@ -154,9 +157,21 @@ void MessageLayout::actuallyLayout(const MessageLayoutContext &ctx)
continue;
}
if (hideBlockedTermAutomodMessages &&
this->message_->flags.has(MessageFlag::AutoModBlockedTerm))
{
// NOTE: This hides the message but it will make the message re-appear if moderation message hiding is no longer active, and the layout is re-laid-out.
// This is only the case for the moderation messages that don't get filtered during creation.
// We should decide which is the correct method & apply that everywhere
continue;
}
if (this->message_->flags.has(MessageFlag::Timeout) ||
this->message_->flags.has(MessageFlag::Untimeout))
{
// NOTE: This hides the message but it will make the message re-appear if moderation message hiding is no longer active, and the layout is re-laid-out.
// This is only the case for the moderation messages that don't get filtered during creation.
// We should decide which is the correct method & apply that everywhere
if (hideModerationActions ||
(getSettings()->streamerModeHideModActions &&
getApp()->getStreamerMode()->isEnabled()))

View file

@ -854,6 +854,18 @@ std::optional<size_t> MessageLayoutContainer::paintSelectionStart(
{
const auto selectionColor = getTheme()->messages.selection;
auto paintRemainingLines = [&](size_t startIndex) {
for (size_t i = startIndex; i < this->lines_.size(); i++)
{
const auto &line = this->lines_[i];
auto left = this->elements_[line.startIndex]->getRect().left();
auto right = this->elements_[line.endIndex - 1]->getRect().right();
this->paintSelectionRect(painter, line, left, right, yOffset,
selectionColor);
}
};
// The selection starts in this message
for (size_t lineIndex = 0; lineIndex < this->lines_.size(); lineIndex++)
{
@ -874,9 +886,19 @@ std::optional<size_t> MessageLayoutContainer::paintSelectionStart(
auto right = this->elements_[line.endIndex - 1]->getRect().right();
this->paintSelectionRect(painter, line, right, right, yOffset,
selectionColor);
if (selection.selectionMax.messageIndex != messageIndex)
{
// The selection does not end in this message
paintRemainingLines(lineIndex + 1);
return std::nullopt;
}
// The selection starts in this line, but ends in some next line or message
return {lineIndex + 1};
}
int x = this->elements_[line.startIndex]->getRect().left();
int r = this->elements_[line.endIndex - 1]->getRect().right();
@ -923,21 +945,9 @@ std::optional<size_t> MessageLayoutContainer::paintSelectionStart(
if (selection.selectionMax.messageIndex != messageIndex)
{
// The selection does not end in this message
for (size_t lineIndex2 = lineIndex + 1;
lineIndex2 < this->lines_.size(); lineIndex2++)
{
const auto &line2 = this->lines_[lineIndex2];
auto left =
this->elements_[line2.startIndex]->getRect().left();
auto right =
this->elements_[line2.endIndex - 1]->getRect().right();
this->paintSelectionRect(painter, line2, left, right,
yOffset, selectionColor);
}
this->paintSelectionRect(painter, line, x, r, yOffset,
selectionColor);
paintRemainingLines(lineIndex + 1);
return std::nullopt;
}

View file

@ -283,7 +283,12 @@ private:
/**
* Paint the selection start
*
* Returns a line index if this message should also paint the selection end
* @returns A line index if the selection ends within this message but start
* and end are on different lines. The returned index is the index
* of the first line where the selection starts at the beginning of
* the line. This index should be passed to paintSelectionEnd().
* If `std::nullopt` is returned, no further call to
* paintSelectionEnd() is necessary.
*/
std::optional<size_t> paintSelectionStart(QPainter &painter,
size_t messageIndex,

View file

@ -53,7 +53,7 @@ IrcConnection::IrcConnection(QObject *parent)
else
{
qCDebug(chatterinoIrc) << "Reconnecting";
this->open();
this->connectAndInitializeRequested();
}
});

View file

@ -12,6 +12,8 @@ namespace chatterino {
class IrcConnection : public Communi::IrcConnection
{
Q_OBJECT
public:
IrcConnection(QObject *parent = nullptr);
~IrcConnection() override;
@ -31,6 +33,11 @@ public:
virtual void open();
virtual void close();
signals:
/// Emitted when this connection intends to be connected.
/// The server should initialize this connection an open it.
void connectAndInitializeRequested();
private:
QTimer pingTimer_;
QTimer reconnectTimer_;

View file

@ -233,6 +233,14 @@ void SeventvEventAPI::handleDispatch(const Dispatch &dispatch)
}
}
break;
case SubscriptionType::ResetEntitlement: {
// unhandled (not clear what we'd do here yet)
}
break;
case SubscriptionType::CreateEmoteSet: {
// unhandled (c2 does not support custom emote sets)
}
break;
default: {
qCDebug(chatterinoSeventvEventAPI)
<< "Unknown subscription type:"

View file

@ -27,6 +27,7 @@ enum class SubscriptionType {
CreateEntitlement,
UpdateEntitlement,
DeleteEntitlement,
ResetEntitlement,
INVALID,
};
@ -119,6 +120,8 @@ constexpr magic_enum::customize::customize_t magic_enum::customize::enum_name<
return "entitlement.update";
case SubscriptionType::DeleteEntitlement:
return "entitlement.delete";
case SubscriptionType::ResetEntitlement:
return "entitlement.reset";
default:
return default_tag;

View file

@ -230,29 +230,10 @@ MessagePtr parseNoticeMessage(Communi::IrcNoticeMessage *message)
if (message->content().startsWith("Login auth", Qt::CaseInsensitive))
{
const auto linkColor = MessageColor(MessageColor::Link);
const auto accountsLink = Link(Link::OpenAccountsPage, QString());
const auto curUser = getApp()->getAccounts()->twitch.getCurrent();
const auto expirationText = QString("Login expired for user \"%1\"!")
.arg(curUser->getUserName());
const auto loginPromptText = QString("Try adding your account again.");
MessageBuilder builder;
auto text = QString("%1 %2").arg(expirationText, loginPromptText);
builder.message().messageText = text;
builder.message().searchText = text;
builder.message().flags.set(MessageFlag::System);
builder.message().flags.set(MessageFlag::DoNotTriggerNotification);
builder.emplace<TimestampElement>();
builder.emplace<TextElement>(expirationText, MessageElementFlag::Text,
MessageColor::System);
builder
.emplace<TextElement>(loginPromptText, MessageElementFlag::Text,
linkColor)
->setLink(accountsLink);
return builder.release();
return MessageBuilder::makeAccountExpiredMessage(
u"Login expired for user \"" % curUser->getUserName() % u"\"!");
}
if (message->content().startsWith("You are permanently banned "))
@ -699,35 +680,6 @@ void IrcMessageHandler::parseUserNoticeMessageInto(Communi::IrcMessage *message,
{
messageText = "Announcement";
}
else if (msgType == "raid")
{
auto login = tags.value("login").toString();
auto displayName = tags.value("msg-param-displayName").toString();
if (!login.isEmpty() && !displayName.isEmpty())
{
MessageColor color = MessageColor::System;
if (auto colorTag = tags.value("color").value<QColor>();
colorTag.isValid())
{
color = MessageColor(colorTag);
}
auto b = MessageBuilder(
raidEntryMessage, parseTagString(messageText), login,
displayName, color, calculateMessageTime(message).time());
b->flags.set(MessageFlag::Subscription);
if (mirrored)
{
b->flags.set(MessageFlag::SharedMessage);
}
auto newMessage = b.release();
sink.addMessage(newMessage, MessageContext::Original);
return;
}
}
else if (msgType == "subgift")
{
if (auto monthsIt = tags.find("msg-param-gift-months");
@ -762,6 +714,20 @@ void IrcMessageHandler::parseUserNoticeMessageInto(Communi::IrcMessage *message,
}
}
}
// subgifts are special because they include two users
auto msg = MessageBuilder::makeSubgiftMessage(
parseTagString(messageText), tags,
calculateMessageTime(message).time());
msg->flags.set(MessageFlag::Subscription);
if (mirrored)
{
msg->flags.set(MessageFlag::SharedMessage);
}
sink.addMessage(msg, MessageContext::Original);
return;
}
else if (msgType == "sub" || msgType == "resub")
{
@ -795,17 +761,37 @@ void IrcMessageHandler::parseUserNoticeMessageInto(Communi::IrcMessage *message,
}
}
auto b = MessageBuilder(systemMessage, parseTagString(messageText),
auto displayName = [&] {
if (msgType == u"raid")
{
return tags.value("msg-param-displayName").toString();
}
return tags.value("display-name").toString();
}();
auto login = tags.value("login").toString();
if (displayName.isEmpty())
{
displayName = login;
}
MessageColor userColor = MessageColor::System;
if (auto colorTag = tags.value("color").value<QColor>();
colorTag.isValid())
{
userColor = MessageColor(colorTag);
}
auto msg = MessageBuilder::makeSystemMessageWithUser(
parseTagString(messageText), login, displayName, userColor,
calculateMessageTime(message).time());
b->flags.set(MessageFlag::Subscription);
msg->flags.set(MessageFlag::Subscription);
if (mirrored)
{
b->flags.set(MessageFlag::SharedMessage);
msg->flags.set(MessageFlag::SharedMessage);
}
auto newMessage = b.release();
sink.addMessage(newMessage, MessageContext::Original);
sink.addMessage(msg, MessageContext::Original);
}
}

View file

@ -1,5 +1,7 @@
#pragma once
#include "providers/twitch/pubsubmessages/AutoMod.hpp"
#include <QColor>
#include <QDebug>
#include <QJsonObject>
@ -143,6 +145,7 @@ struct AutomodAction : PubSubAction {
QString message;
QString reason;
PubSubAutoModQueueMessage::Reason reasonCode;
QString msgID;
};

View file

@ -349,40 +349,6 @@ PubSub::PubSub(const QString &host, std::chrono::seconds pingInterval)
this->moderation.raidCanceled.invoke(action);
};
/*
// This handler is no longer required as we use the automod-queue topic now
this->moderationActionHandlers["automod_rejected"] =
[this](const auto &data, const auto &roomID) {
AutomodAction action(data, roomID);
action.source.id = data.value("created_by_user_id").toString();
action.source.login = data.value("created_by").toString();
action.target.id = data.value("target_user_id").toString();
const auto args = data.value("args").toArray();
if (args.isEmpty())
{
return;
}
action.msgID = data.value("msg_id").toString();
if (action.msgID.isEmpty())
{
// Missing required msg_id parameter
return;
}
action.target.login = args[0].toString();
action.message = args[1].toString(); // May be omitted
action.reason = args[2].toString(); // May be omitted
this->moderation.autoModMessageBlocked.invoke(action);
};
*/
this->moderationActionHandlers["automod_message_rejected"] =
[this](const auto &data, const auto &roomID) {
AutomodInfoAction action(data, roomID);

View file

@ -30,14 +30,74 @@ namespace chatterino {
using namespace literals;
TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken,
const QString &oauthClient, const QString &userID)
std::optional<TwitchAccountData> TwitchAccountData::loadRaw(
const std::string &key)
{
using QStringSetting = pajlada::Settings::Setting<QString>;
auto username = QStringSetting::get("/accounts/" + key + "/username");
auto userID = QStringSetting::get("/accounts/" + key + "/userID");
auto clientID = QStringSetting::get("/accounts/" + key + "/clientID");
auto oauthToken = QStringSetting::get("/accounts/" + key + "/oauthToken");
if (username.isEmpty() || userID.isEmpty() || clientID.isEmpty() ||
oauthToken.isEmpty())
{
return std::nullopt;
}
auto accountType = EnumStringSetting<TwitchAccount::Type>::get(
"/accounts/" + key + "/accountType",
TwitchAccount::Type::ImplicitGrant);
auto refreshToken =
QStringSetting::get("/accounts/" + key + "/refreshToken");
auto expiresAtStr = QStringSetting::get("/accounts/" + key + "/expiresAt");
QDateTime expiresAt;
if (accountType == TwitchAccount::Type::DeviceAuth)
{
expiresAt = QDateTime::fromString(expiresAtStr, Qt::ISODate);
}
return TwitchAccountData{
.username = username.trimmed(),
.userID = userID.trimmed(),
.clientID = clientID.trimmed(),
.oauthToken = oauthToken.trimmed(),
.ty = accountType,
.refreshToken = refreshToken,
.expiresAt = expiresAt,
};
}
void TwitchAccountData::save() const
{
using QStringSetting = pajlada::Settings::Setting<QString>;
auto basePath = "/accounts/uid" + this->userID.toStdString();
QStringSetting::set(basePath + "/username", this->username);
QStringSetting::set(basePath + "/userID", this->userID);
QStringSetting::set(basePath + "/clientID", this->clientID);
QStringSetting::set(basePath + "/oauthToken", this->oauthToken);
EnumStringSetting<TwitchAccount::Type>::set(basePath + "/accountType",
this->ty);
QStringSetting::set(basePath + "/refreshToken", this->refreshToken);
if (this->ty == TwitchAccount::Type::DeviceAuth)
{
QStringSetting::set(basePath + "/expiresAt",
this->expiresAt.toString(Qt::ISODate));
}
}
TwitchAccount::TwitchAccount(const TwitchAccountData &data)
: Account(ProviderId::Twitch)
, oauthClient_(oauthClient)
, oauthToken_(oauthToken)
, userName_(username)
, userId_(userID)
, isAnon_(username == ANONYMOUS_USERNAME)
, oauthClient_(data.clientID)
, oauthToken_(data.oauthToken)
, userName_(data.username)
, userId_(data.userID)
, type_(data.ty)
, refreshToken_(data.refreshToken)
, expiresAt_(data.expiresAt)
, isAnon_(data.username == ANONYMOUS_USERNAME)
, emoteSets_(std::make_shared<TwitchEmoteSetMap>())
, emotes_(std::make_shared<EmoteMap>())
{
@ -70,6 +130,21 @@ const QString &TwitchAccount::getUserId() const
return this->userId_;
}
const QString &TwitchAccount::refreshToken() const
{
return this->refreshToken_;
}
const QDateTime &TwitchAccount::expiresAt() const
{
return this->expiresAt_;
}
TwitchAccount::Type TwitchAccount::type() const
{
return this->type_;
}
QColor TwitchAccount::color()
{
return this->color_.get();
@ -80,28 +155,39 @@ void TwitchAccount::setColor(QColor color)
this->color_.set(std::move(color));
}
bool TwitchAccount::setOAuthClient(const QString &newClientID)
bool TwitchAccount::setData(const TwitchAccountData &data)
{
if (this->oauthClient_.compare(newClientID) == 0)
assert(this->userName_ == data.username && this->userId_ == data.userID);
bool anyUpdate = false;
if (this->oauthToken_ != data.oauthToken)
{
return false;
this->oauthToken_ = data.oauthToken;
anyUpdate = true;
}
if (this->oauthClient_ != data.clientID)
{
this->oauthClient_ = data.clientID;
anyUpdate = true;
}
if (this->refreshToken_ != data.refreshToken)
{
this->refreshToken_ = data.refreshToken;
anyUpdate = true;
}
if (this->expiresAt_ != data.expiresAt)
{
this->expiresAt_ = data.expiresAt;
anyUpdate = true;
}
if (this->type_ != data.ty)
{
this->type_ = data.ty;
anyUpdate = true;
}
this->oauthClient_ = newClientID;
return true;
}
bool TwitchAccount::setOAuthToken(const QString &newOAuthToken)
{
if (this->oauthToken_.compare(newOAuthToken) == 0)
{
return false;
}
this->oauthToken_ = newOAuthToken;
return true;
return anyUpdate;
}
bool TwitchAccount::isAnon() const

View file

@ -12,6 +12,7 @@
#include <boost/unordered/unordered_flat_map_fwd.hpp>
#include <pajlada/signals.hpp>
#include <QColor>
#include <QDateTime>
#include <QElapsedTimer>
#include <QObject>
#include <QString>
@ -26,11 +27,41 @@ namespace chatterino {
class Channel;
using ChannelPtr = std::shared_ptr<Channel>;
struct TwitchAccountData;
class TwitchAccount : public Account
{
public:
TwitchAccount(const QString &username, const QString &oauthToken_,
const QString &oauthClient_, const QString &_userID);
enum class Type : uint32_t {
/// Tokens as obtained from https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#implicit-grant-flow
ImplicitGrant,
/// Tokens as obtained from https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#device-code-grant-flow
DeviceAuth,
};
struct TwitchEmote {
EmoteId id;
EmoteName name;
};
struct EmoteSet {
QString key;
QString channelName;
QString channelID;
QString text;
bool subscriber{false};
bool local{false};
std::vector<TwitchEmote> emotes;
};
struct TwitchAccountEmoteData {
std::vector<std::shared_ptr<EmoteSet>> emoteSets;
// this EmoteMap should contain all emotes available globally
// excluding locally available emotes, such as follower ones
EmoteMap emotes;
};
TwitchAccount(const TwitchAccountData &data);
~TwitchAccount() override;
TwitchAccount(const TwitchAccount &) = delete;
TwitchAccount(TwitchAccount &&) = delete;
@ -43,6 +74,9 @@ public:
const QString &getOAuthToken() const;
const QString &getOAuthClient() const;
const QString &getUserId() const;
[[nodiscard]] const QString &refreshToken() const;
[[nodiscard]] const QDateTime &expiresAt() const;
[[nodiscard]] Type type() const;
/**
* The Seventv user-id of the current user.
@ -53,13 +87,10 @@ public:
QColor color();
void setColor(QColor color);
// Attempts to update the users OAuth Client ID
// Returns true if the value has changed, otherwise false
bool setOAuthClient(const QString &newClientID);
// Attempts to update the users OAuth Token
// Returns true if the value has changed, otherwise false
bool setOAuthToken(const QString &newOAuthToken);
/// Attempts to update the account data
/// @pre The name and userID must match this account.
/// @returns true if the value has changed, otherwise false
bool setData(const TwitchAccountData &data);
bool isAnon() const;
@ -112,6 +143,9 @@ private:
QString oauthToken_;
QString userName_;
QString userId_;
Type type_ = Type::ImplicitGrant;
QString refreshToken_;
QDateTime expiresAt_;
const bool isAnon_;
Atomic<QColor> color_;
@ -128,4 +162,17 @@ private:
QString seventvUserID_;
};
struct TwitchAccountData {
QString username;
QString userID;
QString clientID;
QString oauthToken;
TwitchAccount::Type ty = TwitchAccount::Type::ImplicitGrant;
QString refreshToken;
QDateTime expiresAt;
static std::optional<TwitchAccountData> loadRaw(const std::string &key);
void save() const;
};
} // namespace chatterino

View file

@ -3,18 +3,132 @@
#include "Application.hpp"
#include "common/Args.hpp"
#include "common/Common.hpp"
#include "common/Literals.hpp"
#include "common/network/NetworkResult.hpp"
#include "common/Outcome.hpp"
#include "common/QLogging.hpp"
#include "messages/MessageBuilder.hpp"
#include "providers/twitch/api/Helix.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include "providers/twitch/TwitchIrcServer.hpp"
#include "providers/twitch/TwitchUser.hpp"
#include "util/SharedPtrElementLess.hpp"
#include <QStringBuilder>
namespace chatterino {
using namespace literals;
const QString DEVICE_AUTH_CLIENT_ID = u"ows8k58flcricj1oe1pm53eb78xwql"_s;
const QString DEVICE_AUTH_SCOPES =
u""_s
"channel:moderate" // for seeing automod & which moderator banned/unbanned a user (felanbird unbanned weeb123)
" channel:read:redemptions" // for getting the list of channel point redemptions (not currently used)
" chat:edit" // for sending messages in chat
" chat:read" // for viewing messages in chat
" whispers:read" // for viewing recieved whispers
// https://dev.twitch.tv/docs/api/reference#start-commercial
" channel:edit:commercial" // for /commercial api
// https://dev.twitch.tv/docs/api/reference#create-clip
" clips:edit" // for /clip creation
// https://dev.twitch.tv/docs/api/reference#create-stream-marker
// https://dev.twitch.tv/docs/api/reference#modify-channel-information
" channel:manage:broadcast" // for creating stream markers with /marker command, and for the /settitle and /setgame commands
// https://dev.twitch.tv/docs/api/reference#get-user-block-list
" user:read:blocked_users" // for getting list of blocked users
// https://dev.twitch.tv/docs/api/reference#block-user
// https://dev.twitch.tv/docs/api/reference#unblock-user
" user:manage:blocked_users" // for blocking/unblocking other users
// https://dev.twitch.tv/docs/api/reference#manage-held-automod-messages
" moderator:manage:automod" // for approving/denying automod messages
// https://dev.twitch.tv/docs/api/reference#start-a-raid
// https://dev.twitch.tv/docs/api/reference#cancel-a-raid
" channel:manage:raids" // for starting/canceling raids
// https://dev.twitch.tv/docs/api/reference#create-poll
// https://dev.twitch.tv/docs/api/reference#end-poll
" channel:manage:polls" // for creating & ending polls (not currently used)
// https://dev.twitch.tv/docs/api/reference#get-polls
" channel:read:polls" // for reading broadcaster poll status (not currently used)
// https://dev.twitch.tv/docs/api/reference#create-prediction
// https://dev.twitch.tv/docs/api/reference#end-prediction
" channel:manage:predictions" // for creating & ending predictions (not currently used)
// https://dev.twitch.tv/docs/api/reference#get-predictions
" channel:read:predictions" // for reading broadcaster prediction status (not currently used)
// https://dev.twitch.tv/docs/api/reference#send-chat-announcement
" moderator:manage:announcements" // for /announce api
// https://dev.twitch.tv/docs/api/reference#send-whisper
" user:manage:whispers" // for whispers api
// https://dev.twitch.tv/docs/api/reference#ban-user
// https://dev.twitch.tv/docs/api/reference#unban-user
" moderator:manage:banned_users" // for ban/unban/timeout/untimeout api
// https://dev.twitch.tv/docs/api/reference#delete-chat-messages
" moderator:manage:chat_messages" // for delete message api (/delete, /clear)
// https://dev.twitch.tv/docs/api/reference#update-user-chat-color
" user:manage:chat_color" // for update user color api (/color coral)
// https://dev.twitch.tv/docs/api/reference#get-chat-settings
" moderator:manage:chat_settings" // for roomstate api (/followersonly, /uniquechat, /slow)
// https://dev.twitch.tv/docs/api/reference#get-moderators
// https://dev.twitch.tv/docs/api/reference#add-channel-moderator
// https://dev.twitch.tv/docs/api/reference#remove-channel-vip
" channel:manage:moderators" // for add/remove/view mod api
// https://dev.twitch.tv/docs/api/reference#add-channel-vip
// https://dev.twitch.tv/docs/api/reference#remove-channel-vip
// https://dev.twitch.tv/docs/api/reference#get-vips
" channel:manage:vips" // for add/remove/view vip api
// https://dev.twitch.tv/docs/api/reference#get-chatters
" moderator:read:chatters" // for get chatters api
// https://dev.twitch.tv/docs/api/reference#get-shield-mode-status
// https://dev.twitch.tv/docs/api/reference#update-shield-mode-status
" moderator:manage:shield_mode" // for reading/managing the channel's shield-mode status
// https://dev.twitch.tv/docs/api/reference/#send-a-shoutout
" moderator:manage:shoutouts" // for reading/managing the channel's shoutouts (not currently used)
// https://dev.twitch.tv/docs/api/reference/#get-moderated-channels
" user:read:moderated_channels" // for reading where the user is modded (not currently used)
// https://dev.twitch.tv/docs/eventsub/eventsub-subscription-types/#channelchatmessage
" user:read:chat" // for reading chat via eventsub (in progress)
// https://dev.twitch.tv/docs/api/reference/#send-chat-message
" user:write:chat" // for sending chat messages via helix (in testing)
// https://dev.twitch.tv/docs/api/reference/#get-user-emotes
" user:read:emotes" // for fetching emotes that a user can use via helix
// https://dev.twitch.tv/docs/api/reference/#warn-chat-user
" moderator:manage:warnings" // for /warn api (and channel.moderate v2 eventsub in the future)
// https://dev.twitch.tv/docs/api/reference/#get-followed-channels
" user:read:follows" // for determining if the current user follows a streamer
;
TwitchAccountManager::TwitchAccountManager()
: accounts(SharedPtrElementLess<TwitchAccount>{})
, anonymousUser_(new TwitchAccount(ANONYMOUS_USERNAME, "", "", ""))
, anonymousUser_(new TwitchAccount({.username = ANONYMOUS_USERNAME}))
{
this->currentUserChanged.connect([this] {
auto currentUser = this->getCurrent();
@ -27,6 +141,11 @@ TwitchAccountManager::TwitchAccountManager()
std::ignore = this->accounts.itemRemoved.connect([this](const auto &acc) {
this->removeUser(acc.item.get());
});
this->refreshTask_.start(60000);
QObject::connect(&this->refreshTask_, &QTimer::timeout, [this] {
this->refreshAccounts(false);
});
}
std::shared_ptr<TwitchAccount> TwitchAccountManager::getCurrent()
@ -78,8 +197,6 @@ void TwitchAccountManager::reloadUsers()
{
auto keys = pajlada::Settings::SettingManager::getObjectKeys("/accounts");
UserData userData;
bool listUpdated = false;
for (const auto &uid : keys)
@ -89,39 +206,25 @@ void TwitchAccountManager::reloadUsers()
continue;
}
auto username = pajlada::Settings::Setting<QString>::get(
"/accounts/" + uid + "/username");
auto userID = pajlada::Settings::Setting<QString>::get("/accounts/" +
uid + "/userID");
auto clientID = pajlada::Settings::Setting<QString>::get(
"/accounts/" + uid + "/clientID");
auto oauthToken = pajlada::Settings::Setting<QString>::get(
"/accounts/" + uid + "/oauthToken");
if (username.isEmpty() || userID.isEmpty() || clientID.isEmpty() ||
oauthToken.isEmpty())
auto userData = TwitchAccountData::loadRaw(uid);
if (!userData)
{
continue;
}
userData.username = username.trimmed();
userData.userID = userID.trimmed();
userData.clientID = clientID.trimmed();
userData.oauthToken = oauthToken.trimmed();
switch (this->addUser(userData))
switch (this->addUser(*userData))
{
case AddUserResponse::UserAlreadyExists: {
qCDebug(chatterinoTwitch)
<< "User" << userData.username << "already exists";
<< "User" << userData->username << "already exists";
// Do nothing
}
break;
case AddUserResponse::UserValuesUpdated: {
qCDebug(chatterinoTwitch)
<< "User" << userData.username
<< "User" << userData->username
<< "already exists, and values updated!";
if (userData.username == this->getCurrent()->getUserName())
if (userData->username == this->getCurrent()->getUserName())
{
qCDebug(chatterinoTwitch)
<< "It was the current user, so we need to "
@ -131,7 +234,7 @@ void TwitchAccountManager::reloadUsers()
}
break;
case AddUserResponse::UserAdded: {
qCDebug(chatterinoTwitch) << "Added user" << userData.username;
qCDebug(chatterinoTwitch) << "Added user" << userData->username;
listUpdated = true;
}
break;
@ -168,9 +271,11 @@ void TwitchAccountManager::load()
this->currentUser_ = this->anonymousUser_;
}
this->currentUserChanged();
this->refreshAccounts(true);
this->requestCurrentChecked([this](const auto & /*current*/) {
this->currentUser_->reloadEmotes();
});
});
}
bool TwitchAccountManager::isLoggedIn() const
@ -208,37 +313,189 @@ bool TwitchAccountManager::removeUser(TwitchAccount *account)
return true;
}
void TwitchAccountManager::refreshAccounts(bool emitChanged)
{
assertInGuiThread();
if (this->isRefreshing_)
{
return;
}
this->isRefreshing_ = true;
auto launchedRequests = std::make_shared<size_t>(1);
auto tryFlush = [this, launchedRequests, emitChanged] {
if (*launchedRequests == 0)
{
assert(false && "Called tryFlush after a flush");
return;
}
if (--(*launchedRequests) == 0)
{
this->isRefreshing_ = false;
auto consumers = std::exchange(this->pendingUserConsumers_, {});
for (const auto &consumer : consumers)
{
consumer(this->currentUser_);
}
if (emitChanged)
{
this->currentUserChanged();
}
}
};
qCDebug(chatterinoTwitch) << "Checking for accounts to refresh";
auto current = this->currentUser_;
auto now = QDateTime::currentDateTimeUtc();
for (const auto &account : *this->accounts.readOnly())
{
if (account->isAnon() ||
account->type() != TwitchAccount::Type::DeviceAuth)
{
continue;
}
if (now.secsTo(account->expiresAt()) >= 100)
{
continue;
}
(*launchedRequests)++;
qCDebug(chatterinoTwitch)
<< "Refreshing user" << account->getUserName();
QUrlQuery query{
{u"client_id"_s, DEVICE_AUTH_CLIENT_ID},
{u"scope"_s, DEVICE_AUTH_SCOPES},
{u"refresh_token"_s, account->refreshToken()},
{u"grant_type"_s, u"refresh_token"_s},
};
NetworkRequest("https://id.twitch.tv/oauth2/token",
NetworkRequestType::Post)
.payload(query.toString(QUrl::FullyEncoded).toUtf8())
.timeout(20000)
.onSuccess([account, current](const auto &res) {
const auto json = res.parseJson();
auto accessToken = json["access_token"_L1].toString();
auto refreshToken = json["refresh_token"_L1].toString();
auto expiresIn = json["expires_in"_L1].toInt(-1);
if (accessToken.isEmpty() || refreshToken.isEmpty() ||
expiresIn <= 0)
{
qCWarning(chatterinoTwitch)
<< "Received invalid OAuth response when refreshing"
<< account->getUserName();
return;
}
auto expiresAt =
QDateTime::currentDateTimeUtc().addSecs(expiresIn - 120);
TwitchAccountData data{
.username = account->getUserName(),
.userID = account->getUserId(),
.clientID = DEVICE_AUTH_CLIENT_ID,
.oauthToken = accessToken,
.ty = TwitchAccount::Type::DeviceAuth,
.refreshToken = refreshToken,
.expiresAt = expiresAt,
};
data.save();
account->setData(data);
pajlada::Settings::SettingManager::getInstance()->save();
qCDebug(chatterinoTwitch)
<< "Refreshed user" << account->getUserName();
if (account == current)
{
getHelix()->update(DEVICE_AUTH_CLIENT_ID,
account->getOAuthToken());
}
})
.onError([this, account](const auto &res) {
auto json = res.parseJson();
QString message = u"Failed to refresh OAuth token for " %
account->getUserName() % u" (" %
res.formatError() % u" - " %
json["message"_L1].toString(u"no message"_s) %
u").";
qCWarning(chatterinoTwitch) << message;
if (account == this->getCurrent())
{
if (res.status().value_or(0) == 400) // invalid token
{
auto msg =
MessageBuilder::makeAccountExpiredMessage(message);
getApp()->getTwitch()->forEachChannel(
[msg](const auto &chan) {
chan->addMessage(msg, MessageContext::Original);
});
}
else
{
getApp()->getTwitch()->addGlobalSystemMessage(message);
}
}
})
.finally(tryFlush)
.execute();
}
tryFlush(); // if no account was refreshed
}
void TwitchAccountManager::requestCurrent(UserCallback cb)
{
assertInGuiThread();
if (this->isRefreshing_)
{
this->pendingUserConsumers_.emplace_back(std::move(cb));
return;
}
cb(this->currentUser_);
}
void TwitchAccountManager::requestCurrentChecked(UserCallback cb)
{
assertInGuiThread();
this->recheckRefresher();
this->requestCurrent(std::move(cb));
}
void TwitchAccountManager::recheckRefresher()
{
auto now = QDateTime::currentDateTimeUtc();
for (const auto &account : *this->accounts.readOnly())
{
if (account->isAnon() ||
account->type() != TwitchAccount::Type::DeviceAuth)
{
continue;
}
if (now.secsTo(account->expiresAt()) < 1000)
{
this->refreshAccounts(false);
return;
}
}
}
TwitchAccountManager::AddUserResponse TwitchAccountManager::addUser(
const TwitchAccountManager::UserData &userData)
const TwitchAccountData &userData)
{
auto previousUser = this->findUserByUsername(userData.username);
if (previousUser)
{
bool userUpdated = false;
if (previousUser->setOAuthClient(userData.clientID))
{
userUpdated = true;
}
if (previousUser->setOAuthToken(userData.oauthToken))
{
userUpdated = true;
}
bool userUpdated = previousUser->setData(userData);
if (userUpdated)
{
return AddUserResponse::UserValuesUpdated;
}
else
{
return AddUserResponse::UserAlreadyExists;
}
}
auto newUser =
std::make_shared<TwitchAccount>(userData.username, userData.oauthToken,
userData.clientID, userData.userID);
auto newUser = std::make_shared<TwitchAccount>(userData);
// std::lock_guard<std::mutex> lock(this->mutex);

View file

@ -8,6 +8,7 @@
#include <boost/signals2.hpp>
#include <QString>
#include <QTimer>
#include <memory>
#include <mutex>
@ -22,24 +23,30 @@
namespace chatterino {
class TwitchAccount;
struct TwitchAccountData;
class AccountController;
extern const QString DEVICE_AUTH_SCOPES;
extern const QString DEVICE_AUTH_CLIENT_ID;
class TwitchAccountManager
{
TwitchAccountManager();
public:
struct UserData {
QString username;
QString userID;
QString clientID;
QString oauthToken;
};
struct UserData;
using UserCallback =
std::function<void(const std::shared_ptr<TwitchAccount> &)>;
// Returns the current twitchUsers, or the anonymous user if we're not
// currently logged in
std::shared_ptr<TwitchAccount> getCurrent();
void requestCurrent(UserCallback cb);
void requestCurrentChecked(UserCallback cb);
void recheckRefresher();
std::vector<QString> getUsernames() const;
std::shared_ptr<TwitchAccount> findUserByUsername(
@ -69,8 +76,13 @@ private:
UserValuesUpdated,
UserAdded,
};
AddUserResponse addUser(const UserData &data);
AddUserResponse addUser(const TwitchAccountData &data);
bool removeUser(TwitchAccount *account);
void refreshAccounts(bool emitChanged);
bool isRefreshing_ = false;
std::vector<UserCallback> pendingUserConsumers_;
QTimer refreshTask_;
std::shared_ptr<TwitchAccount> currentUser_;

View file

@ -100,6 +100,10 @@ TwitchChannel::TwitchChannel(const QString &name)
this->bSignals_.emplace_back(
getApp()->getAccounts()->twitch.currentUserChanged.connect([this] {
if (this->roomId().isEmpty())
{
return;
}
this->setMod(false);
this->refreshPubSub();
this->refreshTwitchChannelEmotes(false);
@ -234,6 +238,21 @@ void TwitchChannel::setLocalizedName(const QString &name)
}
void TwitchChannel::refreshTwitchChannelEmotes(bool manualRefresh)
{
// ensure the user is authenticated
getApp()->getAccounts()->twitch.requestCurrentChecked(
[weak{this->weak_from_this()}, manualRefresh](const auto &account) {
auto self = std::dynamic_pointer_cast<TwitchChannel>(weak.lock());
if (!self)
{
return;
}
self->refreshTwitchChannelEmotesFor(account, manualRefresh);
});
}
void TwitchChannel::refreshTwitchChannelEmotesFor(
const std::shared_ptr<TwitchAccount> &account, bool manualRefresh)
{
if (getApp()->isTest())
{
@ -242,15 +261,14 @@ void TwitchChannel::refreshTwitchChannelEmotes(bool manualRefresh)
if (manualRefresh)
{
getApp()->getAccounts()->twitch.getCurrent()->reloadEmotes(this);
account->reloadEmotes(this);
}
// Twitch's 'Get User Emotes' doesn't assigns a different set-ID to follower
// emotes compared to subscriber emotes.
QString setID = TWITCH_SUB_EMOTE_SET_PREFIX % this->roomId();
this->localTwitchEmoteSetID_.set(setID);
if (getApp()->getAccounts()->twitch.getCurrent()->hasEmoteSet(
EmoteSetId{setID}))
if (account->hasEmoteSet(EmoteSetId{setID}))
{
this->localTwitchEmotes_.set(std::make_shared<EmoteMap>());
return;
@ -273,8 +291,7 @@ void TwitchChannel::refreshTwitchChannelEmotes(bool manualRefresh)
};
getHelix()->getFollowedChannel(
getApp()->getAccounts()->twitch.getCurrent()->getUserId(),
this->roomId(),
account->getUserId(), this->roomId(), nullptr,
[weak{this->weak_from_this()}, makeEmotes](const auto &chan) {
auto self = std::dynamic_pointer_cast<TwitchChannel>(weak.lock());
if (!self || !chan)

View file

@ -35,6 +35,7 @@ struct Emote;
using EmotePtr = std::shared_ptr<const Emote>;
class EmoteMap;
class TwitchAccount;
class TwitchBadges;
class FfzEmotes;
class BttvEmotes;
@ -342,6 +343,9 @@ private:
void cleanUpReplyThreads();
void showLoginMessage();
void refreshTwitchChannelEmotesFor(
const std::shared_ptr<TwitchAccount> &account, bool manualRefresh);
/// roomIdChanged is called whenever this channel's ID has been changed
/// This should only happen once per channel, whenever the ID goes from unset to set
void roomIdChanged();

View file

@ -225,6 +225,19 @@ TwitchIrcServer::TwitchIrcServer()
this->connections_.managedConnect(this->readConnection_->heartbeat, [this] {
this->markChannelsConnected();
});
QObject::connect(
this->writeConnection_.get(),
&IrcConnection::connectAndInitializeRequested, this, [this]() {
this->initializeConnection(this->writeConnection_.get(),
ConnectionType::Write);
});
QObject::connect(this->readConnection_.get(),
&IrcConnection::connectAndInitializeRequested, this,
[this]() {
this->initializeConnection(this->readConnection_.get(),
ConnectionType::Read);
});
}
void TwitchIrcServer::initialize()
@ -494,6 +507,7 @@ void TwitchIrcServer::initialize()
action.msgID = msg.messageID;
action.message = msg.messageText;
action.reasonCode = msg.reason;
// this message also contains per-word automod data, which could be implemented
@ -711,9 +725,9 @@ void TwitchIrcServer::initialize()
void TwitchIrcServer::initializeConnection(IrcConnection *connection,
ConnectionType type)
{
std::shared_ptr<TwitchAccount> account =
getApp()->getAccounts()->twitch.getCurrent();
getApp()->getAccounts()->twitch.requestCurrentChecked([this, connection,
type](const auto
&account) {
qCDebug(chatterinoTwitch) << "logging in as" << account->getUserName();
// twitch.tv/tags enables IRCv3 tags on messages. See https://dev.twitch.tv/docs/irc/tags
@ -754,6 +768,7 @@ void TwitchIrcServer::initializeConnection(IrcConnection *connection,
connection->setSecure(Env::get().twitchServerSecure);
this->open(type);
});
}
std::shared_ptr<Channel> TwitchIrcServer::createChannel(

View file

@ -3138,7 +3138,7 @@ void Helix::getUserEmotes(
}
void Helix::getFollowedChannel(
QString userID, QString broadcasterID,
QString userID, QString broadcasterID, const QObject *caller,
ResultCallback<std::optional<HelixFollowedChannel>> successCallback,
FailureCallback<QString> failureCallback)
{
@ -3147,6 +3147,7 @@ void Helix::getFollowedChannel(
{u"user_id"_s, userID},
{u"broadcaster_id"_s, broadcasterID},
})
.caller(caller)
.onSuccess([successCallback](auto result) {
if (result.status() != 200)
{

View file

@ -1143,7 +1143,7 @@ public:
/// https://dev.twitch.tv/docs/api/reference/#get-followed-channels
/// (non paginated)
virtual void getFollowedChannel(
QString userID, QString broadcasterID,
QString userID, QString broadcasterID, const QObject *caller,
ResultCallback<std::optional<HelixFollowedChannel>> successCallback,
FailureCallback<QString> failureCallback) = 0;
@ -1486,7 +1486,7 @@ public:
/// https://dev.twitch.tv/docs/api/reference/#get-followed-channels
/// (non paginated)
void getFollowedChannel(
QString userID, QString broadcasterID,
QString userID, QString broadcasterID, const QObject *caller,
ResultCallback<std::optional<HelixFollowedChannel>> successCallback,
FailureCallback<QString> failureCallback) final;

View file

@ -15,6 +15,10 @@ PubSubAutoModQueueMessage::PubSubAutoModQueueMessage(const QJsonObject &root)
this->type = oType.value();
}
this->reason =
qmagicenum::enumCast<Reason>(data.value("reason_code").toString())
.value_or(Reason::INVALID);
auto contentClassification =
data.value("content_classification").toObject();

View file

@ -13,15 +13,24 @@ struct PubSubAutoModQueueMessage {
INVALID,
};
enum class Reason {
AutoMod,
BlockedTerm,
INVALID,
};
QString typeString;
Type type = Type::INVALID;
Reason reason = Reason::INVALID;
QJsonObject data;
QString status;
QString contentCategory;
int contentLevel;
int contentLevel{};
QString messageID;
QString messageText;
@ -51,3 +60,20 @@ constexpr magic_enum::customize::customize_t magic_enum::customize::enum_name<
return default_tag;
}
}
template <>
constexpr magic_enum::customize::customize_t magic_enum::customize::enum_name<
chatterino::PubSubAutoModQueueMessage::Reason>(
chatterino::PubSubAutoModQueueMessage::Reason value) noexcept
{
switch (value)
{
case chatterino::PubSubAutoModQueueMessage::Reason::AutoMod:
return "AutoModCaughtMessageReason";
case chatterino::PubSubAutoModQueueMessage::Reason::BlockedTerm:
return "BlockedTermCaughtMessageReason";
default:
return default_tag;
}
}

View file

@ -69,6 +69,13 @@ enum class ChatSendProtocol : int {
Helix = 2,
};
enum class ShowModerationState : int {
// Always show this moderation-related item
Always = 0,
// Never show this moderation-related item
Never = 1,
};
enum StreamerModeSetting {
Disabled = 0,
Enabled = 1,
@ -345,6 +352,10 @@ public:
IntSetting timeoutStackStyle = {
"/moderation/timeoutStackStyle",
static_cast<int>(TimeoutStackStyle::Default)};
EnumStringSetting<ShowModerationState> showBlockedTermAutomodMessages = {
"/moderation/showBlockedTermAutomodMessages",
ShowModerationState::Always,
};
/// Highlighting
// BoolSetting enableHighlights = {"/highlighting/enabled", true};

View file

@ -140,6 +140,8 @@ WindowManager::WindowManager(const Paths &paths, Settings &settings,
this->forceLayoutChannelViewsListener.add(settings.enableRedeemedHighlight);
this->forceLayoutChannelViewsListener.add(settings.colorUsernames);
this->forceLayoutChannelViewsListener.add(settings.boldUsernames);
this->forceLayoutChannelViewsListener.add(
settings.showBlockedTermAutomodMessages);
this->layoutChannelViewsListener.add(settings.timestampFormat);
this->layoutChannelViewsListener.add(fonts.fontChanged);

View file

@ -41,6 +41,7 @@ DraggablePopup::DraggablePopup(bool closeAutomatically, QWidget *parent)
BaseWindow::ClearBuffersOnDpiChange,
parent)
, lifetimeHack_(std::make_shared<bool>(false))
, closeAutomatically_(closeAutomatically)
, dragTimer_(this)
{
@ -128,4 +129,14 @@ Button *DraggablePopup::createPinButton()
return this->pinButton_;
}
bool DraggablePopup::ensurePinned()
{
if (this->closeAutomatically_ && !this->isPinned_)
{
this->togglePinned();
return true;
}
return false;
}
} // namespace chatterino

View file

@ -38,10 +38,18 @@ protected:
// button pixmap
void togglePinned();
/// Ensures that this popup is pinned (if it's expected to close automatically)
///
/// @returns `true` if the popup was pinned as a result (i.e. if the popup
/// was unpinned and said to automatically close before)
bool ensurePinned();
private:
// isMoving_ is set to true if the user is holding the left mouse button down and has moved the mouse a small amount away from the original click point (startPosDrag_)
bool isMoving_ = false;
bool closeAutomatically_ = false;
// startPosDrag_ is the coordinates where the user originally pressed the mouse button down to start dragging
QPoint startPosDrag_;

View file

@ -204,7 +204,7 @@ void Notebook::duplicatePage(QWidget *page)
{
newTabPosition = tabPosition + 1;
}
auto newTabHighlightState = item->tab->highlightState();
QString newTabTitle = "";
if (item->tab->hasCustomTitle())
{
@ -213,7 +213,7 @@ void Notebook::duplicatePage(QWidget *page)
auto *tab =
this->addPageAt(newContainer, newTabPosition, newTabTitle, false);
tab->setHighlightState(newTabHighlightState);
tab->copyHighlightStateAndSourcesFrom(item->tab);
newContainer->setTab(tab);
}

View file

@ -2,10 +2,15 @@
#include "Application.hpp"
#include "common/Common.hpp"
#include "common/Literals.hpp"
#include "common/network/NetworkRequest.hpp"
#include "common/network/NetworkResult.hpp"
#include "common/Outcome.hpp"
#include "common/QLogging.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "providers/twitch/api/Helix.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "singletons/StreamerMode.hpp"
#include "util/Clipboard.hpp"
#include "util/Helpers.hpp"
@ -17,15 +22,20 @@
#include <QClipboard>
#include <QDebug>
#include <QDesktopServices>
#include <QFontDatabase>
#include <QMessageBox>
#include <QPointer>
#include <QUrl>
namespace chatterino {
#include <QUrlQuery>
namespace {
bool logInWithCredentials(QWidget *parent, const QString &userID,
const QString &username, const QString &clientID,
using namespace chatterino;
using namespace literals;
bool logInWithImplicitGrantCredentials(QWidget *parent, const QString &userID,
const QString &username,
const QString &clientID,
const QString &oauthToken)
{
QStringList errors;
@ -47,7 +57,7 @@ namespace {
errors.append("Missing OAuth Token");
}
if (errors.length() > 0)
if (!errors.empty())
{
QMessageBox messageBox(parent);
messageBox.setWindowTitle("Invalid account credentials");
@ -57,22 +67,324 @@ namespace {
return false;
}
std::string basePath = "/accounts/uid" + userID.toStdString();
pajlada::Settings::Setting<QString>::set(basePath + "/username",
username);
pajlada::Settings::Setting<QString>::set(basePath + "/userID", userID);
pajlada::Settings::Setting<QString>::set(basePath + "/clientID",
clientID);
pajlada::Settings::Setting<QString>::set(basePath + "/oauthToken",
oauthToken);
TwitchAccountData{
.username = username,
.userID = userID,
.clientID = clientID,
.oauthToken = oauthToken,
.ty = TwitchAccount::Type::ImplicitGrant,
.refreshToken = {},
.expiresAt = {},
}
.save();
getApp()->getAccounts()->twitch.reloadUsers();
getApp()->getAccounts()->twitch.currentUsername = username;
return true;
}
class DeviceLoginWidget : public QWidget
{
public:
DeviceLoginWidget();
private:
void reset(const QString &prevError = {});
void tryInitSession(const QJsonObject &response);
void displayError(const QString &error);
void ping();
void updateCurrentWidget(QWidget *next);
QHBoxLayout layout;
QLabel *detailLabel = nullptr;
QTimer expiryTimer_;
QTimer pingTimer_;
QString verificationUri_;
QString userCode_;
QString deviceCode_;
};
DeviceLoginWidget::DeviceLoginWidget()
{
QObject::connect(&this->pingTimer_, &QTimer::timeout, [this] {
this->ping();
});
QObject::connect(&this->expiryTimer_, &QTimer::timeout, [this] {
this->reset(u"The code expired."_s);
});
this->setLayout(&this->layout);
this->reset();
}
void DeviceLoginWidget::updateCurrentWidget(QWidget *next)
{
// clear the layout
QLayoutItem *prev = nullptr;
while ((prev = this->layout.takeAt(0)))
{
delete prev->widget();
delete prev;
}
// insert the item
this->layout.addWidget(next, 1, Qt::AlignCenter);
}
void DeviceLoginWidget::reset(const QString &prevError)
{
this->expiryTimer_.stop();
this->pingTimer_.stop();
auto *wrap = new QWidget;
auto *layout = new QVBoxLayout(wrap);
auto *titleLabel = new QLabel(u"Click on 'Start' to connect an account!"_s);
this->detailLabel = new QLabel(prevError);
this->detailLabel->setWordWrap(true);
layout->addWidget(titleLabel, 1, Qt::AlignCenter);
layout->addWidget(this->detailLabel, 0, Qt::AlignCenter);
auto *startButton = new QPushButton(u"Start"_s);
connect(startButton, &QPushButton::clicked, this, [this] {
QUrlQuery query{
{u"client_id"_s, DEVICE_AUTH_CLIENT_ID},
{u"scopes"_s, DEVICE_AUTH_SCOPES},
};
NetworkRequest(u"https://id.twitch.tv/oauth2/device"_s,
NetworkRequestType::Post)
.payload(query.toString(QUrl::FullyEncoded).toUtf8())
.timeout(10000)
.caller(this)
.onSuccess([this](const auto &res) {
this->tryInitSession(res.parseJson());
return Success;
})
.onError([this](const auto &res) {
const auto json = res.parseJson();
this->displayError(
json["message"_L1].toString(u"error: (no message)"_s));
})
.execute();
});
layout->addWidget(startButton);
this->updateCurrentWidget(wrap);
}
void DeviceLoginWidget::tryInitSession(const QJsonObject &response)
{
auto getString = [&](auto key, QString &dest) {
const auto val = response[key];
if (!val.isString())
{
return false;
}
dest = val.toString();
return true;
};
if (!getString("device_code"_L1, this->deviceCode_))
{
this->displayError(u"Failed to initialize: missing 'device_code'"_s);
return;
}
if (!getString("user_code"_L1, this->userCode_))
{
this->displayError(u"Failed to initialize: missing 'user_code'"_s);
return;
}
if (!getString("verification_uri"_L1, this->verificationUri_))
{
this->displayError(
u"Failed to initialize: missing 'verification_uri'"_s);
return;
}
const auto expiry = response["expires_in"_L1];
if (!expiry.isDouble())
{
this->displayError(u"Failed to initialize: missing 'expires_in'"_s);
return;
}
this->expiryTimer_.start(expiry.toInt(1800) * 1000);
this->pingTimer_.start(response["interval"_L1].toInt(5) * 1000);
auto *wrap = new QWidget;
auto *layout = new QVBoxLayout(wrap);
// A simplified link split by the code, such that
// prefixUrl is the part before the code and postfixUrl
// is the part after the code.
auto [prefixUrl, postfixUrl] = [&] {
QStringView view(this->verificationUri_);
// TODO(Qt 6): use .sliced()
if (view.startsWith(u"https://"))
{
view = view.mid(8);
}
if (view.startsWith(u"www."))
{
view = view.mid(4);
}
auto idx = view.indexOf(this->userCode_);
if (idx < 0)
{
return std::make_tuple(view, QStringView());
}
return std::make_tuple(view.mid(0, idx),
view.mid(idx + this->userCode_.length()));
}();
// <a href={verificationUri}>
// <span>{prefixUrl}</span>
// <span style="font-size: large">{userCode}</span>
// <span>{postfixUrl}</span>
// </a>
auto *userCode = new QLabel(
u"<a href=\"%1\"><span>%2</span><span style=\"font-size: large\">%3</span><span>%4</span></a>"_s
.arg(this->verificationUri_, prefixUrl, this->userCode_,
postfixUrl));
userCode->setOpenExternalLinks(true);
userCode->setTextInteractionFlags(Qt::TextBrowserInteraction);
if (getApp()->getStreamerMode()->isEnabled())
{
userCode->setText(
u"You're in streamer mode.\nUse the buttons below.\nDon't show the code on stream!"_s);
}
layout->addWidget(userCode, 1, Qt::AlignCenter);
this->detailLabel = new QLabel;
layout->addWidget(this->detailLabel, 0, Qt::AlignCenter);
{
auto *hbox = new QHBoxLayout;
auto addButton = [&](auto text, auto handler) {
auto *button = new QPushButton(text);
connect(button, &QPushButton::clicked, handler);
hbox->addWidget(button, 1);
};
addButton(u"Copy code"_s, [this] {
crossPlatformCopy(this->userCode_);
});
addButton(u"Copy URL"_s, [this] {
crossPlatformCopy(this->verificationUri_);
});
addButton(u"Open URL"_s, [this] {
if (!QDesktopServices::openUrl(QUrl(this->verificationUri_)))
{
qCWarning(chatterinoWidget) << "open login in browser failed";
this->displayError(u"Failed to open browser"_s);
}
});
layout->addLayout(hbox, 1);
}
this->updateCurrentWidget(wrap);
}
void DeviceLoginWidget::displayError(const QString &error)
{
if (this->detailLabel)
{
this->detailLabel->setText(error);
}
else
{
qCWarning(chatterinoWidget)
<< "Tried to display error but no detail label was found - error:"
<< error;
}
}
void DeviceLoginWidget::ping()
{
QUrlQuery query{
{u"client_id"_s, DEVICE_AUTH_CLIENT_ID},
{u"scope"_s, DEVICE_AUTH_SCOPES},
{u"device_code"_s, this->deviceCode_},
{u"grant_type"_s, u"urn:ietf:params:oauth:grant-type:device_code"_s},
};
NetworkRequest(u"https://id.twitch.tv/oauth2/token"_s,
NetworkRequestType::Post)
.caller(this)
.timeout((this->pingTimer_.interval() * 9) / 10)
.payload(query.toString(QUrl::FullyEncoded).toUtf8())
.onSuccess([this](const auto &res) {
const auto json = res.parseJson();
auto accessToken = json["access_token"_L1].toString();
auto refreshToken = json["refresh_token"_L1].toString();
auto expiresIn = json["expires_in"_L1].toInt(-1);
if (accessToken.isEmpty() || refreshToken.isEmpty() ||
expiresIn <= 0)
{
this->displayError("Received malformed response");
return;
}
auto expiresAt =
QDateTime::currentDateTimeUtc().addSecs(expiresIn - 120);
QPointer self(this);
auto helix = std::make_shared<Helix>();
helix->update(DEVICE_AUTH_CLIENT_ID, accessToken);
helix->fetchUsers(
{}, {},
[self, helix, refreshToken, accessToken,
expiresAt](const auto &res) {
if (res.empty())
{
if (self)
{
self->displayError("No user associated with token");
}
return;
}
const auto &user = res.front();
TwitchAccountData{
.username = user.login,
.userID = user.id,
.clientID = DEVICE_AUTH_CLIENT_ID,
.oauthToken = accessToken,
.ty = TwitchAccount::Type::DeviceAuth,
.refreshToken = refreshToken,
.expiresAt = expiresAt,
}
.save();
getApp()->getAccounts()->twitch.reloadUsers();
getApp()->getAccounts()->twitch.currentUsername =
user.login;
if (self)
{
self->window()->close();
}
},
[self]() {
if (self)
{
self->displayError(
u"Failed to fetch authenticated user"_s);
}
});
})
.onError([this](const auto &res) {
auto json = res.parseJson();
auto message = json["message"_L1].toString(u"(no message)"_s);
if (message != u"authorization_pending"_s)
{
this->displayError(res.formatError() + u" - "_s + message);
}
})
.execute();
}
} // namespace
namespace chatterino {
BasicLoginWidget::BasicLoginWidget()
{
const QString logInLink = "https://chatterino.com/client_login";
@ -145,7 +457,8 @@ BasicLoginWidget::BasicLoginWidget()
}
}
if (logInWithCredentials(this, userID, username, clientID, oauthToken))
if (logInWithImplicitGrantCredentials(this, userID, username, clientID,
oauthToken))
{
this->window()->close();
}
@ -215,8 +528,8 @@ AdvancedLoginWidget::AdvancedLoginWidget()
QString clientID = this->ui_.clientIDInput.text();
QString oauthToken = this->ui_.oauthTokenInput.text();
logInWithCredentials(this, userID, username, clientID,
oauthToken);
logInWithImplicitGrantCredentials(this, userID, username,
clientID, oauthToken);
});
}
@ -238,7 +551,7 @@ void AdvancedLoginWidget::refreshButtons()
LoginDialog::LoginDialog(QWidget *parent)
: QDialog(parent)
{
this->setMinimumWidth(300);
this->setMinimumWidth(400);
this->setWindowFlags(
(this->windowFlags() & ~(Qt::WindowContextHelpButtonHint)) |
Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint);
@ -248,6 +561,7 @@ LoginDialog::LoginDialog(QWidget *parent)
this->setLayout(&this->ui_.mainLayout);
this->ui_.mainLayout.addWidget(&this->ui_.tabWidget);
this->ui_.tabWidget.addTab(new DeviceLoginWidget, "Device");
this->ui_.tabWidget.addTab(&this->ui_.basic, "Basic");
this->ui_.tabWidget.addTab(&this->ui_.advanced, "Advanced");

View file

@ -2,6 +2,7 @@
#include "Application.hpp"
#include "common/Channel.hpp"
#include "common/Literals.hpp"
#include "common/network/NetworkRequest.hpp"
#include "common/QLogging.hpp"
#include "controllers/accounts/AccountController.hpp"
@ -37,6 +38,8 @@
#include <QCheckBox>
#include <QDesktopServices>
#include <QMessageBox>
#include <QMetaEnum>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QPointer>
@ -141,6 +144,8 @@ int calculateTimeoutDuration(TimeoutButton timeout)
namespace chatterino {
using namespace literals;
UserInfoPopup::UserInfoPopup(bool closeAutomatically, Split *split)
: DraggablePopup(closeAutomatically, split)
, split_(split)
@ -623,9 +628,8 @@ void UserInfoPopup::installEvents()
return;
}
switch (newState)
if (newState == Qt::Unchecked)
{
case Qt::CheckState::Unchecked: {
this->ui_.block->setEnabled(false);
getApp()->getAccounts()->twitch.getCurrent()->unblockUser(
@ -638,23 +642,37 @@ void UserInfoPopup::installEvents()
},
[this, reenableBlockCheckbox] {
this->channel_->addSystemMessage(
QString(
"User %1 couldn't be unblocked, an unknown "
QString("User %1 couldn't be unblocked, an unknown "
"error occurred!")
.arg(this->userName_));
reenableBlockCheckbox();
});
return;
}
break;
case Qt::CheckState::PartiallyChecked: {
// We deliberately ignore this state
}
break;
case Qt::CheckState::Checked: {
if (newState == Qt::Checked)
{
this->ui_.block->setEnabled(false);
bool wasPinned = this->ensurePinned();
auto btn = QMessageBox::warning(
this, u"Blocking " % this->userName_,
u"Blocking %1 can cause unintended side-effects like unfollowing.\n\n"_s
"Are you sure you want to block %1?".arg(this->userName_),
QMessageBox::Yes | QMessageBox::Cancel,
QMessageBox::Cancel);
if (wasPinned)
{
this->togglePinned();
}
if (btn != QMessageBox::Yes)
{
reenableBlockCheckbox();
QSignalBlocker blocker(this->ui_.block);
this->ui_.block->setCheckState(Qt::Unchecked);
return;
}
getApp()->getAccounts()->twitch.getCurrent()->blockUser(
this->userId_, this,
[this, reenableBlockCheckbox, currentUser] {
@ -665,15 +683,17 @@ void UserInfoPopup::installEvents()
},
[this, reenableBlockCheckbox] {
this->channel_->addSystemMessage(
QString(
"User %1 couldn't be blocked, an unknown "
"error occurred!")
QString("User %1 couldn't be blocked, an "
"unknown error occurred!")
.arg(this->userName_));
reenableBlockCheckbox();
});
return;
}
break;
}
qCWarning(chatterinoWidget)
<< "Unexpected check-state when blocking" << this->userName_
<< QMetaEnum::fromType<Qt::CheckState>().valueToKey(newState);
});
// ignore highlights

View file

@ -141,7 +141,7 @@ void QuickSwitcherPopup::updateSuggestions(const QString &text)
* Timeout interval 0 means the call will be delayed until all window events
* have been processed (cf. https://doc.qt.io/qt-5/qtimer.html#interval-prop).
*/
QTimer::singleShot(0, [this] {
QTimer::singleShot(0, this, [this] {
this->adjustSize();
});
}

View file

@ -474,6 +474,8 @@ bool ChannelView::paused() const
void ChannelView::pause(PauseReason reason, std::optional<uint> msecs)
{
bool wasUnpaused = !this->paused();
if (msecs)
{
/// Msecs has a value
@ -504,6 +506,11 @@ void ChannelView::pause(PauseReason reason, std::optional<uint> msecs)
}
this->updatePauses();
if (wasUnpaused)
{
this->update();
}
}
void ChannelView::unpause(PauseReason reason)
@ -1064,6 +1071,8 @@ void ChannelView::setChannel(const ChannelPtr &underlyingChannel)
this->underlyingChannel_ = underlyingChannel;
this->updateID();
this->performLayout();
this->queueUpdate();
@ -1082,6 +1091,8 @@ void ChannelView::setChannel(const ChannelPtr &underlyingChannel)
void ChannelView::setFilters(const QList<QUuid> &ids)
{
this->channelFilters_ = std::make_shared<FilterSet>(ids);
this->updateID();
}
QList<QUuid> ChannelView::getFilterIds() const
@ -3243,4 +3254,27 @@ void ChannelView::pendingLinkInfoStateChanged()
this->tooltipWidget_->applyLastBoundsCheck();
}
void ChannelView::updateID()
{
if (!this->underlyingChannel_)
{
// cannot update
return;
}
std::size_t seed = 0;
auto first = qHash(this->underlyingChannel_->getName());
auto second = qHash(this->getFilterIds());
boost::hash_combine(seed, first);
boost::hash_combine(seed, second);
this->id_ = seed;
}
ChannelView::ChannelViewID ChannelView::getID() const
{
return this->id_;
}
} // namespace chatterino

View file

@ -212,6 +212,14 @@ public:
Scrollbar *scrollbar();
using ChannelViewID = std::size_t;
///
/// \brief Get the ID of this ChannelView
///
/// The ID is made of the underlying channel's name
/// combined with the filter set IDs
ChannelViewID getID() const;
pajlada::Signals::Signal<QMouseEvent *> mouseDown;
pajlada::Signals::NoArgSignal selectionChanged;
pajlada::Signals::Signal<HighlightState> tabHighlightRequested;
@ -315,6 +323,9 @@ private:
void showReplyThreadPopup(const MessagePtr &message);
bool canReplyToMessages() const;
void updateID();
ChannelViewID id_{};
bool layoutQueued_ = false;
bool bufferInvalidationQueued_ = false;
@ -376,7 +387,7 @@ private:
FilterSetPtr channelFilters_;
// Returns true if message should be included
bool shouldIncludeMessage(const MessagePtr &m) const;
bool shouldIncludeMessage(const MessagePtr &message) const;
// Returns whether the scrollbar should have highlights
bool showScrollbarHighlights() const;

View file

@ -1,6 +1,7 @@
#include "widgets/helper/NotebookTab.hpp"
#include "Application.hpp"
#include "common/Channel.hpp"
#include "common/Common.hpp"
#include "controllers/hotkeys/HotkeyCategory.hpp"
#include "controllers/hotkeys/HotkeyController.hpp"
@ -12,9 +13,11 @@
#include "widgets/dialogs/SettingsDialog.hpp"
#include "widgets/Notebook.hpp"
#include "widgets/splits/DraggedSplit.hpp"
#include "widgets/splits/Split.hpp"
#include "widgets/splits/SplitContainer.hpp"
#include <boost/bind/bind.hpp>
#include <boost/container_hash/hash.hpp>
#include <QAbstractAnimation>
#include <QApplication>
#include <QDebug>
@ -302,10 +305,134 @@ bool NotebookTab::isSelected() const
return this->selected_;
}
void NotebookTab::removeHighlightStateChangeSources(
const HighlightSources &toRemove)
{
for (const auto &[source, _] : toRemove)
{
this->removeHighlightSource(source);
}
}
void NotebookTab::removeHighlightSource(
const ChannelView::ChannelViewID &source)
{
this->highlightSources_.erase(source);
}
void NotebookTab::newHighlightSourceAdded(const ChannelView &channelViewSource)
{
auto channelViewId = channelViewSource.getID();
this->removeHighlightSource(channelViewId);
this->updateHighlightStateDueSourcesChange();
auto *splitNotebook = dynamic_cast<SplitNotebook *>(this->notebook_);
if (splitNotebook)
{
for (int i = 0; i < splitNotebook->getPageCount(); ++i)
{
auto *splitContainer =
dynamic_cast<SplitContainer *>(splitNotebook->getPageAt(i));
if (splitContainer)
{
auto *tab = splitContainer->getTab();
if (tab && tab != this)
{
tab->removeHighlightSource(channelViewId);
tab->updateHighlightStateDueSourcesChange();
}
}
}
}
}
void NotebookTab::updateHighlightStateDueSourcesChange()
{
if (std::ranges::any_of(this->highlightSources_, [](const auto &keyval) {
return keyval.second == HighlightState::Highlighted;
}))
{
assert(this->highlightState_ == HighlightState::Highlighted);
return;
}
if (std::ranges::any_of(this->highlightSources_, [](const auto &keyval) {
return keyval.second == HighlightState::NewMessage;
}))
{
if (this->highlightState_ != HighlightState::NewMessage)
{
this->highlightState_ = HighlightState::NewMessage;
this->update();
}
}
else
{
if (this->highlightState_ != HighlightState::None)
{
this->highlightState_ = HighlightState::None;
this->update();
}
}
assert(this->highlightState_ != HighlightState::Highlighted);
}
void NotebookTab::copyHighlightStateAndSourcesFrom(const NotebookTab *sourceTab)
{
if (this->isSelected())
{
assert(this->highlightSources_.empty());
assert(this->highlightState_ == HighlightState::None);
return;
}
this->highlightSources_ = sourceTab->highlightSources_;
if (!this->highlightEnabled_ &&
sourceTab->highlightState_ == HighlightState::NewMessage)
{
return;
}
if (this->highlightState_ == sourceTab->highlightState_ ||
this->highlightState_ == HighlightState::Highlighted)
{
return;
}
this->highlightState_ = sourceTab->highlightState_;
this->update();
}
void NotebookTab::setSelected(bool value)
{
this->selected_ = value;
if (value)
{
auto *splitNotebook = dynamic_cast<SplitNotebook *>(this->notebook_);
if (splitNotebook)
{
for (int i = 0; i < splitNotebook->getPageCount(); ++i)
{
auto *splitContainer =
dynamic_cast<SplitContainer *>(splitNotebook->getPageAt(i));
if (splitContainer)
{
auto *tab = splitContainer->getTab();
if (tab && tab != this)
{
tab->removeHighlightStateChangeSources(
this->highlightSources_);
tab->updateHighlightStateDueSourcesChange();
}
}
}
}
}
this->highlightSources_.clear();
this->highlightState_ = HighlightState::None;
this->update();
@ -358,13 +485,22 @@ bool NotebookTab::isLive() const
return this->isLive_;
}
HighlightState NotebookTab::highlightState() const
{
return this->highlightState_;
}
void NotebookTab::setHighlightState(HighlightState newHighlightStyle)
{
if (this->isSelected())
{
assert(this->highlightSources_.empty());
assert(this->highlightState_ == HighlightState::None);
return;
}
this->highlightSources_.clear();
if (!this->highlightEnabled_ &&
newHighlightStyle == HighlightState::NewMessage)
{
@ -381,9 +517,79 @@ void NotebookTab::setHighlightState(HighlightState newHighlightStyle)
this->update();
}
HighlightState NotebookTab::highlightState() const
void NotebookTab::updateHighlightState(HighlightState newHighlightStyle,
const ChannelView &channelViewSource)
{
return this->highlightState_;
if (this->isSelected())
{
assert(this->highlightSources_.empty());
assert(this->highlightState_ == HighlightState::None);
return;
}
if (!this->shouldMessageHighlight(channelViewSource))
{
return;
}
if (!this->highlightEnabled_ &&
newHighlightStyle == HighlightState::NewMessage)
{
return;
}
// message is highlighting unvisible tab
auto channelViewId = channelViewSource.getID();
switch (newHighlightStyle)
{
case HighlightState::Highlighted:
// override lower states
this->highlightSources_.insert_or_assign(channelViewId,
newHighlightStyle);
case HighlightState::NewMessage: {
// only insert if no state already there to avoid overriding
if (!this->highlightSources_.contains(channelViewId))
{
this->highlightSources_.emplace(channelViewId,
newHighlightStyle);
}
break;
}
case HighlightState::None:
break;
}
if (this->highlightState_ == newHighlightStyle ||
this->highlightState_ == HighlightState::Highlighted)
{
return;
}
this->highlightState_ = newHighlightStyle;
this->update();
}
bool NotebookTab::shouldMessageHighlight(
const ChannelView &channelViewSource) const
{
auto *visibleSplitContainer =
dynamic_cast<SplitContainer *>(this->notebook_->getSelectedPage());
if (visibleSplitContainer != nullptr)
{
const auto &visibleSplits = visibleSplitContainer->getSplits();
for (const auto &visibleSplit : visibleSplits)
{
if (channelViewSource.getID() ==
visibleSplit->getChannelView().getID())
{
return false;
}
}
}
return true;
}
void NotebookTab::setHighlightsEnabled(const bool &newVal)

View file

@ -2,6 +2,7 @@
#include "common/Common.hpp"
#include "widgets/helper/Button.hpp"
#include "widgets/helper/ChannelView.hpp"
#include "widgets/Notebook.hpp"
#include <pajlada/settings/setting.hpp>
@ -59,11 +60,24 @@ public:
**/
bool isLive() const;
/**
* @brief Sets the highlight state of this tab clearing highlight sources
*
* Obeys the HighlightsEnabled setting and highlight states hierarchy
*/
void setHighlightState(HighlightState style);
HighlightState highlightState() const;
/**
* @brief Updates the highlight state and highlight sources of this tab
*
* Obeys the HighlightsEnabled setting and the highlight state hierarchy and tracks the highlight state update sources
*/
void updateHighlightState(HighlightState style,
const ChannelView &channelViewSource);
void copyHighlightStateAndSourcesFrom(const NotebookTab *sourceTab);
void setHighlightsEnabled(const bool &newVal);
void newHighlightSourceAdded(const ChannelView &channelViewSource);
bool hasHighlightsEnabled() const;
HighlightState highlightState() const;
void moveAnimated(QPoint targetPos, bool animated = true);
@ -107,6 +121,16 @@ private:
int normalTabWidthForHeight(int height) const;
bool shouldMessageHighlight(const ChannelView &channelViewSource) const;
using HighlightSources =
std::unordered_map<ChannelView::ChannelViewID, HighlightState>;
HighlightSources highlightSources_;
void removeHighlightStateChangeSources(const HighlightSources &toRemove);
void removeHighlightSource(const ChannelView::ChannelViewID &source);
void updateHighlightStateDueSourcesChange();
QPropertyAnimation positionChangedAnimation_;
QPoint positionAnimationDesiredPoint_;

View file

@ -614,12 +614,16 @@ void GeneralPage::initLayout(GeneralPageView &layout)
"Google",
},
s.emojiSet);
layout.addCheckbox("Show BTTV global emotes", s.enableBTTVGlobalEmotes);
layout.addCheckbox("Show BTTV channel emotes", s.enableBTTVChannelEmotes);
layout.addCheckbox("Enable BTTV live emote updates (requires restart)",
layout.addCheckbox("Show BetterTTV global emotes",
s.enableBTTVGlobalEmotes);
layout.addCheckbox("Show BetterTTV channel emotes",
s.enableBTTVChannelEmotes);
layout.addCheckbox("Enable BetterTTV live emote updates (requires restart)",
s.enableBTTVLiveUpdates);
layout.addCheckbox("Show FFZ global emotes", s.enableFFZGlobalEmotes);
layout.addCheckbox("Show FFZ channel emotes", s.enableFFZChannelEmotes);
layout.addCheckbox("Show FrankerFaceZ global emotes",
s.enableFFZGlobalEmotes);
layout.addCheckbox("Show FrankerFaceZ channel emotes",
s.enableFFZChannelEmotes);
layout.addCheckbox("Show 7TV global emotes", s.enableSevenTVGlobalEmotes);
layout.addCheckbox("Show 7TV channel emotes", s.enableSevenTVChannelEmotes);
layout.addCheckbox("Enable 7TV live emote updates (requires restart)",
@ -1167,6 +1171,14 @@ void GeneralPage::initLayout(GeneralPageView &layout)
layout.addIntInput("Usercard scrollback limit (requires restart)",
s.scrollbackUsercardLimit, 100, 100000, 100);
layout.addDropdownEnumClass<ShowModerationState>(
"Show blocked term automod messages",
qmagicenum::enumNames<ShowModerationState>(),
s.showBlockedTermAutomodMessages,
"Show messages that are blocked by AutoMod for containing a public "
"blocked term in the current channel.",
{});
layout.addDropdown<int>(
"Stack timeouts", {"Stack", "Stack until timeout", "Don't stack"},
s.timeoutStackStyle,

View file

@ -214,10 +214,18 @@ void SplitContainer::addSplit(Split *split)
auto &&conns = this->connectionsPerSplit_[split];
conns.managedConnect(split->getChannelView().tabHighlightRequested,
[this](HighlightState state) {
[this, split](HighlightState state) {
if (this->tab_ != nullptr)
{
this->tab_->setHighlightState(state);
this->tab_->updateHighlightState(
state, split->getChannelView());
}
});
conns.managedConnect(split->channelChanged, [this, split] {
if (this->tab_ != nullptr)
{
this->tab_->newHighlightSourceAdded(split->getChannelView());
}
});

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ffff4500",
"userLoginName": "whoopiix",
"words": [
"whoopiix"
]

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ff00ff7f",
"userLoginName": "hyperbolicxd",
"words": [
"hyperbolicxd"
]
@ -142,6 +145,24 @@
"to"
]
},
{
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
},
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": false,
"type": "MentionElement",
"userColor": "System",
"userLoginName": "quote_if_nam",
"words": [
"quote_if_nam"
]
},
{
"color": "System",
"flags": "Text",
@ -154,7 +175,7 @@
"trailingSpace": true,
"type": "TextElement",
"words": [
"quote_if_nam!"
"!"
]
},
{

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ff0000ff",
"userLoginName": "byebyeheart",
"words": [
"byebyeheart"
]

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ff0000ff",
"userLoginName": "tww2",
"words": [
"TWW2"
]
@ -142,6 +145,24 @@
"to"
]
},
{
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
},
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": false,
"type": "MentionElement",
"userColor": "System",
"userLoginName": "mr_woodchuck",
"words": [
"Mr_Woodchuck"
]
},
{
"color": "System",
"flags": "Text",
@ -154,7 +175,7 @@
"trailingSpace": true,
"type": "TextElement",
"words": [
"Mr_Woodchuck!"
"!"
]
}
],

View file

@ -290,8 +290,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -299,7 +300,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ff008000",
"userLoginName": "ronni",
"words": [
"ronni"
]

View file

@ -217,6 +217,24 @@
"to"
]
},
{
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
},
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": false,
"type": "MentionElement",
"userColor": "System",
"userLoginName": "mohammadrezadh",
"words": [
"MohammadrezaDH"
]
},
{
"color": "System",
"flags": "Text",
@ -229,7 +247,7 @@
"trailingSpace": true,
"type": "TextElement",
"words": [
"MohammadrezaDH!"
"!"
]
}
],

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ffff8ea3",
"userLoginName": "inatsufn",
"words": [
"iNatsuFN"
]
@ -187,6 +190,24 @@
"to"
]
},
{
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
},
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": false,
"type": "MentionElement",
"userColor": "System",
"userLoginName": "kimmi_tm",
"words": [
"kimmi_tm"
]
},
{
"color": "System",
"flags": "Text",
@ -199,7 +220,7 @@
"trailingSpace": true,
"type": "TextElement",
"words": [
"kimmi_tm!"
"!"
]
},
{

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ffeb078d",
"userLoginName": "lucidfoxx",
"words": [
"Lucidfoxx"
]
@ -187,6 +190,24 @@
"to"
]
},
{
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
},
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": false,
"type": "MentionElement",
"userColor": "System",
"userLoginName": "ogprodigy",
"words": [
"OGprodigy"
]
},
{
"color": "System",
"flags": "Text",
@ -199,7 +220,7 @@
"trailingSpace": true,
"type": "TextElement",
"words": [
"OGprodigy!"
"!"
]
}
],

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ff0000ff",
"userLoginName": "calm__like_a_tom",
"words": [
"calm__like_a_tom"
]

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "System",
"userLoginName": "foly__",
"words": [
"foly__"
]

View file

@ -38,8 +38,9 @@
"type": "TimestampElement"
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -47,7 +48,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ffcc00c2",
"userLoginName": "cspice",
"words": [
"cspice"
]
@ -158,8 +161,9 @@
]
},
{
"color": "System",
"flags": "Text",
"color": "Text",
"fallbackColor": "System",
"flags": "Text|Mention",
"link": {
"type": "None",
"value": ""
@ -167,7 +171,9 @@
"style": "ChatMedium",
"tooltip": "",
"trailingSpace": true,
"type": "TextElement",
"type": "MentionElement",
"userColor": "#ffcc00c2",
"userLoginName": "cspice",
"words": [
"cspice"
]

View file

@ -873,9 +873,15 @@ TEST(Commands, E2E)
EXPECT_CALL(mockHelix, update).Times(1);
EXPECT_CALL(mockHelix, loadBlocks).Times(1);
auto account = std::make_shared<TwitchAccount>(
testaccount420["login"].toString(), "token", "oauthclient",
testaccount420["id"].toString());
auto account = std::make_shared<TwitchAccount>(TwitchAccountData{
.username = testaccount420["login"].toString(),
.userID = testaccount420["id"].toString(),
.clientID = "oauthclient",
.oauthToken = "token",
.ty = TwitchAccount::Type::ImplicitGrant,
.refreshToken = {},
.expiresAt = {},
});
getApp()->getAccounts()->twitch.accounts.append(account);
getApp()->getAccounts()->twitch.currentUsername =
testaccount420["login"].toString();

View file

@ -10,6 +10,7 @@
#include <chrono>
#include <mutex>
#include <utility>
using namespace chatterino;
using namespace std::chrono_literals;
@ -82,8 +83,15 @@ public:
QString token = "token")
: PubSub(QString("wss://127.0.0.1:9050%1").arg(path), pingInterval)
{
auto account = std::make_shared<TwitchAccount>("testaccount_420", token,
"clientid", "123456");
auto account = std::make_shared<TwitchAccount>(TwitchAccountData{
.username = "testaccount_420",
.userID = "123456",
.clientID = "clientid",
.oauthToken = std::move(token),
.ty = TwitchAccount::Type::ImplicitGrant,
.refreshToken = {},
.expiresAt = {},
});
this->setAccount(account);
}
};