mirror-chatterino2/src/providers/twitch/TwitchChannel.cpp

463 lines
14 KiB
C++
Raw Normal View History

2018-06-26 14:09:39 +02:00
#include "providers/twitch/TwitchChannel.hpp"
2018-06-26 15:33:51 +02:00
#include "common/Common.hpp"
2018-06-26 17:20:03 +02:00
#include "common/UrlFetch.hpp"
2018-06-26 14:09:39 +02:00
#include "debug/Log.hpp"
#include "messages/Message.hpp"
2018-07-06 19:23:47 +02:00
#include "providers/twitch/PubsubClient.hpp"
2018-06-26 14:09:39 +02:00
#include "providers/twitch/TwitchMessageBuilder.hpp"
2018-06-28 19:46:45 +02:00
#include "singletons/Emotes.hpp"
#include "singletons/Settings.hpp"
2018-06-26 14:09:39 +02:00
#include "util/PostToThread.hpp"
2018-02-05 15:11:50 +01:00
#include <IrcConnection>
#include <QThread>
#include <QTimer>
namespace chatterino {
2018-07-06 19:23:47 +02:00
TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection *readConnection)
2018-07-06 17:30:12 +02:00
: Channel(channelName, Channel::Type::Twitch)
2018-06-26 17:06:17 +02:00
, bttvChannelEmotes(new EmoteMap)
, ffzChannelEmotes(new EmoteMap)
2017-12-28 17:50:28 +01:00
, subscriptionURL("https://www.twitch.tv/subs/" + name)
, channelURL("https://twitch.tv/" + name)
, popoutPlayerURL("https://player.twitch.tv/?channel=" + name)
2018-07-06 19:23:47 +02:00
, mod_(false)
, readConnection_(readConnection)
{
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:{}] Opened", this->name);
this->startRefreshLiveStatusTimer(60 * 1000);
auto app = getApp();
2017-12-31 00:50:07 +01:00
this->reloadChannelEmotes();
2018-05-26 20:26:25 +02:00
this->managedConnect(app->accounts->twitch.currentUserChanged,
[this]() { this->setMod(false); });
auto refreshPubSubState = [=]() {
if (!this->hasModRights()) {
return;
}
if (this->roomID.isEmpty()) {
return;
}
2018-05-26 20:26:25 +02:00
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);
2018-05-26 20:26:25 +02:00
this->managedConnect(app->accounts->twitch.currentUserChanged, refreshPubSubState);
refreshPubSubState();
this->fetchMessages.connect([this] {
this->fetchRecentMessages(); //
});
2018-01-17 18:36:12 +01:00
2018-07-06 19:23:47 +02:00
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 = [=]() {
2018-05-24 08:58:34 +02:00
const auto streamStatus = this->getStreamStatus();
if (app->settings->onlyFetchChattersForSmallerStreamers) {
if (streamStatus.live && streamStatus.viewerCount > app->settings->smallStreamerLimit) {
return;
}
}
2018-06-26 17:12:50 +02:00
twitchApiGet("https://tmi.twitch.tv/group/user/" + this->name + "/chatters",
2018-06-26 17:20:03 +02:00
QThread::currentThread(), refreshChatters);
};
doRefreshChatters();
this->chattersListTimer = new QTimer;
QObject::connect(this->chattersListTimer, &QTimer::timeout, doRefreshChatters);
this->chattersListTimer->start(5 * 60 * 1000);
2018-06-19 20:34:50 +02:00
#if 0
for (int i = 0; i < 1000; i++) {
this->addMessage(Message::createSystemMessage("asdf"));
2018-06-19 20:34:50 +02:00
}
#endif
}
TwitchChannel::~TwitchChannel()
{
this->liveStatusTimer->stop();
this->liveStatusTimer->deleteLater();
this->chattersListTimer->stop();
this->chattersListTimer->deleteLater();
}
bool TwitchChannel::isEmpty() const
{
return this->name.isEmpty();
}
bool TwitchChannel::canSendMessage() const
{
2017-12-31 00:50:07 +01:00
return !this->isEmpty();
}
void TwitchChannel::setRoomID(const QString &_roomID)
{
this->roomID = _roomID;
this->roomIDchanged.invoke();
this->fetchMessages.invoke();
}
void TwitchChannel::reloadChannelEmotes()
{
auto app = getApp();
2017-12-17 02:18:13 +01:00
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:{}] Reloading channel emotes", this->name);
2018-06-05 17:39:49 +02:00
app->emotes->bttv.loadChannelEmotes(this->name, this->bttvChannelEmotes);
2018-06-05 18:07:17 +02:00
app->emotes->ffz.loadChannelEmotes(this->name, this->ffzChannelEmotes);
}
void TwitchChannel::sendMessage(const QString &message)
{
auto app = getApp();
2017-12-17 02:18:13 +01:00
if (!app->accounts->twitch.isLoggedIn()) {
// XXX: It would be nice if we could add a link here somehow that opened the "account
// manager" dialog
this->addMessage(
Message::createSystemMessage("You need to log in to send messages. You can "
"link your Twitch account in the settings."));
return;
}
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:{}] Send message: {}", this->name, message);
// Do last message processing
2018-06-05 18:53:49 +02:00
QString parsedMessage = app->emotes->emojis.replaceShortCodes(message);
parsedMessage = parsedMessage.trimmed();
2018-02-05 15:11:50 +01:00
if (parsedMessage.isEmpty()) {
return;
2018-02-05 15:11:50 +01:00
}
if (!this->hasModRights()) {
if (app->settings->allowDuplicateMessages) {
2018-07-06 19:23:47 +02:00
if (parsedMessage == this->lastSentMessage_) {
parsedMessage.append(this->messageSuffix_);
}
}
}
2018-06-06 18:57:22 +02:00
bool messageSent = false;
this->sendMessageSignal.invoke(this->name, parsedMessage, messageSent);
2018-02-11 21:13:23 +01:00
2018-06-06 18:57:22 +02:00
if (messageSent) {
qDebug() << "sent";
2018-07-06 19:23:47 +02:00
this->lastSentMessage_ = parsedMessage;
2018-06-06 18:57:22 +02:00
}
}
bool TwitchChannel::isMod() const
2018-01-17 17:17:26 +01:00
{
2018-07-06 19:23:47 +02:00
return this->mod_;
2018-01-17 17:17:26 +01:00
}
2018-01-17 18:36:12 +01:00
void TwitchChannel::setMod(bool value)
{
2018-07-06 19:23:47 +02:00
if (this->mod_ != value) {
this->mod_ = value;
2018-01-17 18:36:12 +01:00
this->userStateChanged.invoke();
2018-01-17 18:36:12 +01:00
}
}
bool TwitchChannel::isBroadcaster() const
2018-01-17 17:17:26 +01:00
{
auto app = getApp();
2018-05-26 20:26:25 +02:00
return this->name == app->accounts->twitch.getCurrent()->getUserName();
2018-01-17 17:17:26 +01:00
}
void TwitchChannel::addRecentChatter(const std::shared_ptr<Message> &message)
{
assert(!message->loginName.isEmpty());
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->recentChattersMutex_);
2018-07-06 19:23:47 +02:00
this->recentChatters_[message->loginName] = {message->displayName, message->localizedName};
this->completionModel.addUser(message->displayName);
}
void TwitchChannel::addJoinedUser(const QString &user)
{
auto *app = getApp();
2018-05-26 20:26:25 +02:00
if (user == app->accounts->twitch.getCurrent()->getUserName() ||
!app->settings->showJoins.getValue()) {
return;
}
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> guard(this->joinedUserMutex_);
2018-07-06 19:23:47 +02:00
joinedUsers_ << user;
2018-07-06 19:23:47 +02:00
if (!this->joinedUsersMergeQueued_) {
this->joinedUsersMergeQueued_ = true;
2018-07-06 19:23:47 +02:00
QTimer::singleShot(500, &this->object_, [this] {
std::lock_guard<std::mutex> guard(this->joinedUserMutex_);
auto message =
2018-07-06 19:23:47 +02:00
Message::createSystemMessage("Users joined: " + this->joinedUsers_.join(", "));
message->flags |= Message::Collapsed;
2018-05-31 16:02:20 +02:00
this->addMessage(message);
2018-07-06 19:23:47 +02:00
this->joinedUsers_.clear();
this->joinedUsersMergeQueued_ = false;
});
}
}
void TwitchChannel::addPartedUser(const QString &user)
{
auto *app = getApp();
2018-05-26 20:26:25 +02:00
if (user == app->accounts->twitch.getCurrent()->getUserName() ||
!app->settings->showJoins.getValue()) {
return;
}
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> guard(this->partedUserMutex_);
2018-07-06 19:23:47 +02:00
partedUsers_ << user;
2018-07-06 19:23:47 +02:00
if (!this->partedUsersMergeQueued_) {
this->partedUsersMergeQueued_ = true;
2018-07-06 19:23:47 +02:00
QTimer::singleShot(500, &this->object_, [this] {
std::lock_guard<std::mutex> guard(this->partedUserMutex_);
auto message =
2018-07-06 19:23:47 +02:00
Message::createSystemMessage("Users parted: " + this->partedUsers_.join(", "));
message->flags |= Message::Collapsed;
2018-05-31 16:02:20 +02:00
this->addMessage(message);
2018-07-06 19:23:47 +02:00
this->partedUsers_.clear();
2018-07-06 19:23:47 +02:00
this->partedUsersMergeQueued_ = false;
});
}
}
2018-05-24 08:58:34 +02:00
TwitchChannel::RoomModes TwitchChannel::getRoomModes()
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->roomModeMutex_);
2018-05-24 08:58:34 +02:00
2018-07-06 19:23:47 +02:00
return this->roomModes_;
2018-05-24 08:58:34 +02:00
}
void TwitchChannel::setRoomModes(const RoomModes &_roomModes)
{
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->roomModeMutex_);
this->roomModes_ = _roomModes;
2018-05-24 08:58:34 +02:00
}
this->roomModesChanged.invoke();
}
bool TwitchChannel::isLive() const
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->streamStatusMutex_);
return this->streamStatus_.live;
2018-05-24 08:58:34 +02:00
}
TwitchChannel::StreamStatus TwitchChannel::getStreamStatus() const
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->streamStatusMutex_);
return this->streamStatus_;
2018-05-24 08:58:34 +02:00
}
void TwitchChannel::setLive(bool newLiveStatus)
{
bool gotNewLiveStatus = false;
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(this->streamStatusMutex_);
if (this->streamStatus_.live != newLiveStatus) {
gotNewLiveStatus = true;
2018-07-06 19:23:47 +02:00
this->streamStatus_.live = newLiveStatus;
}
}
if (gotNewLiveStatus) {
this->updateLiveInfo.invoke();
}
}
void TwitchChannel::refreshLiveStatus()
{
if (this->roomID.isEmpty()) {
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->name);
this->setLive(false);
return;
}
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:{}] Refreshing live status", this->name);
QString url("https://api.twitch.tv/kraken/streams/" + this->roomID);
std::weak_ptr<Channel> weak = this->shared_from_this();
2018-06-26 17:12:50 +02:00
twitchApiGet2(url, QThread::currentThread(), false, [weak](const rapidjson::Document &d) {
ChannelPtr shared = weak.lock();
if (!shared) {
return;
}
TwitchChannel *channel = dynamic_cast<TwitchChannel *>(shared.get());
if (!d.IsObject()) {
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:refreshLiveStatus] root is not an object");
return;
}
if (!d.HasMember("stream")) {
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:refreshLiveStatus] Missing stream in root");
return;
}
const auto &stream = d["stream"];
if (!stream.IsObject()) {
// Stream is offline (stream is most likely null)
channel->setLive(false);
return;
}
if (!stream.HasMember("viewers") || !stream.HasMember("game") ||
!stream.HasMember("channel") || !stream.HasMember("created_at")) {
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:refreshLiveStatus] Missing members in stream");
channel->setLive(false);
return;
}
const rapidjson::Value &streamChannel = stream["channel"];
if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) {
2018-06-26 17:06:17 +02:00
Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel");
return;
}
// Stream is live
{
2018-07-06 19:23:47 +02:00
std::lock_guard<std::mutex> lock(channel->streamStatusMutex_);
channel->streamStatus_.live = true;
channel->streamStatus_.viewerCount = stream["viewers"].GetUint();
channel->streamStatus_.game = stream["game"].GetString();
channel->streamStatus_.title = streamChannel["status"].GetString();
QDateTime since = QDateTime::fromString(stream["created_at"].GetString(), Qt::ISODate);
auto diff = since.secsTo(QDateTime::currentDateTime());
2018-07-06 19:23:47 +02:00
channel->streamStatus_.uptime =
QString::number(diff / 3600) + "h " + QString::number(diff % 3600 / 60) + "m";
2018-07-06 19:23:47 +02:00
channel->streamStatus_.rerun = false;
if (stream.HasMember("stream_type")) {
2018-07-06 19:23:47 +02:00
channel->streamStatus_.streamType = stream["stream_type"].GetString();
} else {
2018-07-06 19:23:47 +02:00
channel->streamStatus_.streamType = QString();
}
if (stream.HasMember("broadcast_platform")) {
const auto &broadcastPlatformValue = stream["broadcast_platform"];
if (broadcastPlatformValue.IsString()) {
const char *broadcastPlatform = stream["broadcast_platform"].GetString();
if (strcmp(broadcastPlatform, "rerun") == 0) {
2018-07-06 19:23:47 +02:00
channel->streamStatus_.rerun = true;
}
}
}
}
// Signal all listeners that the stream status has been updated
channel->updateLiveInfo.invoke();
});
}
void TwitchChannel::startRefreshLiveStatusTimer(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()
{
static QString genericURL =
"https://tmi.twitch.tv/api/rooms/%1/recent_messages?client_id=" + getDefaultClientID();
std::weak_ptr<Channel> weak = this->shared_from_this();
2018-06-26 17:12:50 +02:00
twitchApiGet(genericURL.arg(roomID), QThread::currentThread(), [weak](QJsonObject obj) {
ChannelPtr shared = weak.lock();
if (!shared) {
return;
}
2018-03-30 12:37:00 +02:00
auto channel = dynamic_cast<TwitchChannel *>(shared.get());
assert(channel != nullptr);
2018-07-06 19:23:47 +02:00
static auto readConnection = channel->readConnection_;
2018-03-30 12:37:00 +02:00
QJsonArray msgArray = obj.value("messages").toArray();
if (msgArray.empty()) {
return;
}
std::vector<MessagePtr> messages;
2018-03-30 12:37:00 +02:00
for (const QJsonValueRef _msg : msgArray) {
QByteArray content = _msg.toString().toUtf8();
auto msg = Communi::IrcMessage::fromData(content, readConnection);
auto privMsg = static_cast<Communi::IrcPrivateMessage *>(msg);
MessageParseArgs args;
2018-06-26 17:06:17 +02:00
TwitchMessageBuilder builder(channel, privMsg, args);
2018-03-30 12:37:00 +02:00
if (!builder.isIgnored()) {
messages.push_back(builder.build());
}
}
2018-03-30 12:37:00 +02:00
channel->addMessagesAtStart(messages);
});
}
} // namespace chatterino