improving TwitchChannel

This commit is contained in:
fourtf 2018-07-14 14:24:18 +02:00
parent a720c76dc0
commit 111853c574
16 changed files with 752 additions and 674 deletions

View file

@ -15,7 +15,7 @@ BreakBeforeBraces: Custom
AccessModifierOffset: -4
ConstructorInitializerAllOnOneLineOrOnePerLine: false
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: false
DerivePointerBinding: false
BraceWrapping: {

View file

@ -232,7 +232,8 @@ SOURCES += \
src/widgets/dialogs/UpdateDialog.cpp \
src/widgets/settingspages/IgnoresPage.cpp \
src/providers/twitch/PubsubClient.cpp \
src/providers/twitch/TwitchApi.cpp
src/providers/twitch/TwitchApi.cpp \
src/common/uniqueaccess.cpp
HEADERS += \
src/Application.hpp \
@ -414,7 +415,8 @@ HEADERS += \
src/widgets/dialogs/UpdateDialog.hpp \
src/widgets/settingspages/IgnoresPage.hpp \
src/providers/twitch/PubsubClient.hpp \
src/providers/twitch/TwitchApi.hpp
src/providers/twitch/TwitchApi.hpp \
src/common/uniqueaccess.hpp
RESOURCES += \
resources/resources.qrc \

View file

@ -215,4 +215,9 @@ void Channel::onConnected()
{
}
std::weak_ptr<Channel> Channel::weak_from_this()
{
return std::weak_ptr<Channel>(this->shared_from_this());
}
} // namespace chatterino

View file

@ -65,6 +65,9 @@ public:
CompletionModel completionModel;
// pre c++17 polyfill
std::weak_ptr<Channel> weak_from_this();
protected:
virtual void onConnected();

View file

@ -27,13 +27,13 @@ const Qt::KeyboardModifiers showResizeHandlesModifiers = Qt::ControlModifier;
static const char *ANONYMOUS_USERNAME_LABEL ATTR_UNUSED = " - anonymous - ";
#define return_if(x) \
if ((x)) { \
#define return_if(condition) \
if ((condition)) { \
return; \
}
#define return_unless(x) \
if (!(x)) { \
#define return_unless(condition) \
if (!(condition)) { \
return; \
}

View file

@ -212,9 +212,7 @@ void NetworkRequest::doRequest()
return;
}
QByteArray readBytes = reply->readAll();
QByteArray bytes;
bytes.setRawData(readBytes.data(), readBytes.size());
QByteArray bytes = reply->readAll();
data->writeToCache(bytes);
NetworkResult result(bytes);

View file

@ -25,7 +25,7 @@ QJsonObject NetworkResult::parseJson() const
rapidjson::Document NetworkResult::parseRapidJson() const
{
rapidjson::Document ret(rapidjson::kNullType);
rapidjson::Document ret(rapidjson::kObjectType);
rapidjson::ParseResult result = ret.Parse(this->data_.data(), this->data_.length());

View file

@ -0,0 +1 @@
#include "uniqueaccess.hpp"

View file

@ -0,0 +1,81 @@
#pragma once
#include <mutex>
#include <type_traits>
namespace chatterino {
template <typename T>
class AccessGuard
{
public:
AccessGuard(T &element, std::mutex &mutex)
: element_(element)
, mutex_(mutex)
{
this->mutex_.lock();
}
~AccessGuard()
{
this->mutex_.unlock();
}
T *operator->() const
{
return &this->element_;
}
T &operator*() const
{
return this->element_;
}
private:
T &element_;
std::mutex &mutex_;
};
template <typename T>
class UniqueAccess
{
public:
template <typename std::enable_if<std::is_default_constructible<T>::value>::type * = 0>
UniqueAccess()
: element_(T())
{
}
UniqueAccess(const T &element)
: element_(element)
{
}
UniqueAccess(T &&element)
: element_(element)
{
}
UniqueAccess<T> &operator=(const T &element)
{
this->element_ = element;
return *this;
}
UniqueAccess<T> &operator=(T &&element)
{
this->element_ = element;
return *this;
}
AccessGuard<T> access()
{
return AccessGuard<T>(this->element_, this->mutex_);
}
private:
T element_;
std::mutex mutex_;
};
} // namespace chatterino

View file

@ -85,18 +85,17 @@ void IrcMessageHandler::handleRoomStateMessage(Communi::IrcMessage *message)
return;
}
auto chan = app->twitch.server->getChannelOrEmpty(chanName);
TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(chan.get());
if (twitchChannel) {
if (auto *twitchChannel = dynamic_cast<TwitchChannel *>(chan.get())) {
// room-id
decltype(tags.find("xD")) it;
if ((it = tags.find("room-id")) != tags.end()) {
auto roomID = it.value().toString();
auto roomId = it.value().toString();
twitchChannel->setRoomID(roomID);
twitchChannel->setRoomID(roomId);
app->resources->loadChannelData(roomID);
app->resources->loadChannelData(roomId);
}
// Room modes

View file

@ -513,7 +513,7 @@ void PubSub::listenToChannelModerationActions(const QString &channelID,
assert(!channelID.isEmpty());
assert(account != nullptr);
QString userID = account->getUserId();
assert(!userID.isEmpty());
if (userID.isEmpty()) return;
std::string topic(fS("chat_moderator_actions.{}.{}", userID, channelID));

View file

@ -31,78 +31,35 @@ TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection
{
Log("[TwitchChannel:{}] Opened", this->name);
this->startRefreshLiveStatusTimer(60 * 1000);
this->refreshChannelEmotes();
this->refreshViewerList();
auto app = getApp();
this->reloadChannelEmotes();
this->managedConnect(getApp()->accounts->twitch.currentUserChanged,
[=] { this->setMod(false); });
this->managedConnect(app->accounts->twitch.currentUserChanged,
[this]() { this->setMod(false); });
// pubsub
this->userStateChanged.connect([=] { this->refreshPubsub(); });
this->roomIDChanged.connect([=] { this->refreshPubsub(); });
this->managedConnect(getApp()->accounts->twitch.currentUserChanged,
[=] { this->refreshPubsub(); });
this->refreshPubsub();
auto refreshPubSubState = [=]() {
if (!this->hasModRights()) {
return;
}
// room id loaded -> refresh live status
this->roomIDChanged.connect([this]() { this->refreshLiveStatus(); });
if (this->roomID.isEmpty()) {
return;
}
// timers
QObject::connect(&this->chattersListTimer_, &QTimer::timeout,
[=] { this->refreshViewerList(); });
this->chattersListTimer_.start(5 * 60 * 1000);
auto account = app->accounts->twitch.getCurrent();
if (account && !account->getUserId().isEmpty()) {
app->twitch.pubsub->listenToChannelModerationActions(this->roomID, account);
}
};
this->userStateChanged.connect(refreshPubSubState);
this->roomIDchanged.connect(refreshPubSubState);
this->managedConnect(app->accounts->twitch.currentUserChanged, refreshPubSubState);
refreshPubSubState();
this->fetchMessages.connect([this] {
this->fetchRecentMessages(); //
});
QObject::connect(&this->liveStatusTimer_, &QTimer::timeout, [=] { this->refreshLiveStatus(); });
this->liveStatusTimer_.start(60 * 1000);
// --
this->messageSuffix_.append(' ');
this->messageSuffix_.append(QChar(0x206D));
static QStringList jsonLabels = {"moderators", "staff", "admins", "global_mods", "viewers"};
auto refreshChatters = [=](QJsonObject obj) {
QJsonObject chattersObj = obj.value("chatters").toObject();
for (int i = 0; i < jsonLabels.size(); i++) {
foreach (const QJsonValue &v, chattersObj.value(jsonLabels.at(i)).toArray()) {
this->completionModel.addUser(v.toString());
}
}
};
auto doRefreshChatters = [=]() {
const auto streamStatus = this->getStreamStatus();
if (app->settings->onlyFetchChattersForSmallerStreamers) {
if (streamStatus.live && streamStatus.viewerCount > app->settings->smallStreamerLimit) {
return;
}
}
NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->name + "/chatters");
request.setCaller(QThread::currentThread());
request.onSuccess([refreshChatters](auto result) {
refreshChatters(result.parseJson()); //
return true;
});
request.execute();
};
doRefreshChatters();
this->chattersListTimer = new QTimer;
QObject::connect(this->chattersListTimer, &QTimer::timeout, doRefreshChatters);
this->chattersListTimer->start(5 * 60 * 1000);
// debugging
#if 0
for (int i = 0; i < 1000; i++) {
this->addMessage(Message::createSystemMessage("asdf"));
@ -110,15 +67,6 @@ TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection
#endif
}
TwitchChannel::~TwitchChannel()
{
this->liveStatusTimer->stop();
this->liveStatusTimer->deleteLater();
this->chattersListTimer->stop();
this->chattersListTimer->deleteLater();
}
bool TwitchChannel::isEmpty() const
{
return this->name.isEmpty();
@ -129,14 +77,7 @@ bool TwitchChannel::canSendMessage() const
return !this->isEmpty();
}
void TwitchChannel::setRoomID(const QString &_roomID)
{
this->roomID = _roomID;
this->roomIDchanged.invoke();
this->fetchMessages.invoke();
}
void TwitchChannel::reloadChannelEmotes()
void TwitchChannel::refreshChannelEmotes()
{
auto app = getApp();
@ -249,16 +190,16 @@ void TwitchChannel::addJoinedUser(const QString &user)
void TwitchChannel::addPartedUser(const QString &user)
{
auto *app = getApp();
auto app = getApp();
if (user == app->accounts->twitch.getCurrent()->getUserName() ||
!app->settings->showJoins.getValue()) {
!getSettings()->showJoins.getValue()) {
return;
}
std::lock_guard<std::mutex> guard(this->partedUserMutex_);
partedUsers_ << user;
this->partedUsers_ << user;
if (!this->partedUsersMergeQueued_) {
this->partedUsersMergeQueued_ = true;
@ -277,6 +218,18 @@ void TwitchChannel::addPartedUser(const QString &user)
}
}
QString TwitchChannel::getRoomID() const
{
return this->roomID_.get();
}
void TwitchChannel::setRoomID(const QString &id)
{
this->roomID_.set(id);
this->roomIDChanged.invoke();
this->loadRecentMessages();
}
TwitchChannel::RoomModes TwitchChannel::getRoomModes()
{
std::lock_guard<std::mutex> lock(this->roomModeMutex_);
@ -318,13 +271,15 @@ void TwitchChannel::setLive(bool newLiveStatus)
}
if (gotNewLiveStatus) {
this->updateLiveInfo.invoke();
this->liveStatusChanged.invoke();
}
}
void TwitchChannel::refreshLiveStatus()
{
if (this->roomID.isEmpty()) {
auto roomID = this->getRoomID();
if (roomID.isEmpty()) {
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->name);
this->setLive(false);
return;
@ -332,13 +287,11 @@ void TwitchChannel::refreshLiveStatus()
Log("[TwitchChannel:{}] Refreshing live status", this->name);
QString url("https://api.twitch.tv/kraken/streams/" + this->roomID);
QString url("https://api.twitch.tv/kraken/streams/" + roomID);
std::weak_ptr<Channel> weak = this->shared_from_this();
auto request = makeGetStreamRequest(roomID, QThread::currentThread());
auto request = makeGetStreamRequest(this->roomID, QThread::currentThread());
request.onSuccess([weak](auto result) {
request.onSuccess([weak = this->weak_from_this()](auto result) {
auto d = result.parseRapidJson();
ChannelPtr shared = weak.lock();
@ -384,6 +337,7 @@ void TwitchChannel::refreshLiveStatus()
{
std::lock_guard<std::mutex> lock(channel->streamStatusMutex_);
StreamStatus status;
channel->streamStatus_.live = true;
channel->streamStatus_.viewerCount = stream["viewers"].GetUint();
channel->streamStatus_.game = stream["game"].GetString();
@ -413,7 +367,7 @@ void TwitchChannel::refreshLiveStatus()
}
// Signal all listeners that the stream status has been updated
channel->updateLiveInfo.invoke();
channel->liveStatusChanged.invoke();
return true;
});
@ -421,70 +375,109 @@ void TwitchChannel::refreshLiveStatus()
request.execute();
}
void TwitchChannel::startRefreshLiveStatusTimer(int intervalMS)
void TwitchChannel::initializeLiveStatusTimer(int intervalMS)
{
this->liveStatusTimer = new QTimer;
QObject::connect(this->liveStatusTimer, &QTimer::timeout, [this]() {
this->refreshLiveStatus(); //
});
// When the Room ID of a twitch channel has been set, refresh the live status an extra time
this->roomIDchanged.connect([this]() {
this->refreshLiveStatus(); //
});
this->liveStatusTimer->start(intervalMS);
}
void TwitchChannel::fetchRecentMessages()
void TwitchChannel::loadRecentMessages()
{
static QString genericURL =
"https://tmi.twitch.tv/api/rooms/%1/recent_messages?client_id=" + getDefaultClientID();
NetworkRequest request(genericURL.arg(this->roomID));
NetworkRequest request(genericURL.arg(this->getRoomID()));
request.makeAuthorizedV5(getDefaultClientID());
request.setCaller(QThread::currentThread());
std::weak_ptr<Channel> weak = this->shared_from_this();
request.onSuccess([weak](auto result) {
auto obj = result.parseJson();
request.onSuccess([this, weak = this->weak_from_this()](auto result) {
// channel still exists?
ChannelPtr shared = weak.lock();
if (!shared) return false;
if (!shared) {
return false;
}
// parse json
return this->parseRecentMessages(result.parseJson());
});
auto channel = dynamic_cast<TwitchChannel *>(shared.get());
assert(channel != nullptr);
request.execute();
}
static auto readConnection = channel->readConnection_;
QJsonArray msgArray = obj.value("messages").toArray();
if (msgArray.empty()) {
bool TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
{
QJsonArray jsonMessages = jsonRoot.value("messages").toArray();
if (jsonMessages.empty()) {
return false;
}
std::vector<MessagePtr> messages;
for (const QJsonValueRef _msg : msgArray) {
QByteArray content = _msg.toString().toUtf8();
auto msg = Communi::IrcMessage::fromData(content, readConnection);
auto privMsg = static_cast<Communi::IrcPrivateMessage *>(msg);
for (const auto jsonMessage : jsonMessages) {
auto content = jsonMessage.toString().toUtf8();
auto message = Communi::IrcMessage::fromData(content, this->readConnection_);
auto privMsg = dynamic_cast<Communi::IrcPrivateMessage *>(message);
assert(privMsg);
MessageParseArgs args;
TwitchMessageBuilder builder(channel, privMsg, args);
TwitchMessageBuilder builder(this, privMsg, args);
if (!builder.isIgnored()) {
messages.push_back(builder.build());
}
}
channel->addMessagesAtStart(messages);
this->addMessagesAtStart(messages);
return true;
}
void TwitchChannel::refreshPubsub()
{
// listen to moderation actions
if (!this->hasModRights()) return;
auto roomId = this->getRoomID();
if (roomId.isEmpty()) return;
auto account = getApp()->accounts->twitch.getCurrent();
getApp()->twitch2->pubsub->listenToChannelModerationActions(roomId, account);
}
void TwitchChannel::refreshViewerList()
{
// setting?
const auto streamStatus = this->getStreamStatus();
if (getSettings()->onlyFetchChattersForSmallerStreamers) {
if (streamStatus.live && streamStatus.viewerCount > getSettings()->smallStreamerLimit) {
return;
}
}
// get viewer list
NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->name + "/chatters");
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = this->weak_from_this()](auto result) {
// channel still exists?
auto shared = weak.lock();
if (!shared) return false;
return this->parseViewerList(result.parseJson());
});
request.execute();
}
bool TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
{
static QStringList categories = {"moderators", "staff", "admins", "global_mods", "viewers"};
// parse json
QJsonObject jsonCategories = jsonRoot.value("chatters").toObject();
for (const auto &category : categories) {
for (const auto jsonCategory : jsonCategories.value(category).toArray()) {
this->completionModel.addUser(jsonCategory.toString());
}
}
return true;
}
} // namespace chatterino

View file

@ -18,9 +18,6 @@ class TwitchServer;
class TwitchChannel final : public Channel, pajlada::Signals::SignalHolder
{
QTimer *liveStatusTimer;
QTimer *chattersListTimer;
public:
struct StreamStatus {
bool live = false;
@ -46,22 +43,32 @@ public:
QString broadcasterLang;
};
~TwitchChannel() final;
void reloadChannelEmotes();
bool isEmpty() const override;
bool canSendMessage() const override;
void sendMessage(const QString &message) override;
bool isLive() const;
virtual bool isMod() const override;
void setMod(bool value);
virtual bool isBroadcaster() const override;
QString getRoomID() const;
void setRoomID(const QString &id);
RoomModes getRoomModes();
void setRoomModes(const RoomModes &roomModes_);
StreamStatus getStreamStatus() const;
void addRecentChatter(const std::shared_ptr<Message> &message) final;
void addJoinedUser(const QString &user);
void addPartedUser(const QString &user);
struct NameOptions {
QString displayName;
QString localizedName;
};
void refreshChannelEmotes();
const std::shared_ptr<EmoteMap> bttvChannelEmotes;
const std::shared_ptr<EmoteMap> ffzChannelEmotes;
@ -69,35 +76,24 @@ public:
const QString channelURL;
const QString popoutPlayerURL;
void setRoomID(const QString &_roomID);
pajlada::Signals::NoArgSignal roomIDchanged;
pajlada::Signals::NoArgSignal updateLiveInfo;
pajlada::Signals::NoArgSignal roomIDChanged;
pajlada::Signals::NoArgSignal liveStatusChanged;
pajlada::Signals::NoArgBoltSignal fetchMessages;
pajlada::Signals::NoArgSignal userStateChanged;
pajlada::Signals::NoArgSignal roomModesChanged;
QString roomID;
RoomModes getRoomModes();
void setRoomModes(const RoomModes &roomModes_);
StreamStatus getStreamStatus() const;
struct NameOptions {
QString displayName;
QString localizedName;
};
bool isLive() const;
private:
explicit TwitchChannel(const QString &channelName, Communi::IrcConnection *readConnection);
void setLive(bool newLiveStatus);
void initializeLiveStatusTimer(int intervalMS);
void refreshLiveStatus();
void startRefreshLiveStatusTimer(int intervalMS);
void fetchRecentMessages();
void refreshPubsub();
void refreshViewerList();
bool parseViewerList(const QJsonObject &jsonRoot);
void loadRecentMessages();
bool parseRecentMessages(const QJsonObject &jsonRoot);
void setLive(bool newLiveStatus);
mutable std::mutex streamStatusMutex_;
StreamStatus streamStatus_;
@ -110,6 +106,7 @@ private:
QString lastSentMessage_;
RoomModes roomModes_;
std::mutex roomModeMutex_;
MutexValue<QString> roomID_;
QObject object_;
std::mutex joinedUserMutex_;
@ -125,6 +122,9 @@ private:
std::map<QString, NameOptions> recentChatters_;
std::mutex recentChattersMutex_;
QTimer liveStatusTimer_;
QTimer chattersListTimer_;
friend class TwitchServer;
};

View file

@ -298,8 +298,8 @@ void TwitchMessageBuilder::parseRoomID()
if (iterator != std::end(this->tags)) {
this->roomID_ = iterator.value().toString();
if (this->twitchChannel->roomID.isEmpty()) {
this->twitchChannel->roomID = this->roomID_;
if (this->twitchChannel->getRoomID().isEmpty()) {
this->twitchChannel->setRoomID(this->roomID_);
}
}
}

View file

@ -161,16 +161,12 @@ std::shared_ptr<Channel> TwitchServer::getChannelOrEmptyByID(const QString &chan
for (const auto &weakChannel : this->channels) {
auto channel = weakChannel.lock();
if (!channel) {
continue;
}
if (!channel) continue;
auto twitchChannel = std::dynamic_pointer_cast<TwitchChannel>(channel);
if (!twitchChannel) {
continue;
}
if (!twitchChannel) continue;
if (twitchChannel->roomID == channelID) {
if (twitchChannel->getRoomID() == channelID) {
return twitchChannel;
}
}

View file

@ -284,7 +284,7 @@ void SplitHeader::initializeChannelSignals()
TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (twitchChannel) {
this->managedConnections_.emplace_back(twitchChannel->updateLiveInfo.connect([this]() {
this->managedConnections_.emplace_back(twitchChannel->liveStatusChanged.connect([this]() {
this->updateChannelText(); //
}));
}
@ -494,7 +494,7 @@ void SplitHeader::menuReloadChannelEmotes()
TwitchChannel *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (twitchChannel) {
twitchChannel->reloadChannelEmotes();
twitchChannel->refreshChannelEmotes();
}
}