refactored irc

This commit is contained in:
fourtf
2018-02-05 15:11:50 +01:00
parent 12b30eb2ed
commit b351c40d29
56 changed files with 1397 additions and 1154 deletions
+1 -1
View File
@@ -43,5 +43,5 @@ void AccountManager::load()
this->Twitch.userChanged.invoke();
}
} // namespace singletons
} // namespace chatterino
}
+2 -2
View File
@@ -1,6 +1,6 @@
#pragma once
#include "twitch/twitchaccountmanager.hpp"
#include "providers/twitch/twitchaccountmanager.hpp"
namespace chatterino {
namespace singletons {
@@ -14,7 +14,7 @@ public:
void load();
twitch::TwitchAccountManager Twitch;
providers::twitch::TwitchAccountManager Twitch;
};
} // namespace singletons
+101 -103
View File
@@ -1,142 +1,140 @@
#include "singletons/channelmanager.hpp"
#include "singletons/ircmanager.hpp"
//#include "singletons/channelmanager.hpp"
//#include "singletons/ircmanager.hpp"
using namespace chatterino::twitch;
// namespace chatterino {
// namespace singletons {
namespace chatterino {
namespace singletons {
// ChannelManager &ChannelManager::getInstance()
//{
// static ChannelManager instance;
// return instance;
//}
ChannelManager &ChannelManager::getInstance()
{
static ChannelManager instance;
return instance;
}
// ChannelManager::ChannelManager()
// : whispersChannel(new Channel("/whispers"))
// , mentionsChannel(new Channel("/mentions"))
// , emptyChannel(new Channel(""))
//{
//}
ChannelManager::ChannelManager()
: whispersChannel(new Channel("/whispers"))
, mentionsChannel(new Channel("/mentions"))
, emptyChannel(new Channel(""))
{
}
// const std::vector<ChannelPtr> ChannelManager::getItems()
//{
// QMutexLocker locker(&this->channelsMutex);
const std::vector<ChannelPtr> ChannelManager::getItems()
{
QMutexLocker locker(&this->channelsMutex);
// std::vector<ChannelPtr> items;
std::vector<ChannelPtr> items;
// for (auto &item : this->twitchChannels.values()) {
// items.push_back(std::get<0>(item));
// }
for (auto &item : this->twitchChannels.values()) {
items.push_back(std::get<0>(item));
}
// return items;
//}
return items;
}
// ChannelPtr ChannelManager::addTwitchChannel(const QString &rawChannelName)
//{
// QString channelName = rawChannelName.toLower();
ChannelPtr ChannelManager::addTwitchChannel(const QString &rawChannelName)
{
QString channelName = rawChannelName.toLower();
// if (channelName.length() > 1 && channelName.at(0) == '/') {
// return this->getTwitchChannel(channelName);
// }
if (channelName.length() > 1 && channelName.at(0) == '/') {
return this->getTwitchChannel(channelName);
}
// if (channelName.length() > 0 && channelName.at(0) == '#') {
// channelName = channelName.mid(1);
// }
if (channelName.length() > 0 && channelName.at(0) == '#') {
channelName = channelName.mid(1);
}
// QMutexLocker locker(&this->channelsMutex);
QMutexLocker locker(&this->channelsMutex);
// auto it = this->twitchChannels.find(channelName);
auto it = this->twitchChannels.find(channelName);
// if (it == this->twitchChannels.end()) {
// auto channel = std::make_shared<TwitchChannel>(channelName);
if (it == this->twitchChannels.end()) {
auto channel = std::make_shared<TwitchChannel>(channelName);
// this->twitchChannels.insert(channelName, std::make_tuple(channel, 1));
this->twitchChannels.insert(channelName, std::make_tuple(channel, 1));
// this->ircJoin.invoke(channelName);
this->ircJoin.invoke(channelName);
// return channel;
// }
return channel;
}
// std::get<1>(it.value())++;
std::get<1>(it.value())++;
// return std::get<0>(it.value());
//}
return std::get<0>(it.value());
}
// ChannelPtr ChannelManager::getTwitchChannel(const QString &channel)
//{
// QMutexLocker locker(&this->channelsMutex);
ChannelPtr ChannelManager::getTwitchChannel(const QString &channel)
{
QMutexLocker locker(&this->channelsMutex);
// QString c = channel.toLower();
QString c = channel.toLower();
// if (channel.length() > 1 && channel.at(0) == '/') {
// if (c == "/whispers") {
// return whispersChannel;
// }
if (channel.length() > 1 && channel.at(0) == '/') {
if (c == "/whispers") {
return whispersChannel;
}
// if (c == "/mentions") {
// return mentionsChannel;
// }
if (c == "/mentions") {
return mentionsChannel;
}
// return emptyChannel;
// }
return emptyChannel;
}
// auto a = this->twitchChannels.find(c);
auto a = this->twitchChannels.find(c);
// if (a == this->twitchChannels.end()) {
// return emptyChannel;
// }
if (a == this->twitchChannels.end()) {
return emptyChannel;
}
// return std::get<0>(a.value());
//}
return std::get<0>(a.value());
}
// void ChannelManager::removeTwitchChannel(const QString &channel)
//{
// QMutexLocker locker(&this->channelsMutex);
void ChannelManager::removeTwitchChannel(const QString &channel)
{
QMutexLocker locker(&this->channelsMutex);
// if (channel.length() > 1 && channel.at(0) == '/') {
// return;
// }
if (channel.length() > 1 && channel.at(0) == '/') {
return;
}
// QString c = channel.toLower();
QString c = channel.toLower();
// auto a = this->twitchChannels.find(c);
auto a = this->twitchChannels.find(c);
// if (a == this->twitchChannels.end()) {
// return;
// }
if (a == this->twitchChannels.end()) {
return;
}
// std::get<1>(a.value())--;
std::get<1>(a.value())--;
// if (std::get<1>(a.value()) == 0) {
// this->ircPart.invoke(c);
// this->twitchChannels.remove(c);
// }
//}
if (std::get<1>(a.value()) == 0) {
this->ircPart.invoke(c);
this->twitchChannels.remove(c);
}
}
// const std::string &ChannelManager::getUserID(const std::string &username)
//{
// /* TODO: Implement
// auto it = this->usernameToID.find(username);
const std::string &ChannelManager::getUserID(const std::string &username)
{
/* TODO: Implement
auto it = this->usernameToID.find(username);
// if (it != std::end(this->usernameToID)) {
// return *it;
// }
// */
if (it != std::end(this->usernameToID)) {
return *it;
}
*/
// static std::string temporary = "xd";
// return temporary;
//}
static std::string temporary = "xd";
return temporary;
}
// void ChannelManager::doOnAll(std::function<void(ChannelPtr)> func)
//{
// for (const auto &channel : this->twitchChannels) {
// func(std::get<0>(channel));
// }
void ChannelManager::doOnAll(std::function<void(ChannelPtr)> func)
{
for (const auto &channel : this->twitchChannels) {
func(std::get<0>(channel));
}
// func(this->whispersChannel);
// func(this->mentionsChannel);
//}
func(this->whispersChannel);
func(this->mentionsChannel);
}
} // namespace chatterino
}
//} // namespace singletons
//} // namespace chatterino
+31 -36
View File
@@ -1,49 +1,44 @@
#pragma once
//#pragma once
#include "channel.hpp"
#include "channeldata.hpp"
#include "twitch/twitchchannel.hpp"
//#include "channel.hpp"
//#include "channeldata.hpp"
//#include "providers/twitch/twitchchannel.hpp"
#include <map>
//#include <map>
namespace chatterino {
namespace singletons {
class IrcManager;
// namespace chatterino {
// namespace singletons {
// class IrcManager;
class ChannelManager
{
explicit ChannelManager();
// class ChannelManager
//{
// explicit ChannelManager();
public:
static ChannelManager &getInstance();
// public:
// static ChannelManager &getInstance();
const std::vector<ChannelPtr> getItems();
// const std::vector<ChannelPtr> getItems();
ChannelPtr addTwitchChannel(const QString &channel);
ChannelPtr getTwitchChannel(const QString &channel);
void removeTwitchChannel(const QString &channel);
// const std::string &getUserID(const std::string &username);
const std::string &getUserID(const std::string &username);
// void doOnAll(std::function<void(ChannelPtr)> func);
void doOnAll(std::function<void(ChannelPtr)> func);
// // Special channels
// const ChannelPtr whispersChannel;
// const ChannelPtr mentionsChannel;
// const ChannelPtr emptyChannel;
// Special channels
const ChannelPtr whispersChannel;
const ChannelPtr mentionsChannel;
const ChannelPtr emptyChannel;
// private:
// std::map<std::string, std::string> usernameToID;
// std::map<std::string, ChannelData> channelDatas;
private:
std::map<std::string, std::string> usernameToID;
std::map<std::string, ChannelData> channelDatas;
// QMutex channelsMutex;
// QMap<QString, std::tuple<std::shared_ptr<TwitchChannel>, int>> twitchChannels;
QMutex channelsMutex;
QMap<QString, std::tuple<std::shared_ptr<twitch::TwitchChannel>, int>> twitchChannels;
// pajlada::Signals::Signal<const QString &> ircJoin;
// pajlada::Signals::Signal<const QString &> ircPart;
pajlada::Signals::Signal<const QString &> ircJoin;
pajlada::Signals::Signal<const QString &> ircPart;
friend class singletons::IrcManager;
};
} // namespace chatterino
}
// friend class singletons::IrcManager;
//};
//} // namespace singletons
//} // namespace chatterino
+19 -14
View File
@@ -6,7 +6,9 @@
#include <QRegularExpression>
#include "channel.hpp"
#include "twitch/twitchchannel.hpp"
#include "providers/twitch/twitchchannel.hpp"
using namespace chatterino::providers::twitch;
namespace chatterino {
namespace singletons {
@@ -88,8 +90,7 @@ QStringList CommandManager::getCommands()
return this->commandsStringList;
}
QString CommandManager::execCommand(const QString &text, ChannelPtr channel,
bool dryRun)
QString CommandManager::execCommand(const QString &text, ChannelPtr channel, bool dryRun)
{
QStringList words = text.split(' ', QString::SkipEmptyParts);
Command command;
@@ -104,7 +105,7 @@ QString CommandManager::execCommand(const QString &text, ChannelPtr channel,
QString commandName = words[0];
// check if default command exists
auto *twitchChannel = dynamic_cast<twitch::TwitchChannel *>(channel.get());
auto *twitchChannel = dynamic_cast<TwitchChannel *>(channel.get());
if (!dryRun && twitchChannel != nullptr) {
if (commandName == "/uptime") {
@@ -115,22 +116,26 @@ QString CommandManager::execCommand(const QString &text, ChannelPtr channel,
return "";
} else if (commandName == "/ignore" && words.size() >= 2) {
QString messageText;
// fourtf: ignore user
// QString messageText;
if (IrcManager::getInstance().tryAddIgnoredUser(words.at(1), messageText)) {
messageText = "Ignored user \"" + words.at(1) + "\".";
}
// if (IrcManager::getInstance().tryAddIgnoredUser(words.at(1),
// messageText)) {
// messageText = "Ignored user \"" + words.at(1) + "\".";
// }
channel->addMessage(messages::Message::createSystemMessage(messageText));
// channel->addMessage(messages::Message::createSystemMessage(messageText));
return "";
} else if (commandName == "/unignore") {
QString messageText;
// fourtf: ignore user
// QString messageText;
if (IrcManager::getInstance().tryRemoveIgnoredUser(words.at(1), messageText)) {
messageText = "Ignored user \"" + words.at(1) + "\".";
}
// if (IrcManager::getInstance().tryRemoveIgnoredUser(words.at(1),
// messageText)) {
// messageText = "Ignored user \"" + words.at(1) + "\".";
// }
channel->addMessage(messages::Message::createSystemMessage(messageText));
// channel->addMessage(messages::Message::createSystemMessage(messageText));
return "";
}
}
+3 -3
View File
@@ -13,18 +13,18 @@ CompletionManager &CompletionManager::getInstance()
return instance;
}
CompletionModel *CompletionManager::createModel(const std::string &channelName)
CompletionModel *CompletionManager::createModel(const QString &channelName)
{
auto it = this->models.find(channelName);
if (it != this->models.end()) {
return it->second;
}
CompletionModel *ret = new CompletionModel(qS(channelName));
CompletionModel *ret = new CompletionModel(channelName);
this->models[channelName] = ret;
return ret;
}
} // namespace singletons
} // namespace chatterino
}
+3 -3
View File
@@ -16,11 +16,11 @@ class CompletionManager
public:
static CompletionManager &getInstance();
CompletionModel *createModel(const std::string &channelName);
CompletionModel *createModel(const QString &channelName);
private:
std::map<std::string, CompletionModel *> models;
std::map<QString, CompletionModel *> models;
};
} // namespace singletons
} // namespace chatterino
}
+5 -6
View File
@@ -18,6 +18,7 @@
#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
using namespace chatterino::providers::twitch;
using namespace chatterino::messages;
namespace chatterino {
@@ -206,7 +207,7 @@ void EmoteManager::reloadFFZChannelEmotes(const QString &channelName,
});
}
util::ConcurrentMap<QString, twitch::EmoteValue *> &EmoteManager::getTwitchEmotes()
util::ConcurrentMap<QString, providers::twitch::EmoteValue *> &EmoteManager::getTwitchEmotes()
{
return _twitchEmotes;
}
@@ -420,9 +421,9 @@ QString EmoteManager::replaceShortCodes(const QString &text)
return ret;
}
void EmoteManager::refreshTwitchEmotes(const std::shared_ptr<twitch::TwitchUser> &user)
void EmoteManager::refreshTwitchEmotes(const std::shared_ptr<TwitchAccount> &user)
{
debug::Log("Loading Twitch emotes for user {}", user->getNickName());
debug::Log("Loading Twitch emotes for user {}", user->getUserName());
const auto &roomID = user->getUserId();
const auto &clientID = user->getOAuthClient();
@@ -462,9 +463,7 @@ void EmoteManager::refreshTwitchEmotes(const std::shared_ptr<twitch::TwitchUser>
}
emoteData.filled = true;
}
);
});
}
void EmoteManager::loadBTTVEmotes()
+5 -5
View File
@@ -4,9 +4,9 @@
#include "emojis.hpp"
#include "messages/image.hpp"
#include "providers/twitch/emotevalue.hpp"
#include "providers/twitch/twitchaccount.hpp"
#include "signalvector.hpp"
#include "twitch/emotevalue.hpp"
#include "twitch/twitchuser.hpp"
#include "util/concurrentmap.hpp"
#include "util/emotemap.hpp"
@@ -38,7 +38,7 @@ public:
void reloadFFZChannelEmotes(const QString &channelName,
std::weak_ptr<util::EmoteMap> channelEmoteMap);
util::ConcurrentMap<QString, twitch::EmoteValue *> &getTwitchEmotes();
util::ConcurrentMap<QString, providers::twitch::EmoteValue *> &getTwitchEmotes();
util::EmoteMap &getFFZEmotes();
util::EmoteMap &getChatterinoEmotes();
util::EmoteMap &getBTTVChannelEmoteFromCaches();
@@ -92,7 +92,7 @@ public:
std::vector<std::string> emojiShortCodes;
/// Twitch emotes
void refreshTwitchEmotes(const std::shared_ptr<twitch::TwitchUser> &user);
void refreshTwitchEmotes(const std::shared_ptr<providers::twitch::TwitchAccount> &user);
struct TwitchAccountEmoteData {
struct TwitchEmote {
@@ -112,7 +112,7 @@ public:
private:
// emote code
util::ConcurrentMap<QString, twitch::EmoteValue *> _twitchEmotes;
util::ConcurrentMap<QString, providers::twitch::EmoteValue *> _twitchEmotes;
// emote id
util::ConcurrentMap<long, util::EmoteData> _twitchEmoteFromCache;
+14 -13
View File
@@ -61,18 +61,19 @@ void CompletionModel::refresh()
}
// Channel-specific: Usernames
auto c = singletons::ChannelManager::getInstance().getTwitchChannel(this->channelName);
auto usernames = c->getUsernamesForCompletions();
for (const auto &name : usernames) {
assert(!name.displayName.isEmpty());
this->addString(name.displayName);
this->addString('@' + name.displayName);
// fourtf: only works with twitch chat
// auto c = singletons::ChannelManager::getInstance().getTwitchChannel(this->channelName);
// auto usernames = c->getUsernamesForCompletions();
// for (const auto &name : usernames) {
// assert(!name.displayName.isEmpty());
// this->addString(name.displayName);
// this->addString('@' + name.displayName);
if (!name.localizedName.isEmpty()) {
this->addString(name.localizedName);
this->addString('@' + name.localizedName);
}
}
// if (!name.localizedName.isEmpty()) {
// this->addString(name.localizedName);
// this->addString('@' + name.localizedName);
// }
// }
}
void CompletionModel::addString(const std::string &str)
@@ -86,5 +87,5 @@ void CompletionModel::addString(const QString &str)
// Always add a space at the end of completions
this->emotes.push_back(str + " ");
}
}
}
} // namespace singletons
} // namespace chatterino
-207
View File
@@ -1,207 +0,0 @@
#include "ircmessagehandler.hpp"
#include <memory>
#include "debug/log.hpp"
#include "messages/limitedqueue.hpp"
#include "messages/message.hpp"
#include "singletons/channelmanager.hpp"
#include "singletons/resourcemanager.hpp"
#include "singletons/windowmanager.hpp"
#include "twitch/twitchchannel.hpp"
using namespace chatterino::messages;
namespace chatterino {
namespace singletons {
namespace helper {
IrcMessageHandler::IrcMessageHandler(ChannelManager &_channelManager,
ResourceManager &_resourceManager)
: channelManager(_channelManager)
, resourceManager(_resourceManager)
{
}
IrcMessageHandler &IrcMessageHandler::getInstance()
{
static IrcMessageHandler instance(ChannelManager::getInstance(),
ResourceManager::getInstance());
return instance;
}
void IrcMessageHandler::handleRoomStateMessage(Communi::IrcMessage *message)
{
const auto &tags = message->tags();
auto iterator = tags.find("room-id");
if (iterator != tags.end()) {
auto roomID = iterator.value().toString();
auto channel =
this->channelManager.getTwitchChannel(QString(message->toData()).split("#").at(1));
auto twitchChannel = dynamic_cast<twitch::TwitchChannel *>(channel.get());
if (twitchChannel != nullptr) {
twitchChannel->setRoomID(roomID);
}
this->resourceManager.loadChannelData(roomID);
}
}
void IrcMessageHandler::handleClearChatMessage(Communi::IrcMessage *message)
{
assert(message->parameters().length() >= 1);
auto rawChannelName = message->parameter(0);
assert(rawChannelName.length() >= 2);
auto trimmedChannelName = rawChannelName.mid(1);
auto c = this->channelManager.getTwitchChannel(trimmedChannelName);
if (!c) {
debug::Log(
"[IrcMessageHandler:handleClearChatMessage] Channel {} not found in channel manager",
trimmedChannelName);
return;
}
// check if the chat has been cleared by a moderator
if (message->parameters().length() == 1) {
c->addMessage(Message::createSystemMessage("Chat has been cleared by a moderator."));
return;
}
assert(message->parameters().length() >= 2);
// get username, duration and message of the timed out user
QString username = message->parameter(1);
QString durationInSeconds, reason;
QVariant v = message->tag("ban-duration");
if (v.isValid()) {
durationInSeconds = v.toString();
}
v = message->tag("ban-reason");
if (v.isValid()) {
reason = v.toString();
}
// add the notice that the user has been timed out
LimitedQueueSnapshot<MessagePtr> snapshot = c->getMessageSnapshot();
bool addMessage = true;
int snapshotLength = snapshot.getLength();
for (int i = std::max(0, snapshotLength - 20); i < snapshotLength; i++) {
if (snapshot[i]->flags & Message::Timeout && snapshot[i]->loginName == username) {
MessagePtr replacement(
Message::createTimeoutMessage(username, durationInSeconds, reason, true));
c->replaceMessage(snapshot[i], replacement);
addMessage = false;
break;
}
}
if (addMessage) {
c->addMessage(Message::createTimeoutMessage(username, durationInSeconds, reason, false));
}
// disable the messages from the user
for (int i = 0; i < snapshotLength; i++) {
if (!(snapshot[i]->flags & Message::Timeout) && snapshot[i]->loginName == username) {
snapshot[i]->flags &= Message::Disabled;
}
}
// refresh all
WindowManager::getInstance().repaintVisibleChatWidgets(c.get());
}
void IrcMessageHandler::handleUserStateMessage(Communi::IrcMessage *message)
{
QVariant _mod = message->tag("mod");
if (_mod.isValid()) {
auto rawChannelName = message->parameters().at(0);
auto trimmedChannelName = rawChannelName.mid(1);
auto c = this->channelManager.getTwitchChannel(trimmedChannelName);
twitch::TwitchChannel *tc = dynamic_cast<twitch::TwitchChannel *>(c.get());
if (tc != nullptr) {
tc->setMod(_mod == "1");
}
}
}
void IrcMessageHandler::handleWhisperMessage(Communi::IrcMessage *message)
{
// TODO: Implement
}
void IrcMessageHandler::handleUserNoticeMessage(Communi::IrcMessage *message)
{
// do nothing
}
void IrcMessageHandler::handleModeMessage(Communi::IrcMessage *message)
{
auto channel = channelManager.getTwitchChannel(message->parameter(0).remove(0, 1));
if (message->parameter(1) == "+o") {
channel->modList.append(message->parameter(2));
} else if (message->parameter(1) == "-o") {
channel->modList.append(message->parameter(2));
}
}
void IrcMessageHandler::handleNoticeMessage(Communi::IrcNoticeMessage *message)
{
auto rawChannelName = message->target();
bool broadcast = rawChannelName.length() < 2;
MessagePtr msg = Message::createSystemMessage(message->content());
if (broadcast) {
this->channelManager.doOnAll([msg](const auto &c) {
c->addMessage(msg); //
});
return;
}
auto trimmedChannelName = rawChannelName.mid(1);
auto c = this->channelManager.getTwitchChannel(trimmedChannelName);
if (!c) {
debug::Log("[IrcManager:handleNoticeMessage] Channel {} not found in channel manager",
trimmedChannelName);
return;
}
c->addMessage(msg);
}
void IrcMessageHandler::handleWriteConnectionNoticeMessage(Communi::IrcNoticeMessage *message)
{
QVariant v = message->tag("msg-id");
if (!v.isValid()) {
return;
}
QString msg_id = v.toString();
static QList<QString> idsToSkip = {"timeout_success", "ban_success"};
if (idsToSkip.contains(msg_id)) {
// Already handled in the read-connection
return;
}
this->handleNoticeMessage(message);
}
} // namespace helper
} // namespace singletons
} // namespace chatterino
@@ -1,32 +0,0 @@
#pragma once
#include <IrcMessage>
namespace chatterino {
namespace singletons {
class ChannelManager;
class ResourceManager;
namespace helper {
class IrcMessageHandler
{
IrcMessageHandler(ChannelManager &channelManager, ResourceManager &resourceManager);
ChannelManager &channelManager;
ResourceManager &resourceManager;
public:
static IrcMessageHandler &getInstance();
void handleRoomStateMessage(Communi::IrcMessage *message);
void handleClearChatMessage(Communi::IrcMessage *message);
void handleUserStateMessage(Communi::IrcMessage *message);
void handleWhisperMessage(Communi::IrcMessage *message);
void handleUserNoticeMessage(Communi::IrcMessage *message);
void handleModeMessage(Communi::IrcMessage *message);
void handleNoticeMessage(Communi::IrcNoticeMessage *message);
void handleWriteConnectionNoticeMessage(Communi::IrcNoticeMessage *message);
};
}
}
}
+121 -412
View File
@@ -2,15 +2,14 @@
#include "channel.hpp"
#include "debug/log.hpp"
#include "messages/messageparseargs.hpp"
#include "providers/twitch/twitchaccount.hpp"
#include "providers/twitch/twitchmessagebuilder.hpp"
#include "singletons/accountmanager.hpp"
#include "singletons/channelmanager.hpp"
#include "singletons/emotemanager.hpp"
#include "singletons/helper/ircmessagehandler.hpp"
#include "singletons/resourcemanager.hpp"
#include "singletons/settingsmanager.hpp"
#include "singletons/windowmanager.hpp"
#include "twitch/twitchmessagebuilder.hpp"
#include "twitch/twitchuser.hpp"
#include "util/posttothread.hpp"
#include "util/urlfetch.hpp"
@@ -25,412 +24,122 @@
using namespace chatterino::messages;
namespace chatterino {
namespace singletons {
IrcManager::IrcManager(ChannelManager &_channelManager, ResourceManager &_resources,
AccountManager &_accountManager)
: channelManager(_channelManager)
, resources(_resources)
, accountManager(_accountManager)
{
this->account = accountManager.Twitch.getCurrent();
accountManager.Twitch.userChanged.connect([this]() {
this->setUser(accountManager.Twitch.getCurrent());
debug::Log("[IrcManager] Reconnecting to Twitch IRC as new user {}",
this->account->getUserName());
postToThread([this] { this->connect(); });
});
// Initialize the connections
this->writeConnection.reset(new Communi::IrcConnection);
this->writeConnection->moveToThread(QCoreApplication::instance()->thread());
QObject::connect(this->writeConnection.get(), &Communi::IrcConnection::messageReceived, this,
&IrcManager::writeConnectionMessageReceived);
this->readConnection.reset(new Communi::IrcConnection);
this->readConnection->moveToThread(QCoreApplication::instance()->thread());
// Listen to read connection message signals
QObject::connect(this->readConnection.get(), &Communi::IrcConnection::messageReceived, this,
&IrcManager::messageReceived);
QObject::connect(this->readConnection.get(), &Communi::IrcConnection::privateMessageReceived,
this, &IrcManager::privateMessageReceived);
QObject::connect(this->readConnection.get(), &Communi::IrcConnection::connected, this,
&IrcManager::onConnected);
QObject::connect(this->readConnection.get(), &Communi::IrcConnection::disconnected, this,
&IrcManager::onDisconnected);
// join and part chats on event
ChannelManager::getInstance().ircJoin.connect(
[this](const QString &name) { this->joinChannel(name); });
ChannelManager::getInstance().ircPart.connect(
[this](const QString &name) { this->partChannel(name); });
}
IrcManager &IrcManager::getInstance()
{
static IrcManager instance(ChannelManager::getInstance(),
singletons::ResourceManager::getInstance(),
AccountManager::getInstance());
return instance;
}
void IrcManager::setUser(std::shared_ptr<twitch::TwitchUser> newAccount)
{
this->account = newAccount;
}
void IrcManager::connect()
{
this->disconnect();
this->initializeConnection(this->writeConnection, false);
this->initializeConnection(this->readConnection, true);
// XXX(pajlada): Disabled the async_exec for now, because if we happen to run the
// `beginConnecting` function in a different thread than last time, we won't be able to connect
// because we can't clean up the previous connection properly
// async_exec([this] { beginConnecting(); });
this->beginConnecting();
}
void IrcManager::initializeConnection(const std::unique_ptr<Communi::IrcConnection> &connection,
bool isReadConnection)
{
assert(this->account);
QString username = this->account->getUserName();
QString oauthClient = this->account->getOAuthClient();
QString oauthToken = this->account->getOAuthToken();
if (!oauthToken.startsWith("oauth:")) {
oauthToken.prepend("oauth:");
}
connection->setUserName(username);
connection->setNickName(username);
connection->setRealName(username);
if (!this->account->isAnon()) {
connection->setPassword(oauthToken);
this->refreshIgnoredUsers(username, oauthClient, oauthToken);
}
if (isReadConnection) {
connection->sendCommand(
Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership"));
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/commands"));
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/tags"));
} else {
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/tags"));
connection->sendCommand(
Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership"));
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/commands"));
}
connection->setHost("irc.chat.twitch.tv");
connection->setPort(6667);
}
void IrcManager::refreshIgnoredUsers(const QString &username, const QString &oauthClient,
const QString &oauthToken)
{
QString nextLink = "https://api.twitch.tv/kraken/users/" + username + "/blocks?limit=" + 100 +
"&client_id=" + oauthClient;
QNetworkAccessManager *manager = new QNetworkAccessManager();
QNetworkRequest req(QUrl(nextLink + "&oauth_token=" + oauthToken));
QNetworkReply *reply = manager->get(req);
QObject::connect(reply, &QNetworkReply::finished, [=] {
this->twitchBlockedUsersMutex.lock();
this->twitchBlockedUsers.clear();
this->twitchBlockedUsersMutex.unlock();
QByteArray data = reply->readAll();
QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
QJsonObject root = jsonDoc.object();
// nextLink =
// root.value("this->links").toObject().value("next").toString();
auto blocks = root.value("blocks").toArray();
this->twitchBlockedUsersMutex.lock();
for (QJsonValue block : blocks) {
QJsonObject user = block.toObject().value("user").toObject();
// displaythis->name
this->twitchBlockedUsers.insert(user.value("name").toString().toLower(), true);
}
this->twitchBlockedUsersMutex.unlock();
manager->deleteLater();
});
}
void IrcManager::beginConnecting()
{
std::lock_guard<std::mutex> locker(this->connectionMutex);
for (auto &channel : this->channelManager.getItems()) {
this->writeConnection->sendRaw("JOIN #" + channel->name);
this->readConnection->sendRaw("JOIN #" + channel->name);
}
this->writeConnection->open();
this->readConnection->open();
this->connected();
}
void IrcManager::disconnect()
{
std::lock_guard<std::mutex> locker(this->connectionMutex);
this->readConnection->close();
this->writeConnection->close();
}
void IrcManager::sendMessage(const QString &channelName, QString message)
{
QString trimmedMessage = message.trimmed();
if (trimmedMessage.isEmpty()) {
return;
}
this->connectionMutex.lock();
if (this->writeConnection) {
this->writeConnection->sendRaw("PRIVMSG #" + channelName + " :" + trimmedMessage);
}
this->connectionMutex.unlock();
}
void IrcManager::joinChannel(const QString &channelName)
{
this->connectionMutex.lock();
if (this->readConnection && this->writeConnection) {
this->readConnection->sendRaw("JOIN #" + channelName);
this->writeConnection->sendRaw("JOIN #" + channelName);
}
this->connectionMutex.unlock();
}
void IrcManager::partChannel(const QString &channelName)
{
this->connectionMutex.lock();
if (this->readConnection && this->writeConnection) {
this->readConnection->sendRaw("PART #" + channelName);
this->writeConnection->sendRaw("PART #" + channelName);
}
this->connectionMutex.unlock();
}
void IrcManager::privateMessageReceived(Communi::IrcPrivateMessage *message)
{
this->onPrivateMessage.invoke(message);
auto c = this->channelManager.getTwitchChannel(message->target().mid(1));
if (!c) {
return;
}
// auto xd = message->content();
// auto xd2 = message->toData();
// debug::Log("HEHE: {}", xd2.toStdString());
messages::MessageParseArgs args;
twitch::TwitchMessageBuilder builder(c.get(), message, args);
if (!builder.isIgnored()) {
messages::MessagePtr _message = builder.build();
if (_message->flags & messages::Message::Highlighted) {
singletons::ChannelManager::getInstance().mentionsChannel->addMessage(_message);
}
c->addMessage(_message);
}
}
void IrcManager::messageReceived(Communi::IrcMessage *message)
{
if (message->type() == Communi::IrcMessage::Type::Private) {
// We already have a handler for private messages
return;
}
const QString &command = message->command();
if (command == "ROOMSTATE") {
helper::IrcMessageHandler::getInstance().handleRoomStateMessage(message);
} else if (command == "CLEARCHAT") {
helper::IrcMessageHandler::getInstance().handleClearChatMessage(message);
} else if (command == "USERSTATE") {
helper::IrcMessageHandler::getInstance().handleUserStateMessage(message);
} else if (command == "WHISPER") {
helper::IrcMessageHandler::getInstance().handleWhisperMessage(message);
} else if (command == "USERNOTICE") {
helper::IrcMessageHandler::getInstance().handleUserNoticeMessage(message);
} else if (command == "MODE") {
helper::IrcMessageHandler::getInstance().handleModeMessage(message);
} else if (command == "NOTICE") {
helper::IrcMessageHandler::getInstance().handleNoticeMessage(
static_cast<Communi::IrcNoticeMessage *>(message));
}
}
void IrcManager::writeConnectionMessageReceived(Communi::IrcMessage *message)
{
switch (message->type()) {
case Communi::IrcMessage::Type::Notice: {
helper::IrcMessageHandler::getInstance().handleWriteConnectionNoticeMessage(
static_cast<Communi::IrcNoticeMessage *>(message));
} break;
}
}
// XXX: This does not fit in IrcManager
bool IrcManager::isTwitchUserBlocked(QString const &username)
{
QMutexLocker locker(&this->twitchBlockedUsersMutex);
auto iterator = this->twitchBlockedUsers.find(username);
return iterator != this->twitchBlockedUsers.end();
}
// XXX: This does not fit in IrcManager
bool IrcManager::tryAddIgnoredUser(QString const &username, QString &errorMessage)
{
assert(this->account);
QUrl url("https://api.twitch.tv/kraken/users/" + this->account->getUserName() + "/blocks/" +
username + "?oauth_token=" + this->account->getOAuthToken() +
"&client_id=" + this->account->getOAuthClient());
QNetworkRequest request(url);
auto reply = this->networkAccessManager.put(request, QByteArray());
reply->waitForReadyRead(10000);
if (reply->error() == QNetworkReply::NoError) {
this->twitchBlockedUsersMutex.lock();
this->twitchBlockedUsers.insert(username, true);
this->twitchBlockedUsersMutex.unlock();
return true;
}
reply->deleteLater();
errorMessage = "Error while ignoring user \"" + username + "\": " + reply->errorString();
return false;
}
// XXX: This does not fit in IrcManager
void IrcManager::addIgnoredUser(QString const &username)
{
QString errorMessage;
if (!tryAddIgnoredUser(username, errorMessage)) {
// TODO: Implement IrcManager::addIgnoredUser
}
}
// XXX: This does not fit in IrcManager
bool IrcManager::tryRemoveIgnoredUser(QString const &username, QString &errorMessage)
{
assert(this->account);
QUrl url("https://api.twitch.tv/kraken/users/" + this->account->getUserName() + "/blocks/" +
username + "?oauth_token=" + this->account->getOAuthToken() +
"&client_id=" + this->account->getOAuthClient());
QNetworkRequest request(url);
auto reply = this->networkAccessManager.deleteResource(request);
reply->waitForReadyRead(10000);
if (reply->error() == QNetworkReply::NoError) {
this->twitchBlockedUsersMutex.lock();
this->twitchBlockedUsers.remove(username);
this->twitchBlockedUsersMutex.unlock();
return true;
}
reply->deleteLater();
errorMessage = "Error while unignoring user \"" + username + "\": " + reply->errorString();
return false;
}
// XXX: This does not fit in IrcManager
void IrcManager::removeIgnoredUser(QString const &username)
{
QString errorMessage;
if (!tryRemoveIgnoredUser(username, errorMessage)) {
// TODO: Implement IrcManager::removeIgnoredUser
}
}
void IrcManager::onConnected()
{
MessagePtr connMsg = Message::createSystemMessage("connected to chat");
MessagePtr reconnMsg = Message::createSystemMessage("reconnected to chat");
this->channelManager.doOnAll([connMsg, reconnMsg](ChannelPtr channel) {
assert(channel);
LimitedQueueSnapshot<MessagePtr> snapshot = channel->getMessageSnapshot();
bool replaceMessage =
snapshot.getLength() > 0 &&
snapshot[snapshot.getLength() - 1]->flags & Message::DisconnectedMessage;
if (replaceMessage) {
channel->replaceMessage(snapshot[snapshot.getLength() - 1], reconnMsg);
return;
}
channel->addMessage(connMsg);
});
}
void IrcManager::onDisconnected()
{
MessagePtr msg = Message::createSystemMessage("disconnected from chat");
msg->flags &= Message::DisconnectedMessage;
this->channelManager.doOnAll([msg](ChannelPtr channel) {
assert(channel);
channel->addMessage(msg);
});
}
Communi::IrcConnection *IrcManager::getReadConnection()
{
return this->readConnection.get();
}
void IrcManager::addFakeMessage(const QString &data)
{
auto fakeMessage = Communi::IrcMessage::fromData(data.toUtf8(), this->readConnection.get());
this->privateMessageReceived(qobject_cast<Communi::IrcPrivateMessage *>(fakeMessage));
}
} // namespace singletons
} // namespace chatterino
// void IrcManager::refreshIgnoredUsers(const QString &username, const QString &oauthClient,
// const QString &oauthToken)
//{
// QString nextLink = "https://api.twitch.tv/kraken/users/" + username + "/blocks?limit=" + 100 +
// "&client_id=" + oauthClient;
//
// QNetworkAccessManager *manager = new QNetworkAccessManager();
// QNetworkRequest req(QUrl(nextLink + "&oauth_token=" + oauthToken));
// QNetworkReply *reply = manager->get(req);
//
// QObject::connect(reply, &QNetworkReply::finished, [=] {
// this->twitchBlockedUsersMutex.lock();
// this->twitchBlockedUsers.clear();
// this->twitchBlockedUsersMutex.unlock();
//
// QByteArray data = reply->readAll();
// QJsonDocument jsonDoc(QJsonDocument::fromJson(data));
// QJsonObject root = jsonDoc.object();
//
// // nextLink =
// // root.value("this->links").toObject().value("next").toString();
//
// auto blocks = root.value("blocks").toArray();
//
// this->twitchBlockedUsersMutex.lock();
// for (QJsonValue block : blocks) {
// QJsonObject user = block.toObject().value("user").toObject();
// // displaythis->name
// this->twitchBlockedUsers.insert(user.value("name").toString().toLower(), true);
// }
// this->twitchBlockedUsersMutex.unlock();
//
// manager->deleteLater();
// });
//}
//
//// XXX: This does not fit in IrcManager
// bool IrcManager::isTwitchUserBlocked(QString const &username)
//{
// QMutexLocker locker(&this->twitchBlockedUsersMutex);
//
// auto iterator = this->twitchBlockedUsers.find(username);
//
// return iterator != this->twitchBlockedUsers.end();
//}
//
//// XXX: This does not fit in IrcManager
// bool IrcManager::tryAddIgnoredUser(QString const &username, QString &errorMessage)
//{
// assert(this->account);
//
// QUrl url("https://api.twitch.tv/kraken/users/" + this->account->getUserName() + "/blocks/" +
// username + "?oauth_token=" + this->account->getOAuthToken() +
// "&client_id=" + this->account->getOAuthClient());
//
// QNetworkRequest request(url);
// auto reply = this->networkAccessManager.put(request, QByteArray());
// reply->waitForReadyRead(10000);
//
// if (reply->error() == QNetworkReply::NoError) {
// this->twitchBlockedUsersMutex.lock();
// this->twitchBlockedUsers.insert(username, true);
// this->twitchBlockedUsersMutex.unlock();
//
// return true;
// }
//
// reply->deleteLater();
//
// errorMessage = "Error while ignoring user \"" + username + "\": " + reply->errorString();
//
// return false;
//}
//
//// XXX: This does not fit in IrcManager
// void IrcManager::addIgnoredUser(QString const &username)
//{
// QString errorMessage;
// if (!tryAddIgnoredUser(username, errorMessage)) {
// // TODO: Implement IrcManager::addIgnoredUser
// }
//}
//
//// XXX: This does not fit in IrcManager
// bool IrcManager::tryRemoveIgnoredUser(QString const &username, QString &errorMessage)
//{
// assert(this->account);
//
// QUrl url("https://api.twitch.tv/kraken/users/" + this->account->getUserName() + "/blocks/" +
// username + "?oauth_token=" + this->account->getOAuthToken() +
// "&client_id=" + this->account->getOAuthClient());
//
// QNetworkRequest request(url);
// auto reply = this->networkAccessManager.deleteResource(request);
// reply->waitForReadyRead(10000);
//
// if (reply->error() == QNetworkReply::NoError) {
// this->twitchBlockedUsersMutex.lock();
// this->twitchBlockedUsers.remove(username);
// this->twitchBlockedUsersMutex.unlock();
//
// return true;
// }
//
// reply->deleteLater();
//
// errorMessage = "Error while unignoring user \"" + username + "\": " + reply->errorString();
//
// return false;
//}
//
//// XXX: This does not fit in IrcManager
// void IrcManager::removeIgnoredUser(QString const &username)
//{
// QString errorMessage;
// if (!tryRemoveIgnoredUser(username, errorMessage)) {
// // TODO: Implement IrcManager::removeIgnoredUser
// }
//}
+10 -92
View File
@@ -1,95 +1,13 @@
#pragma once
// bool isTwitchUserBlocked(QString const &username);
// bool tryAddIgnoredUser(QString const &username, QString &errorMessage);
// void addIgnoredUser(QString const &username);
// bool tryRemoveIgnoredUser(QString const &username, QString &errorMessage);
// void removeIgnoredUser(QString const &username);
#define TWITCH_MAX_MESSAGELENGTH 500
// QMap<QString, bool> twitchBlockedUsers;
// QMutex twitchBlockedUsersMutex;
#include "messages/message.hpp"
#include "twitch/twitchuser.hpp"
// QNetworkAccessManager networkAccessManager;
#include <ircconnection.h>
#include <IrcMessage>
#include <QMap>
#include <QMutex>
#include <QNetworkAccessManager>
#include <QString>
#include <pajlada/signals/signal.hpp>
#include <memory>
#include <mutex>
namespace chatterino {
namespace singletons {
class ChannelManager;
class ResourceManager;
class AccountManager;
class WindowManager;
class IrcManager : public QObject
{
IrcManager(ChannelManager &channelManager, ResourceManager &resources,
AccountManager &accountManager);
public:
static IrcManager &getInstance();
void connect();
void disconnect();
bool isTwitchUserBlocked(QString const &username);
bool tryAddIgnoredUser(QString const &username, QString &errorMessage);
void addIgnoredUser(QString const &username);
bool tryRemoveIgnoredUser(QString const &username, QString &errorMessage);
void removeIgnoredUser(QString const &username);
void sendMessage(const QString &channelName, QString message);
void joinChannel(const QString &channelName);
void partChannel(const QString &channelName);
void setUser(std::shared_ptr<twitch::TwitchUser> newAccount);
pajlada::Signals::Signal<Communi::IrcPrivateMessage *> onPrivateMessage;
void privateMessageReceived(Communi::IrcPrivateMessage *message);
boost::signals2::signal<void()> connected;
Communi::IrcConnection *getReadConnection();
/// Debug function
void addFakeMessage(const QString &data);
private:
ChannelManager &channelManager;
ResourceManager &resources;
AccountManager &accountManager;
// variables
std::shared_ptr<twitch::TwitchUser> account = nullptr;
std::unique_ptr<Communi::IrcConnection> writeConnection = nullptr;
std::unique_ptr<Communi::IrcConnection> readConnection = nullptr;
std::mutex connectionMutex;
QMap<QString, bool> twitchBlockedUsers;
QMutex twitchBlockedUsersMutex;
QNetworkAccessManager networkAccessManager;
void initializeConnection(const std::unique_ptr<Communi::IrcConnection> &connection,
bool isReadConnection);
void refreshIgnoredUsers(const QString &username, const QString &oauthClient,
const QString &oauthToken);
void beginConnecting();
void messageReceived(Communi::IrcMessage *message);
void writeConnectionMessageReceived(Communi::IrcMessage *message);
void onConnected();
void onDisconnected();
};
} // namespace singletons
} // namespace chatterino
// void refreshIgnoredUsers(const QString &username, const QString &oauthClient,
// const QString &oauthToken);