Merge branch '4tf'

This commit is contained in:
fourtf
2018-08-06 18:41:30 +02:00
197 changed files with 3807 additions and 2801 deletions
+55 -73
View File
@@ -6,9 +6,10 @@
#include "controllers/ignores/IgnoreController.hpp"
#include "controllers/moderationactions/ModerationActions.hpp"
#include "controllers/taggedusers/TaggedUsersController.hpp"
#include "providers/bttv/BttvEmotes.hpp"
#include "providers/ffz/FfzEmotes.hpp"
#include "providers/twitch/PubsubClient.hpp"
#include "providers/twitch/TwitchServer.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Fonts.hpp"
#include "singletons/Logging.hpp"
#include "singletons/NativeMessaging.hpp"
@@ -24,69 +25,75 @@
namespace chatterino {
static std::atomic<bool> isAppConstructed{false};
static std::atomic<bool> isAppInitialized{false};
static Application *staticApp = nullptr;
Application *Application::instance = nullptr;
// this class is responsible for handling the workflow of Chatterino
// It will create the instances of the major classes, and connect their signals to each other
Application::Application(int _argc, char **_argv)
: argc_(_argc)
, argv_(_argv)
Application::Application(Settings &_settings, Paths &_paths)
: settings(&_settings)
, paths(&_paths)
, resources(&this->emplace<Resources2>())
, themes(&this->emplace<Theme>())
, fonts(&this->emplace<Fonts>())
, emotes(&this->emplace<Emotes>())
, windows(&this->emplace<WindowManager>())
, accounts(&this->emplace<AccountController>())
, commands(&this->emplace<CommandController>())
, highlights(&this->emplace<HighlightController>())
, ignores(&this->emplace<IgnoreController>())
, taggedUsers(&this->emplace<TaggedUsersController>())
, moderationActions(&this->emplace<ModerationActions>())
, twitch2(&this->emplace<TwitchServer>())
, logging(&this->emplace<Logging>())
{
getSettings()->initialize();
getSettings()->load();
}
this->instance = this;
void Application::construct()
{
assert(isAppConstructed == false);
isAppConstructed = true;
this->fonts->fontChanged.connect([this]() { this->windows->layoutChannelViews(); });
// 1. Instantiate all classes
this->settings = getSettings();
this->paths = getPaths();
this->addSingleton(this->themes = new Theme);
this->addSingleton(this->windows = new WindowManager);
this->addSingleton(this->logging = new Logging);
this->addSingleton(this->commands = new CommandController);
this->addSingleton(this->highlights = new HighlightController);
this->addSingleton(this->ignores = new IgnoreController);
this->addSingleton(this->taggedUsers = new TaggedUsersController);
this->addSingleton(this->accounts = new AccountController);
this->addSingleton(this->emotes = new Emotes);
this->addSingleton(this->fonts = new Fonts);
this->addSingleton(this->resources = new Resources);
this->addSingleton(this->moderationActions = new ModerationActions);
this->addSingleton(this->twitch2 = new TwitchServer);
this->twitch.server = this->twitch2;
this->twitch.pubsub = this->twitch2->pubsub;
}
void Application::instantiate(int argc, char **argv)
{
assert(staticApp == nullptr);
staticApp = new Application(argc, argv);
}
void Application::initialize()
void Application::initialize(Settings &settings, Paths &paths)
{
assert(isAppInitialized == false);
isAppInitialized = true;
// 2. Initialize/load classes
for (Singleton *singleton : this->singletons_) {
singleton->initialize(*this);
for (auto &singleton : this->singletons_) {
singleton->initialize(settings, paths);
}
// XXX
this->windows->updateWordTypeMask();
this->initNm();
this->initPubsub();
}
int Application::run(QApplication &qtApp)
{
assert(isAppInitialized);
this->twitch.server->connect();
this->windows->getMainWindow().show();
return qtApp.exec();
}
void Application::save()
{
for (auto &singleton : this->singletons_) {
singleton->save();
}
}
void Application::initNm()
{
#ifdef Q_OS_WIN
#ifdef QT_DEBUG
#ifdef C_DEBUG_NM
@@ -98,7 +105,10 @@ void Application::initialize()
this->nativeMessaging->openGuiMessageQueue();
#endif
#endif
}
void Application::initPubsub()
{
this->twitch.pubsub->signals_.whisper.sent.connect([](const auto &msg) {
Log("WHISPER SENT LOL"); //
});
@@ -197,39 +207,11 @@ void Application::initialize()
RequestModerationActions();
}
int Application::run(QApplication &qtApp)
{
// Start connecting to the IRC Servers (Twitch only for now)
this->twitch.server->connect();
// Show main window
this->windows->getMainWindow().show();
return qtApp.exec();
}
void Application::save()
{
for (Singleton *singleton : this->singletons_) {
singleton->save();
}
}
void Application::addSingleton(Singleton *singleton)
{
this->singletons_.push_back(singleton);
}
Application *getApp()
{
assert(staticApp != nullptr);
assert(Application::instance != nullptr);
return staticApp;
}
bool appInitialized()
{
return isAppInitialized;
return Application::instance;
}
} // namespace chatterino
+35 -35
View File
@@ -1,13 +1,13 @@
#pragma once
#include "common/Singleton.hpp"
#include "singletons/Resources.hpp"
#include <QApplication>
#include <memory>
namespace chatterino {
class Singleton;
class TwitchServer;
class PubSub;
@@ -24,45 +24,47 @@ class Logging;
class Paths;
class AccountManager;
class Emotes;
class NativeMessaging;
class Settings;
class Fonts;
class Resources;
class Application
{
Application(int _argc, char **_argv);
std::vector<std::unique_ptr<Singleton>> singletons_;
int argc_;
char **argv_;
public:
static void instantiate(int argc_, char **argv_);
static Application *instance;
~Application() = delete;
Application(Settings &settings, Paths &paths);
void construct();
void initialize();
void initialize(Settings &settings, Paths &paths);
void load();
void save();
int run(QApplication &qtApp);
friend void test();
[[deprecated("use getSettings() instead")]] Settings *settings = nullptr;
[[deprecated("use getPaths() instead")]] Paths *paths = nullptr;
Settings *const settings = nullptr;
Paths *const paths = nullptr;
Resources2 *const resources;
Theme *themes = nullptr;
WindowManager *windows = nullptr;
Logging *logging = nullptr;
CommandController *commands = nullptr;
HighlightController *highlights = nullptr;
IgnoreController *ignores = nullptr;
TaggedUsersController *taggedUsers = nullptr;
AccountController *accounts = nullptr;
Emotes *emotes = nullptr;
NativeMessaging *nativeMessaging = nullptr;
Fonts *fonts = nullptr;
Resources *resources = nullptr;
ModerationActions *moderationActions = nullptr;
TwitchServer *twitch2 = nullptr;
Theme *const themes = nullptr;
Fonts *const fonts = nullptr;
Emotes *const emotes = nullptr;
WindowManager *const windows = nullptr;
AccountController *const accounts = nullptr;
CommandController *const commands = nullptr;
HighlightController *const highlights = nullptr;
IgnoreController *const ignores = nullptr;
TaggedUsersController *const taggedUsers = nullptr;
ModerationActions *const moderationActions = nullptr;
TwitchServer *const twitch2 = nullptr;
[[deprecated]] Logging *const logging = nullptr;
/// Provider-specific
struct {
@@ -70,22 +72,20 @@ public:
[[deprecated("use twitch2->pubsub instead")]] PubSub *pubsub = nullptr;
} twitch;
void save();
// Special application mode that only initializes the native messaging host
static void runNativeMessagingHost();
private:
void addSingleton(Singleton *singleton);
void initPubsub();
void initNm();
int argc_;
char **argv_;
std::vector<Singleton *> singletons_;
template <typename T, typename = std::enable_if_t<std::is_base_of<Singleton, T>::value>>
T &emplace()
{
auto t = new T;
this->singletons_.push_back(std::unique_ptr<T>(t));
return *t;
}
};
Application *getApp();
bool appInitialized();
} // namespace chatterino
+88
View File
@@ -0,0 +1,88 @@
#include "BrowserExtension.hpp"
#include "singletons/NativeMessaging.hpp"
#include <QStringList>
#include <QTimer>
#include <fstream>
#include <iostream>
#include <memory>
#ifdef Q_OS_WIN
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#endif
namespace chatterino {
namespace {
void initFileMode()
{
#ifdef Q_OS_WIN
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
}
void runLoop(NativeMessagingClient &client)
{
while (true) {
char size_c[4];
std::cin.read(size_c, 4);
if (std::cin.eof()) {
break;
}
uint32_t size = *reinterpret_cast<uint32_t *>(size_c);
#if 0
bool bigEndian = isBigEndian();
// To avoid breaking strict-aliasing rules and potentially inducing undefined behaviour, the following code can be run instead
uint32_t size = 0;
if (bigEndian) {
size = size_c[3] | static_cast<uint32_t>(size_c[2]) << 8 |
static_cast<uint32_t>(size_c[1]) << 16 | static_cast<uint32_t>(size_c[0]) << 24;
} else {
size = size_c[0] | static_cast<uint32_t>(size_c[1]) << 8 |
static_cast<uint32_t>(size_c[2]) << 16 | static_cast<uint32_t>(size_c[3]) << 24;
}
#endif
std::unique_ptr<char[]> b(new char[size + 1]);
std::cin.read(b.get(), size);
*(b.get() + size) = '\0';
client.sendMessage(QByteArray::fromRawData(b.get(), static_cast<int32_t>(size)));
}
}
} // namespace
bool shouldRunBrowserExtensionHost(const QStringList &args)
{
return args.size() > 0 &&
(args[0].startsWith("chrome-extension://") || args[0].endsWith(".json"));
}
void runBrowserExtensionHost()
{
initFileMode();
std::atomic<bool> ping(false);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&ping] {
if (!ping.exchange(false)) {
_Exit(0);
}
});
timer.setInterval(11000);
timer.start();
NativeMessagingClient client;
runLoop(client);
}
} // namespace chatterino
+10
View File
@@ -0,0 +1,10 @@
#pragma once
class QStringList;
namespace chatterino {
bool shouldRunBrowserExtensionHost(const QStringList &args);
void runBrowserExtensionHost();
} // namespace chatterino
+130
View File
@@ -0,0 +1,130 @@
#include "RunGui.hpp"
#include <QApplication>
#include <QFile>
#include <QPalette>
#include <QStyleFactory>
#include "Application.hpp"
#include "common/NetworkManager.hpp"
#include "singletons/Paths.hpp"
#include "singletons/Updates.hpp"
#include "widgets/dialogs/LastRunCrashDialog.hpp"
#ifdef C_USE_BREAKPAD
#include <QBreakpadHandler.h>
#endif
// void initQt();
// void installCustomPalette();
// void showLastCrashDialog();
// void createRunningFile(const QString &path);
// void removeRunningFile(const QString &path);
namespace chatterino {
namespace {
void installCustomPalette()
{
// borrowed from
// https://stackoverflow.com/questions/15035767/is-the-qt-5-dark-fusion-theme-available-for-windows
QPalette darkPalette = qApp->palette();
darkPalette.setColor(QPalette::Window, QColor(22, 22, 22));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, QColor(127, 127, 127));
darkPalette.setColor(QPalette::Base, QColor("#333"));
darkPalette.setColor(QPalette::AlternateBase, QColor("#444"));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127));
darkPalette.setColor(QPalette::Dark, QColor(35, 35, 35));
darkPalette.setColor(QPalette::Shadow, QColor(20, 20, 20));
darkPalette.setColor(QPalette::Button, QColor(70, 70, 70));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127));
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(80, 80, 80));
darkPalette.setColor(QPalette::HighlightedText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(127, 127, 127));
qApp->setPalette(darkPalette);
}
void initQt()
{
// set up the QApplication flags
QApplication::setAttribute(Qt::AA_Use96Dpi, true);
#ifdef Q_OS_WIN32
QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true);
#endif
QApplication::setStyle(QStyleFactory::create("Fusion"));
installCustomPalette();
}
void showLastCrashDialog()
{
#ifndef C_DISABLE_CRASH_DIALOG
LastRunCrashDialog dialog;
switch (dialog.exec()) {
case QDialog::Accepted: {
}; break;
default: {
_exit(0);
}
}
#endif
}
void createRunningFile(const QString &path)
{
QFile runningFile(path);
runningFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
runningFile.flush();
runningFile.close();
}
void removeRunningFile(const QString &path)
{
QFile::remove(path);
}
} // namespace
void runGui(QApplication &a, Paths &paths, Settings &settings)
{
chatterino::NetworkManager::init();
chatterino::Updates::getInstance().checkForUpdates();
#ifdef C_USE_BREAKPAD
QBreakpadInstance.setDumpPath(app->paths->settingsFolderPath + "/Crashes");
#endif
// Running file
auto runningPath = paths.miscDirectory + "/running_" + paths.applicationFilePathHash;
if (QFile::exists(runningPath)) {
showLastCrashDialog();
} else {
createRunningFile(runningPath);
}
Application app(settings, paths);
app.initialize(settings, paths);
app.run(a);
app.save();
removeRunningFile(runningPath);
pajlada::Settings::SettingManager::gSave();
chatterino::NetworkManager::deinit();
_exit(0);
}
} // namespace chatterino
+10
View File
@@ -0,0 +1,10 @@
#pragma once
class QApplication;
namespace chatterino {
class Paths;
class Settings;
void runGui(QApplication &a, Paths &paths, Settings &settings);
} // namespace chatterino
+44
View File
@@ -0,0 +1,44 @@
#include "ResourcesAutogen.hpp"
namespace chatterino {
Resources2::Resources2()
{
this->avatars.fourtf = QPixmap(":/avatars/fourtf.png");
this->avatars.pajlada = QPixmap(":/avatars/pajlada.png");
this->buttons.ban = QPixmap(":/buttons/ban.png");
this->buttons.banRed = QPixmap(":/buttons/banRed.png");
this->buttons.menuDark = QPixmap(":/buttons/menuDark.png");
this->buttons.menuLight = QPixmap(":/buttons/menuLight.png");
this->buttons.mod = QPixmap(":/buttons/mod.png");
this->buttons.modModeDisabled = QPixmap(":/buttons/modModeDisabled.png");
this->buttons.modModeDisabled2 = QPixmap(":/buttons/modModeDisabled2.png");
this->buttons.modModeEnabled = QPixmap(":/buttons/modModeEnabled.png");
this->buttons.modModeEnabled2 = QPixmap(":/buttons/modModeEnabled2.png");
this->buttons.timeout = QPixmap(":/buttons/timeout.png");
this->buttons.unban = QPixmap(":/buttons/unban.png");
this->buttons.unmod = QPixmap(":/buttons/unmod.png");
this->buttons.update = QPixmap(":/buttons/update.png");
this->buttons.updateError = QPixmap(":/buttons/updateError.png");
this->error = QPixmap(":/error.png");
this->icon = QPixmap(":/icon.png");
this->pajaDank = QPixmap(":/pajaDank.png");
this->settings.aboutlogo = QPixmap(":/settings/aboutlogo.png");
this->split.down = QPixmap(":/split/down.png");
this->split.left = QPixmap(":/split/left.png");
this->split.move = QPixmap(":/split/move.png");
this->split.right = QPixmap(":/split/right.png");
this->split.up = QPixmap(":/split/up.png");
this->twitch.admin = QPixmap(":/twitch/admin.png");
this->twitch.broadcaster = QPixmap(":/twitch/broadcaster.png");
this->twitch.cheer1 = QPixmap(":/twitch/cheer1.png");
this->twitch.globalmod = QPixmap(":/twitch/globalmod.png");
this->twitch.moderator = QPixmap(":/twitch/moderator.png");
this->twitch.prime = QPixmap(":/twitch/prime.png");
this->twitch.staff = QPixmap(":/twitch/staff.png");
this->twitch.subscriber = QPixmap(":/twitch/subscriber.png");
this->twitch.turbo = QPixmap(":/twitch/turbo.png");
this->twitch.verified = QPixmap(":/twitch/verified.png");
}
} // namespace chatterino
+57
View File
@@ -0,0 +1,57 @@
#include <QPixmap>
#include "common/Singleton.hpp"
namespace chatterino {
class Resources2 : public Singleton {
public:
Resources2();
struct {
QPixmap fourtf;
QPixmap pajlada;
} avatars;
struct {
QPixmap ban;
QPixmap banRed;
QPixmap menuDark;
QPixmap menuLight;
QPixmap mod;
QPixmap modModeDisabled;
QPixmap modModeDisabled2;
QPixmap modModeEnabled;
QPixmap modModeEnabled2;
QPixmap timeout;
QPixmap unban;
QPixmap unmod;
QPixmap update;
QPixmap updateError;
} buttons;
QPixmap error;
QPixmap icon;
QPixmap pajaDank;
struct {
QPixmap aboutlogo;
} settings;
struct {
QPixmap down;
QPixmap left;
QPixmap move;
QPixmap right;
QPixmap up;
} split;
struct {
QPixmap admin;
QPixmap broadcaster;
QPixmap cheer1;
QPixmap globalmod;
QPixmap moderator;
QPixmap prime;
QPixmap staff;
QPixmap subscriber;
QPixmap turbo;
QPixmap verified;
} twitch;
};
} // namespace chatterino
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <QHash>
#include <QString>
#include <functional>
#define QStringAlias(name) \
namespace chatterino { \
struct name { \
QString string; \
bool operator==(const name &other) const \
{ \
return this->string == other.string; \
} \
bool operator!=(const name &other) const \
{ \
return this->string != other.string; \
} \
}; \
} /* namespace chatterino */ \
namespace std { \
template <> \
struct hash<chatterino::name> { \
size_t operator()(const chatterino::name &s) const \
{ \
return qHash(s.string); \
} \
}; \
} /* namespace std */
QStringAlias(UserName);
QStringAlias(UserId);
QStringAlias(Url);
QStringAlias(Tooltip);
+10 -5
View File
@@ -17,9 +17,9 @@
namespace chatterino {
Channel::Channel(const QString &_name, Type type)
: name(_name)
, completionModel(this->name)
Channel::Channel(const QString &name, Type type)
: completionModel(name)
, name_(name)
, type_(type)
{
QObject::connect(&this->clearCompletionModelTimer_, &QTimer::timeout, [this]() {
@@ -38,6 +38,11 @@ Channel::Type Channel::getType() const
return this->type_;
}
const QString &Channel::getName() const
{
return this->name_;
}
bool Channel::isTwitchChannel() const
{
return this->type_ >= Type::Twitch && this->type_ < Type::TwitchEnd;
@@ -45,7 +50,7 @@ bool Channel::isTwitchChannel() const
bool Channel::isEmpty() const
{
return this->name.isEmpty();
return this->name_.isEmpty();
}
LimitedQueueSnapshot<MessagePtr> Channel::getMessageSnapshot()
@@ -66,7 +71,7 @@ void Channel::addMessage(MessagePtr message)
// FOURTF: change this when adding more providers
if (this->isTwitchChannel()) {
app->logging->addMessage(this->name, message);
app->logging->addMessage(this->name_, message);
}
if (this->messages_.pushBack(message, deleted)) {
+2 -1
View File
@@ -41,6 +41,7 @@ public:
pajlada::Signals::NoArgSignal destroyed;
Type getType() const;
const QString &getName() const;
bool isTwitchChannel() const;
virtual bool isEmpty() const;
LimitedQueueSnapshot<MessagePtr> getMessageSnapshot();
@@ -52,7 +53,6 @@ public:
void replaceMessage(MessagePtr message, MessagePtr replacement);
virtual void addRecentChatter(const std::shared_ptr<Message> &message);
QString name;
QStringList modList;
virtual bool canSendMessage() const;
@@ -72,6 +72,7 @@ protected:
virtual void onConnected();
private:
const QString name_;
LimitedQueue<MessagePtr> messages_;
Type type_;
QTimer clearCompletionModelTimer_;
+9 -9
View File
@@ -1,9 +1,13 @@
#pragma once
#include "common/Aliases.hpp"
#include "common/Outcome.hpp"
#include "common/ProviderId.hpp"
#include "debug/Log.hpp"
#include <QString>
#include <QWidget>
#include <boost/optional.hpp>
#include <boost/preprocessor.hpp>
#include <string>
@@ -27,14 +31,10 @@ const Qt::KeyboardModifiers showResizeHandlesModifiers = Qt::ControlModifier;
static const char *ANONYMOUS_USERNAME_LABEL ATTR_UNUSED = " - anonymous - ";
#define return_if(condition) \
if ((condition)) { \
return; \
}
#define return_unless(condition) \
if (!(condition)) { \
return; \
}
template <typename T>
std::weak_ptr<T> weakOf(T *element)
{
return element->shared_from_this();
}
} // namespace chatterino
+35 -29
View File
@@ -2,8 +2,10 @@
#include "Application.hpp"
#include "common/Common.hpp"
#include "controllers/accounts/AccountController.hpp"
#include "controllers/commands/CommandController.hpp"
#include "debug/Log.hpp"
#include "providers/twitch/TwitchServer.hpp"
#include "singletons/Emotes.hpp"
#include <QtAlgorithms>
@@ -107,41 +109,45 @@ void CompletionModel::refresh()
auto app = getApp();
// User-specific: Twitch Emotes
// TODO: Fix this so it properly updates with the proper api. oauth token needs proper scope
for (const auto &m : app->emotes->twitch.emotes) {
for (const auto &emoteName : m.second.emoteCodes) {
if (auto account = app->accounts->twitch.getCurrent()) {
for (const auto &emote : account->accessEmotes()->allEmoteNames) {
// XXX: No way to discern between a twitch global emote and sub emote right now
this->addString(emoteName, TaggedString::Type::TwitchGlobalEmote);
this->addString(emote.string, TaggedString::Type::TwitchGlobalEmote);
}
}
// Global: BTTV Global Emotes
std::vector<QString> &bttvGlobalEmoteCodes = app->emotes->bttv.globalEmoteCodes;
for (const auto &m : bttvGlobalEmoteCodes) {
this->addString(m, TaggedString::Type::BTTVGlobalEmote);
// // Global: BTTV Global Emotes
// std::vector<QString> &bttvGlobalEmoteCodes = app->emotes->bttv.globalEmoteNames_;
// for (const auto &m : bttvGlobalEmoteCodes) {
// this->addString(m, TaggedString::Type::BTTVGlobalEmote);
// }
// // Global: FFZ Global Emotes
// std::vector<QString> &ffzGlobalEmoteCodes = app->emotes->ffz.globalEmoteCodes;
// for (const auto &m : ffzGlobalEmoteCodes) {
// this->addString(m, TaggedString::Type::FFZGlobalEmote);
// }
// Channel emotes
if (auto channel = dynamic_cast<TwitchChannel *>(
getApp()->twitch2->getChannelOrEmptyByID(this->channelName_).get())) {
auto bttv = channel->accessBttvEmotes();
// auto it = bttv->begin();
// for (const auto &emote : *bttv) {
// }
// std::vector<QString> &bttvChannelEmoteCodes =
// app->emotes->bttv.channelEmoteName_[this->channelName_];
// for (const auto &m : bttvChannelEmoteCodes) {
// this->addString(m, TaggedString::Type::BTTVChannelEmote);
// }
// Channel-specific: FFZ Channel Emotes
for (const auto &emote : *channel->accessFfzEmotes()) {
this->addString(emote.second->name.string, TaggedString::Type::FFZChannelEmote);
}
}
// Global: FFZ Global Emotes
std::vector<QString> &ffzGlobalEmoteCodes = app->emotes->ffz.globalEmoteCodes;
for (const auto &m : ffzGlobalEmoteCodes) {
this->addString(m, TaggedString::Type::FFZGlobalEmote);
}
// Channel-specific: BTTV Channel Emotes
std::vector<QString> &bttvChannelEmoteCodes =
app->emotes->bttv.channelEmoteCodes[this->channelName_];
for (const auto &m : bttvChannelEmoteCodes) {
this->addString(m, TaggedString::Type::BTTVChannelEmote);
}
// Channel-specific: FFZ Channel Emotes
std::vector<QString> &ffzChannelEmoteCodes =
app->emotes->ffz.channelEmoteCodes[this->channelName_];
for (const auto &m : ffzChannelEmoteCodes) {
this->addString(m, TaggedString::Type::FFZChannelEmote);
}
// Global: Emojis
// Emojis
const auto &emojiShortCodes = app->emotes->emojis.shortCodes;
for (const auto &m : emojiShortCodes) {
this->addString(":" + m + ":", TaggedString::Type::Emoji);
+2
View File
@@ -10,6 +10,8 @@
namespace chatterino {
class TwitchChannel;
class CompletionModel : public QAbstractListModel
{
struct TaggedString {
+32 -32
View File
@@ -5,42 +5,42 @@
namespace chatterino {
EmoteData::EmoteData(Image *image)
: image1x(image)
{
}
// EmoteData::EmoteData(Image *image)
// : image1x(image)
//{
//}
// Emotes must have a 1x image to be valid
bool EmoteData::isValid() const
{
return this->image1x != nullptr;
}
//// Emotes must have a 1x image to be valid
// bool EmoteData::isValid() const
//{
// return this->image1x != nullptr;
//}
Image *EmoteData::getImage(float scale) const
{
int quality = getApp()->settings->preferredEmoteQuality;
// Image *EmoteData::getImage(float scale) const
//{
// int quality = getApp()->settings->preferredEmoteQuality;
if (quality == 0) {
scale *= getApp()->settings->emoteScale.getValue();
quality = [&] {
if (scale <= 1)
return 1;
if (scale <= 2)
return 2;
return 3;
}();
}
// if (quality == 0) {
// scale *= getApp()->settings->emoteScale.getValue();
// quality = [&] {
// if (scale <= 1)
// return 1;
// if (scale <= 2)
// return 2;
// return 3;
// }();
// }
Image *_image;
if (quality == 3 && this->image3x != nullptr) {
_image = this->image3x;
} else if (quality >= 2 && this->image2x != nullptr) {
_image = this->image2x;
} else {
_image = this->image1x;
}
// Image *_image;
// if (quality == 3 && this->image3x != nullptr) {
// _image = this->image3x;
// } else if (quality >= 2 && this->image2x != nullptr) {
// _image = this->image2x;
// } else {
// _image = this->image1x;
// }
return _image;
}
// return _image;
//}
} // namespace chatterino
+13 -13
View File
@@ -5,23 +5,23 @@
namespace chatterino {
struct EmoteData {
EmoteData() = default;
// struct EmoteData {
// EmoteData() = default;
EmoteData(Image *image);
// EmoteData(Image *image);
// Emotes must have a 1x image to be valid
bool isValid() const;
Image *getImage(float scale) const;
// // Emotes must have a 1x image to be valid
// bool isValid() const;
// Image *getImage(float scale) const;
// Link to the emote page i.e. https://www.frankerfacez.com/emoticon/144722-pajaCringe
QString pageLink;
// // Link to the emote page i.e. https://www.frankerfacez.com/emoticon/144722-pajaCringe
// QString pageLink;
Image *image1x = nullptr;
Image *image2x = nullptr;
Image *image3x = nullptr;
};
// Image *image1x = nullptr;
// Image *image2x = nullptr;
// Image *image3x = nullptr;
//};
using EmoteMap = ConcurrentMap<QString, EmoteData>;
// using EmoteMap = ConcurrentMap<QString, EmoteData>;
} // namespace chatterino
+3 -1
View File
@@ -2,13 +2,15 @@
#include <functional>
#include "Common.hpp"
class QNetworkReply;
namespace chatterino {
class NetworkResult;
using NetworkSuccessCallback = std::function<bool(NetworkResult)>;
using NetworkSuccessCallback = std::function<Outcome(NetworkResult)>;
using NetworkErrorCallback = std::function<bool(int)>;
using NetworkReplyCreatedCallback = std::function<void(QNetworkReply *)>;
+11
View File
@@ -2,12 +2,23 @@
#include "Application.hpp"
#include "singletons/Paths.hpp"
#include "util/DebugCount.hpp"
#include <QCryptographicHash>
#include <QFile>
namespace chatterino {
NetworkData::NetworkData()
{
DebugCount::increase("NetworkData");
}
NetworkData::~NetworkData()
{
DebugCount::decrease("NetworkData");
}
QString NetworkData::getHash()
{
if (this->hash_.isEmpty()) {
+3
View File
@@ -13,6 +13,9 @@ namespace chatterino {
class NetworkResult;
struct NetworkData {
NetworkData();
~NetworkData();
QNetworkRequest request_;
const QObject *caller_ = nullptr;
bool useQuickLoadCache_{};
+20 -22
View File
@@ -129,7 +129,7 @@ void NetworkRequest::execute()
}
}
bool NetworkRequest::tryLoadCachedFile()
Outcome NetworkRequest::tryLoadCachedFile()
{
auto app = getApp();
@@ -137,24 +137,24 @@ bool NetworkRequest::tryLoadCachedFile()
if (!cachedFile.exists()) {
// File didn't exist
return false;
return Failure;
}
if (!cachedFile.open(QIODevice::ReadOnly)) {
// File could not be opened
return false;
return Failure;
}
QByteArray bytes = cachedFile.readAll();
NetworkResult result(bytes);
bool success = this->data->onSuccess_(result);
auto outcome = this->data->onSuccess_(result);
cachedFile.close();
// XXX: If success is false, we should invalidate the cache file somehow/somewhere
return success;
return outcome;
}
void NetworkRequest::doRequest()
@@ -167,20 +167,21 @@ void NetworkRequest::doRequest()
this->timer->start();
auto onUrlRequested = [data = this->data, timer = this->timer, worker]() mutable {
QNetworkReply *reply = nullptr;
switch (data->requestType_) {
case NetworkRequestType::Get: {
reply = NetworkManager::NaM.get(data->request_);
} break;
auto reply = [&]() -> QNetworkReply * {
switch (data->requestType_) {
case NetworkRequestType::Get:
return NetworkManager::NaM.get(data->request_);
case NetworkRequestType::Put: {
reply = NetworkManager::NaM.put(data->request_, data->payload_);
} break;
case NetworkRequestType::Put:
return NetworkManager::NaM.put(data->request_, data->payload_);
case NetworkRequestType::Delete: {
reply = NetworkManager::NaM.deleteResource(data->request_);
} break;
}
case NetworkRequestType::Delete:
return NetworkManager::NaM.deleteResource(data->request_);
default:
return nullptr;
}
}();
if (reply == nullptr) {
Log("Unhandled request type");
@@ -201,8 +202,6 @@ void NetworkRequest::doRequest()
data->onReplyCreated_(reply);
}
bool directAction = (data->caller_ == nullptr);
auto handleReply = [data, timer, reply]() mutable {
// TODO(pajlada): A reply was received, kill the timeout timer
if (reply->error() != QNetworkReply::NetworkError::NoError) {
@@ -222,8 +221,7 @@ void NetworkRequest::doRequest()
};
if (data->caller_ != nullptr) {
QObject::connect(worker, &NetworkWorker::doneUrl, data->caller_,
std::move(handleReply));
QObject::connect(worker, &NetworkWorker::doneUrl, data->caller_, handleReply);
QObject::connect(reply, &QNetworkReply::finished, worker, [worker]() mutable {
emit worker->doneUrl();
@@ -231,7 +229,7 @@ void NetworkRequest::doRequest()
});
} else {
QObject::connect(reply, &QNetworkReply::finished, worker,
[handleReply = std::move(handleReply), worker]() mutable {
[handleReply, worker]() mutable {
handleReply();
delete worker;
+2 -2
View File
@@ -33,7 +33,7 @@ public:
explicit NetworkRequest(const std::string &url,
NetworkRequestType requestType = NetworkRequestType::Get);
NetworkRequest(QUrl url, NetworkRequestType requestType = NetworkRequestType::Get);
explicit NetworkRequest(QUrl url, NetworkRequestType requestType = NetworkRequestType::Get);
~NetworkRequest();
@@ -58,7 +58,7 @@ private:
// Returns true if the file was successfully loaded from cache
// Returns false if the cache file either didn't exist, or it contained "invalid" data
// "invalid" is specified by the onSuccess callback
bool tryLoadCachedFile();
Outcome tryLoadCachedFile();
void doRequest();
+1 -1
View File
@@ -38,7 +38,7 @@ rapidjson::Document NetworkResult::parseRapidJson() const
return ret;
}
QByteArray NetworkResult::getData() const
const QByteArray &NetworkResult::getData() const
{
return this->data_;
}
+4 -3
View File
@@ -7,14 +7,15 @@ namespace chatterino {
class NetworkResult
{
QByteArray data_;
public:
NetworkResult(const QByteArray &data);
QJsonObject parseJson() const;
rapidjson::Document parseRapidJson() const;
QByteArray getData() const;
const QByteArray &getData() const;
private:
QByteArray data_;
};
} // namespace chatterino
+14 -1
View File
@@ -1,5 +1,7 @@
#pragma once
#include <type_traits>
namespace chatterino {
template <typename T>
@@ -23,7 +25,7 @@ public:
return element_;
}
T &operator*() const
typename std::add_lvalue_reference<T>::type operator*() const
{
assert(this->hasElement());
@@ -52,6 +54,17 @@ public:
return this->hasElement();
}
bool operator!() const
{
return !this->hasElement();
}
template <typename X = T, typename = std::enable_if_t<!std::is_const<X>::value>>
operator NullablePtr<const T>() const
{
return NullablePtr<const T>(this->element_);
}
private:
T *element_;
};
+51
View File
@@ -0,0 +1,51 @@
#pragma once
namespace chatterino {
struct SuccessTag {
};
struct FailureTag {
};
const SuccessTag Success{};
const FailureTag Failure{};
class Outcome
{
public:
Outcome(SuccessTag)
: success_(true)
{
}
Outcome(FailureTag)
: success_(false)
{
}
explicit operator bool() const
{
return this->success_;
}
bool operator!() const
{
return !this->success_;
}
bool operator==(const Outcome &other) const
{
return this->success_ == other.success_;
}
bool operator!=(const Outcome &other) const
{
return !this->operator==(other);
}
private:
bool success_;
};
} // namespace chatterino
+7 -3
View File
@@ -4,14 +4,18 @@
namespace chatterino {
class Application;
class Settings;
class Paths;
class Singleton : boost::noncopyable
{
public:
virtual void initialize(Application &app)
virtual ~Singleton() = default;
virtual void initialize(Settings &settings, Paths &paths)
{
(void)(app);
(void)(settings);
(void)(paths);
}
virtual void save()
+29 -28
View File
@@ -10,52 +10,52 @@ class AccessGuard
{
public:
AccessGuard(T &element, std::mutex &mutex)
: element_(element)
, mutex_(mutex)
: element_(&element)
, mutex_(&mutex)
{
this->mutex_.lock();
this->mutex_->lock();
}
AccessGuard(AccessGuard<T> &&other)
: element_(other.element_)
, mutex_(other.mutex_)
{
other.isValid_ = false;
}
AccessGuard<T> &operator=(AccessGuard<T> &&other)
{
other.isValid_ = false;
this->element_ = other.element_;
this->mutex_ = other.element_;
}
~AccessGuard()
{
this->mutex_.unlock();
if (this->isValid_) this->mutex_->unlock();
}
const T *operator->() const
{
return &this->element_;
}
T *operator->()
{
return &this->element_;
}
const T &operator*() const
T *operator->() const
{
return this->element_;
}
T &operator*()
T &operator*() const
{
return this->element_;
}
T clone() const
{
return T(this->element_);
return *this->element_;
}
private:
T &element_;
std::mutex &mutex_;
T *element_;
std::mutex *mutex_;
bool isValid_ = true;
};
template <typename T>
class UniqueAccess
{
public:
template <typename X = decltype(T())>
// template <typename X = decltype(T())>
UniqueAccess()
: element_(T())
{
@@ -83,14 +83,15 @@ public:
return *this;
}
AccessGuard<T> access()
AccessGuard<T> access() const
{
return AccessGuard<T>(this->element_, this->mutex_);
}
const AccessGuard<T> access() const
template <typename X = T, typename = std::enable_if_t<!std::is_const_v<X>>>
AccessGuard<const X> accessConst() const
{
return AccessGuard<T>(this->element_, this->mutex_);
return AccessGuard<const T>(this->element_, this->mutex_);
}
private:
@@ -33,7 +33,7 @@ AccountController::AccountController()
});
}
void AccountController::initialize(Application &app)
void AccountController::initialize(Settings &settings, Paths &paths)
{
this->twitch.load();
}
@@ -11,16 +11,19 @@
namespace chatterino {
class Settings;
class Paths;
class AccountModel;
class AccountController : public Singleton
class AccountController final : public Singleton
{
public:
AccountController();
AccountModel *createModel(QObject *parent);
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
TwitchAccountManager twitch;
@@ -11,6 +11,7 @@
#include "providers/twitch/TwitchServer.hpp"
#include "singletons/Paths.hpp"
#include "singletons/Settings.hpp"
#include "util/CombinePath.hpp"
#include "widgets/dialogs/LogsPopup.hpp"
#include <QApplication>
@@ -44,15 +45,14 @@ CommandController::CommandController()
this->items.itemRemoved.connect(addFirstMatchToMap);
}
void CommandController::initialize(Application &app)
void CommandController::initialize(Settings &, Paths &paths)
{
this->load();
this->load(paths);
}
void CommandController::load()
void CommandController::load(Paths &paths)
{
auto app = getApp();
this->filePath_ = app->paths->settingsDirectory + "/commands.txt";
this->filePath_ = combinePath(paths.settingsDirectory, "commands.txt");
QFile textFile(this->filePath_);
if (!textFile.open(QIODevice::ReadOnly)) {
@@ -140,7 +140,7 @@ QString CommandController::execCommand(const QString &text, ChannelPtr channel,
app->twitch.server->whispersChannel->addMessage(b.getMessage());
app->twitch.server->getWriteConnection()->sendRaw("PRIVMSG #jtv :" + text + "\r\n");
app->twitch.server->sendMessage("jtv", text);
if (getSettings()->inlineWhispers) {
app->twitch.server->forEachChannel(
@@ -10,11 +10,14 @@
#include "controllers/commands/Command.hpp"
namespace chatterino {
class Settings;
class Paths;
class Channel;
class CommandModel;
class CommandController : public Singleton
class CommandController final : public Singleton
{
public:
CommandController();
@@ -22,7 +25,7 @@ public:
QString execCommand(const QString &text, std::shared_ptr<Channel> channel, bool dryRun);
QStringList getDefaultTwitchCommandList();
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
virtual void save() override;
CommandModel *createModel(QObject *parent);
@@ -30,7 +33,7 @@ public:
UnsortedSignalVector<Command> items;
private:
void load();
void load(Paths &paths);
QMap<QString, Command> commandsMap_;
@@ -12,7 +12,7 @@ HighlightController::HighlightController()
{
}
void HighlightController::initialize(Application &app)
void HighlightController::initialize(Settings &settings, Paths &paths)
{
assert(!this->initialized_);
this->initialized_ = true;
@@ -10,16 +10,19 @@
namespace chatterino {
class Settings;
class Paths;
class UserHighlightModel;
class HighlightModel;
class HighlightBlacklistModel;
class HighlightController : public Singleton
class HighlightController final : public Singleton
{
public:
HighlightController();
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
UnsortedSignalVector<HighlightPhrase> phrases;
UnsortedSignalVector<HighlightBlacklistUser> blacklistedUsers;
+1 -1
View File
@@ -7,7 +7,7 @@
namespace chatterino {
void IgnoreController::initialize(Application &)
void IgnoreController::initialize(Settings &, Paths &)
{
assert(!this->initialized_);
this->initialized_ = true;
+5 -2
View File
@@ -8,12 +8,15 @@
namespace chatterino {
class Settings;
class Paths;
class IgnoreModel;
class IgnoreController : public Singleton
class IgnoreController final : public Singleton
{
public:
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
UnsortedSignalVector<IgnorePhrase> phrases;
@@ -1,5 +1,6 @@
#include "ModerationAction.hpp"
#include <QRegularExpression>
#include "Application.hpp"
#include "singletons/Resources.hpp"
@@ -57,7 +58,7 @@ ModerationAction::ModerationAction(const QString &action)
// this->_moderationActions.emplace_back(app->resources->buttonTimeout, str);
// }
} else if (action.startsWith("/ban ")) {
this->image_ = getApp()->resources->buttonBan;
this->image_ = Image::fromNonOwningPixmap(&getApp()->resources->buttons.ban);
} else {
QString xD = action;
@@ -75,10 +76,10 @@ bool ModerationAction::operator==(const ModerationAction &other) const
bool ModerationAction::isImage() const
{
return this->image_ != nullptr;
return bool(this->image_);
}
Image *ModerationAction::getImage() const
const boost::optional<ImagePtr> &ModerationAction::getImage() const
{
return this->image_;
}
@@ -1,14 +1,14 @@
#pragma once
#include <QString>
#include <boost/optional.hpp>
#include <pajlada/settings/serialize.hpp>
#include "messages/Image.hpp"
#include "util/RapidjsonHelpers.hpp"
namespace chatterino {
class Image;
class ModerationAction
{
public:
@@ -17,13 +17,13 @@ public:
bool operator==(const ModerationAction &other) const;
bool isImage() const;
Image *getImage() const;
const boost::optional<ImagePtr> &getImage() const;
const QString &getLine1() const;
const QString &getLine2() const;
const QString &getAction() const;
private:
Image *image_ = nullptr;
boost::optional<ImagePtr> image_;
QString line1_;
QString line2_;
QString action_;
@@ -12,7 +12,7 @@ ModerationActions::ModerationActions()
{
}
void ModerationActions::initialize(Application &app)
void ModerationActions::initialize(Settings &settings, Paths &paths)
{
assert(!this->initialized_);
this->initialized_ = true;
@@ -8,6 +8,9 @@
namespace chatterino {
class Settings;
class Paths;
class ModerationActionModel;
class ModerationActions final : public Singleton
@@ -15,7 +18,7 @@ class ModerationActions final : public Singleton
public:
ModerationActions();
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
UnsortedSignalVector<ModerationAction> items;
@@ -9,7 +9,7 @@ namespace chatterino {
class TaggedUsersModel;
class TaggedUsersController : public Singleton
class TaggedUsersController final : public Singleton
{
public:
TaggedUsersController();
+7
View File
@@ -14,4 +14,11 @@ inline void Log(const std::string &formatString, Args &&... args)
<< fS(formatString, std::forward<Args>(args)...).c_str();
}
template <typename... Args>
inline void Warn(const std::string &formatString, Args &&... args)
{
qWarning() << QTime::currentTime().toString("hh:mm:ss.zzz")
<< fS(formatString, std::forward<Args>(args)...).c_str();
}
} // namespace chatterino
+14 -207
View File
@@ -1,221 +1,28 @@
#include "Application.hpp"
#include "common/NetworkManager.hpp"
#include "singletons/NativeMessaging.hpp"
#include "BrowserExtension.hpp"
#include "RunGui.hpp"
#include "singletons/Paths.hpp"
#include "singletons/Updates.hpp"
#include "util/DebugCount.hpp"
#include "widgets/dialogs/LastRunCrashDialog.hpp"
#include "singletons/Settings.hpp"
#include <QAbstractNativeEventFilter>
#include <QApplication>
#include <QFile>
#include <QLibrary>
#include <QStringList>
#include <QStyleFactory>
#include <pajlada/settings/settingmanager.hpp>
#include <fstream>
#include <iostream>
using namespace chatterino;
#ifdef Q_OS_WIN
#include <fcntl.h>
#include <io.h>
#include <stdio.h>
#endif
#ifdef C_USE_BREAKPAD
#include <QBreakpadHandler.h>
#endif
int runGui(QApplication &a, int argc, char *argv[]);
void runNativeMessagingHost();
void installCustomPalette();
//
// Main entry point of the application.
// Decides if it should run in gui mode, daemon mode, ...
// Sets up the QApplication
//
int main(int argc, char *argv[])
int main(int argc, char **argv)
{
// set up the QApplication flags
QApplication::setAttribute(Qt::AA_Use96Dpi, true);
#ifdef Q_OS_WIN32
QApplication::setAttribute(Qt::AA_DisableHighDpiScaling, true);
#endif
// QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL, true);
// instanciate the QApplication
QApplication a(argc, argv);
// FOURTF: might get arguments from the commandline passed in the future
chatterino::Paths::initInstance();
// convert char[][] to QStringList
auto args = QStringList();
std::transform(argv + 1, argv + argc, std::back_inserter(args), [&](auto s) { return s; });
// read args
QStringList args;
for (int i = 1; i < argc; i++) {
args << argv[i];
}
// run native messaging host for the browser extension
if (args.size() > 0 &&
(args[0].startsWith("chrome-extension://") || args[0].endsWith(".json"))) {
runNativeMessagingHost();
return 0;
}
// run gui
return runGui(a, argc, argv);
}
int runGui(QApplication &a, int argc, char *argv[])
{
QApplication::setStyle(QStyleFactory::create("Fusion"));
installCustomPalette();
// Initialize NetworkManager
chatterino::NetworkManager::init();
// Check for upates
chatterino::Updates::getInstance().checkForUpdates();
// Initialize application
chatterino::Application::instantiate(argc, argv);
auto app = chatterino::getApp();
app->construct();
#ifdef C_USE_BREAKPAD
QBreakpadInstance.setDumpPath(app->paths->settingsFolderPath + "/Crashes");
#endif
auto &pathMan = *app->paths;
// Running file
auto runningPath = pathMan.miscDirectory + "/running_" + pathMan.applicationFilePathHash;
if (QFile::exists(runningPath)) {
#ifndef C_DISABLE_CRASH_DIALOG
chatterino::LastRunCrashDialog dialog;
switch (dialog.exec()) {
case QDialog::Accepted: {
}; break;
default: {
_exit(0);
}
}
#endif
// run in gui mode or browser extension host mode
if (shouldRunBrowserExtensionHost(args)) {
runBrowserExtensionHost();
} else {
QFile runningFile(runningPath);
Paths paths;
Settings settings(paths);
runningFile.open(QIODevice::WriteOnly | QIODevice::Truncate);
runningFile.flush();
runningFile.close();
}
app->initialize();
// Start the application
// This is a blocking call
app->run(a);
// We have finished our application, make sure we save stuff
app->save();
// Running file
QFile::remove(runningPath);
// Save settings
pajlada::Settings::SettingManager::gSave();
// Deinitialize NetworkManager (stop thread and wait for finish, should be instant)
chatterino::NetworkManager::deinit();
// None of the singletons has a proper destructor
_exit(0);
}
void runNativeMessagingHost()
{
auto *nm = new chatterino::NativeMessaging;
#ifdef Q_OS_WIN
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
#if 0
bool bigEndian = isBigEndian();
#endif
std::atomic<bool> ping(false);
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&ping] {
if (!ping.exchange(false)) {
_exit(0);
}
});
timer.setInterval(11000);
timer.start();
while (true) {
char size_c[4];
std::cin.read(size_c, 4);
if (std::cin.eof()) {
break;
}
uint32_t size = *reinterpret_cast<uint32_t *>(size_c);
#if 0
// To avoid breaking strict-aliasing rules and potentially inducing undefined behaviour, the following code can be run instead
uint32_t size = 0;
if (bigEndian) {
size = size_c[3] | static_cast<uint32_t>(size_c[2]) << 8 |
static_cast<uint32_t>(size_c[1]) << 16 | static_cast<uint32_t>(size_c[0]) << 24;
} else {
size = size_c[0] | static_cast<uint32_t>(size_c[1]) << 8 |
static_cast<uint32_t>(size_c[2]) << 16 | static_cast<uint32_t>(size_c[3]) << 24;
}
#endif
std::unique_ptr<char[]> b(new char[size + 1]);
std::cin.read(b.get(), size);
*(b.get() + size) = '\0';
nm->sendToGuiProcess(QByteArray::fromRawData(b.get(), static_cast<int32_t>(size)));
runGui(a, paths, settings);
}
}
void installCustomPalette()
{
// borrowed from
// https://stackoverflow.com/questions/15035767/is-the-qt-5-dark-fusion-theme-available-for-windows
QPalette darkPalette = qApp->palette();
darkPalette.setColor(QPalette::Window, QColor(22, 22, 22));
darkPalette.setColor(QPalette::WindowText, Qt::white);
darkPalette.setColor(QPalette::Text, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::WindowText, QColor(127, 127, 127));
darkPalette.setColor(QPalette::Base, QColor("#333"));
darkPalette.setColor(QPalette::AlternateBase, QColor("#444"));
darkPalette.setColor(QPalette::ToolTipBase, Qt::white);
darkPalette.setColor(QPalette::ToolTipText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::Text, QColor(127, 127, 127));
darkPalette.setColor(QPalette::Dark, QColor(35, 35, 35));
darkPalette.setColor(QPalette::Shadow, QColor(20, 20, 20));
darkPalette.setColor(QPalette::Button, QColor(70, 70, 70));
darkPalette.setColor(QPalette::ButtonText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, QColor(127, 127, 127));
darkPalette.setColor(QPalette::BrightText, Qt::red);
darkPalette.setColor(QPalette::Link, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218));
darkPalette.setColor(QPalette::Disabled, QPalette::Highlight, QColor(80, 80, 80));
darkPalette.setColor(QPalette::HighlightedText, Qt::white);
darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, QColor(127, 127, 127));
qApp->setPalette(darkPalette);
}
+75
View File
@@ -0,0 +1,75 @@
#include "Emote.hpp"
#include <unordered_map>
namespace chatterino {
bool operator==(const Emote &a, const Emote &b)
{
return std::tie(a.homePage, a.name, a.tooltip, a.images) ==
std::tie(b.homePage, b.name, b.tooltip, b.images);
}
bool operator!=(const Emote &a, const Emote &b)
{
return !(a == b);
}
// EmotePtr Emote::create(const EmoteData2 &data)
//{
//}
// EmotePtr Emote::create(EmoteData2 &&data)
//{
//}
// Emote::Emote(EmoteData2 &&data)
// : data_(data)
//{
//}
//
// Emote::Emote(const EmoteData2 &data)
// : data_(data)
//{
//}
//
// const Url &Emote::getHomePage() const
//{
// return this->data_.homePage;
//}
//
// const EmoteName &Emote::getName() const
//{
// return this->data_.name;
//}
//
// const Tooltip &Emote::getTooltip() const
//{
// return this->data_.tooltip;
//}
//
// const ImageSet &Emote::getImages() const
//{
// return this->data_.images;
//}
//
// const QString &Emote::getCopyString() const
//{
// return this->data_.name.string;
//}
//
// bool Emote::operator==(const Emote &other) const
//{
// auto &a = this->data_;
// auto &b = other.data_;
//
// return std::tie(a.homePage, a.name, a.tooltip, a.images) ==
// std::tie(b.homePage, b.name, b.tooltip, b.images);
//}
//
// bool Emote::operator!=(const Emote &other) const
//{
// return !this->operator==(other);
//}
} // namespace chatterino
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#include "messages/Image.hpp"
#include "messages/ImageSet.hpp"
#include <functional>
#include <memory>
#include <unordered_map>
QStringAlias(EmoteId);
QStringAlias(EmoteName);
namespace chatterino {
struct Emote {
EmoteName name;
ImageSet images;
Tooltip tooltip;
Url homePage;
// FOURTF: no solution yet, to be refactored later
const QString &getCopyString() const
{
return name.string;
}
};
bool operator==(const Emote &a, const Emote &b);
bool operator!=(const Emote &a, const Emote &b);
using EmotePtr = std::shared_ptr<const Emote>;
class EmoteMap : public std::unordered_map<EmoteName, EmotePtr>
{
};
using EmoteIdMap = std::unordered_map<EmoteId, EmotePtr>;
using WeakEmoteMap = std::unordered_map<EmoteName, std::weak_ptr<const Emote>>;
using WeakEmoteIdMap = std::unordered_map<EmoteId, std::weak_ptr<const Emote>>;
// struct EmoteData2 {
// EmoteName name;
// ImageSet images;
// Tooltip tooltip;
// Url homePage;
//};
//
// class Emote
//{
// public:
// Emote(EmoteData2 &&data);
// Emote(const EmoteData2 &data);
//
// const Url &getHomePage() const;
// const EmoteName &getName() const;
// const Tooltip &getTooltip() const;
// const ImageSet &getImages() const;
// const QString &getCopyString() const;
// bool operator==(const Emote &other) const;
// bool operator!=(const Emote &other) const;
//
// private:
// EmoteData2 data_;
//};
} // namespace chatterino
+93
View File
@@ -0,0 +1,93 @@
#pragma once
#include <QString>
#include <boost/optional.hpp>
#include <unordered_map>
#include <util/QStringHash.hpp>
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
namespace chatterino {
template <typename TKey>
class MapReplacement
{
public:
MapReplacement(std::unordered_map<TKey, EmotePtr> &items)
: oldItems_(items)
{
}
void add(const TKey &key, const Emote &data)
{
this->add(key, Emote(data));
}
void add(const TKey &key, Emote &&data)
{
auto it = this->oldItems_.find(key);
if (it != this->oldItems_.end() && *it->second == data) {
this->newItems_[key] = it->second;
} else {
this->newItems_[key] = std::make_shared<Emote>(std::move(data));
}
}
void apply()
{
this->oldItems_ = std::move(this->newItems_);
}
private:
std::unordered_map<TKey, EmotePtr> &oldItems_;
std::unordered_map<TKey, EmotePtr> newItems_;
};
template <typename TKey>
class EmoteCache
{
public:
using Iterator = typename std::unordered_map<TKey, EmotePtr>::iterator;
using ConstIterator = typename std::unordered_map<TKey, EmotePtr>::iterator;
Iterator begin()
{
return this->items_.begin();
}
ConstIterator begin() const
{
return this->items_.begin();
}
Iterator end()
{
return this->items_.end();
}
ConstIterator end() const
{
return this->items_.end();
}
boost::optional<EmotePtr> get(const TKey &key) const
{
auto it = this->items_.find(key);
if (it == this->items_.end())
return boost::none;
else
return it->second;
}
MapReplacement<TKey> makeReplacment()
{
return MapReplacement<TKey>(this->items_);
}
private:
std::unordered_map<TKey, EmotePtr> items_;
};
} // namespace chatterino
+44
View File
@@ -0,0 +1,44 @@
#include "EmoteMap.hpp"
#include "Application.hpp"
#include "singletons/Settings.hpp"
namespace chatterino {
// EmoteData::EmoteData(Image *image)
// : image1x(image)
//{
//}
//// Emotes must have a 1x image to be valid
// bool EmoteData::isValid() const
//{
// return this->image1x != nullptr;
//}
// Image *EmoteData::getImage(float scale) const
//{
// int quality = getApp()->settings->preferredEmoteQuality;
// if (quality == 0) {
// scale *= getApp()->settings->emoteScale.getValue();
// quality = [&] {
// if (scale <= 1) return 1;
// if (scale <= 2) return 2;
// return 3;
// }();
// }
// Image *_image;
// if (quality == 3 && this->image3x != nullptr) {
// _image = this->image3x;
// } else if (quality >= 2 && this->image2x != nullptr) {
// _image = this->image2x;
// } else {
// _image = this->image1x;
// }
// return _image;
//}
} // namespace chatterino
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "boost/optional.hpp"
#include "messages/Emote.hpp"
namespace chatterino {
// class EmoteMap
//{
// public:
// void add(Emote emote);
// void remove(const Emote &emote);
// void remove(const QString &name);
// private:
//};
// using EmoteMap = ConcurrentMap<QString, EmoteData>;
} // namespace chatterino
+249 -220
View File
@@ -2,6 +2,7 @@
#include "Application.hpp"
#include "common/NetworkRequest.hpp"
#include "debug/AssertInGuiThread.hpp"
#include "debug/Log.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/WindowManager.hpp"
@@ -18,259 +19,287 @@
#include <thread>
namespace chatterino {
namespace {
// Frame
Frame::Frame(const QPixmap *nonOwning, int duration)
: nonOwning_(nonOwning)
, duration_(duration)
{
}
bool Image::loadedEventQueued = false;
Frame::Frame(std::unique_ptr<QPixmap> owning, int duration)
: owning_(std::move(owning))
, duration_(duration)
{
}
Image::Image(const QString &url, qreal scale, const QString &name, const QString &tooltip,
const QMargins &margin, bool isHat)
: url(url)
, name(name)
, tooltip(tooltip)
, margin(margin)
, ishat(isHat)
, scale(scale)
int Frame::duration() const
{
return this->duration_;
}
const QPixmap *Frame::pixmap() const
{
if (this->nonOwning_) return this->nonOwning_;
return this->owning_.get();
}
// Frames
Frames::Frames()
{
DebugCount::increase("images");
}
Image::Image(QPixmap *image, qreal scale, const QString &name, const QString &tooltip,
const QMargins &margin, bool isHat)
: currentPixmap(image)
, name(name)
, tooltip(tooltip)
, margin(margin)
, ishat(isHat)
, scale(scale)
, isLoading(true)
, isLoaded(true)
Frames::Frames(std::vector<Frame> &&frames)
: items_(std::move(frames))
{
DebugCount::increase("images");
if (this->animated()) DebugCount::increase("animated images");
}
Image::~Image()
Frames::~Frames()
{
DebugCount::decrease("images");
if (this->animated()) DebugCount::decrease("animated images");
}
if (this->isAnimated()) {
DebugCount::decrease("animated images");
}
void Frames::advance()
{
this->timeOffset_ += GIF_FRAME_LENGTH;
if (this->isLoaded) {
DebugCount::decrease("loaded images");
while (true) {
this->index_ %= this->items_.size();
if (this->timeOffset_ > this->items_[this->index_].duration()) {
this->timeOffset_ -= this->items_[this->index_].duration();
this->index_ = (this->index_ + 1) % this->items_.size();
} else {
break;
}
}
}
void Image::loadImage()
bool Frames::animated() const
{
NetworkRequest req(this->getUrl());
req.setCaller(this);
req.setUseQuickLoadCache(true);
req.onSuccess([this](auto result) -> bool {
auto bytes = result.getData();
QByteArray copy = QByteArray::fromRawData(bytes.constData(), bytes.length());
QBuffer buffer(&copy);
buffer.open(QIODevice::ReadOnly);
return this->items_.size() > 1;
}
QImage image;
const QPixmap *Frames::current() const
{
if (this->items_.size() == 0) return nullptr;
return this->items_[this->index_].pixmap();
}
const QPixmap *Frames::first() const
{
if (this->items_.size() == 0) return nullptr;
return this->items_.front().pixmap();
}
// functions
std::vector<Frame> readFrames(QImageReader &reader, const Url &url)
{
std::vector<Frame> frames;
if (reader.imageCount() <= 0) {
Log("Error while reading image {}: '{}'", url.string, reader.errorString());
return frames;
}
QImage image;
for (int index = 0; index < reader.imageCount(); ++index) {
if (reader.read(&image)) {
auto pixmap = std::make_unique<QPixmap>(QPixmap::fromImage(image));
int duration = std::max(20, reader.nextImageDelay());
frames.push_back(Frame(std::move(pixmap), duration));
}
}
if (frames.size() != 0) {
Log("Error while reading image {}: '{}'", url.string, reader.errorString());
}
return frames;
}
void queueLoadedEvent()
{
static auto eventQueued = false;
if (!eventQueued) {
eventQueued = true;
QTimer::singleShot(250, [] {
getApp()->windows->incGeneration();
getApp()->windows->layoutChannelViews();
eventQueued = false;
});
}
}
} // namespace
// IMAGE2
std::atomic<bool> Image::loadedEventQueued{false};
ImagePtr Image::fromUrl(const Url &url, qreal scale)
{
static std::unordered_map<Url, std::weak_ptr<Image>> cache;
static std::mutex mutex;
std::lock_guard<std::mutex> lock(mutex);
auto shared = cache[url].lock();
if (!shared) {
cache[url] = shared = ImagePtr(new Image(url, scale));
} else {
Warn("same image loaded multiple times: {}", url.string);
}
return shared;
}
ImagePtr Image::fromOwningPixmap(std::unique_ptr<QPixmap> pixmap, qreal scale)
{
return ImagePtr(new Image(std::move(pixmap), scale));
}
ImagePtr Image::fromNonOwningPixmap(QPixmap *pixmap, qreal scale)
{
return ImagePtr(new Image(pixmap, scale));
}
ImagePtr Image::getEmpty()
{
static auto empty = ImagePtr(new Image);
return empty;
}
Image::Image()
: empty_(true)
{
}
Image::Image(const Url &url, qreal scale)
: url_(url)
, scale_(scale)
, shouldLoad_(true)
{
}
Image::Image(std::unique_ptr<QPixmap> owning, qreal scale)
: scale_(scale)
{
std::vector<Frame> vec;
vec.push_back(Frame(std::move(owning)));
this->frames_ = std::move(vec);
}
Image::Image(QPixmap *nonOwning, qreal scale)
: scale_(scale)
{
std::vector<Frame> vec;
vec.push_back(Frame(nonOwning));
this->frames_ = std::move(vec);
}
const Url &Image::url() const
{
return this->url_;
}
const QPixmap *Image::pixmap() const
{
assertInGuiThread();
if (this->shouldLoad_) {
const_cast<Image *>(this)->shouldLoad_ = false;
const_cast<Image *>(this)->load();
}
return this->frames_.current();
}
qreal Image::scale() const
{
return this->scale_;
}
bool Image::empty() const
{
return this->empty_;
}
bool Image::animated() const
{
assertInGuiThread();
return this->frames_.animated();
}
int Image::width() const
{
assertInGuiThread();
if (auto pixmap = this->frames_.first())
return pixmap->width() * this->scale_;
else
return 16;
}
int Image::height() const
{
assertInGuiThread();
if (auto pixmap = this->frames_.first())
return pixmap->height() * this->scale_;
else
return 16;
}
void Image::load()
{
NetworkRequest req(this->url().string);
req.setCaller(&this->object_);
req.setUseQuickLoadCache(true);
req.onSuccess([this, weak = weakOf(this)](auto result) -> Outcome {
assertInGuiThread();
auto shared = weak.lock();
if (!shared) return Failure;
// const cast since we are only reading from it
QBuffer buffer(const_cast<QByteArray *>(&result.getData()));
buffer.open(QIODevice::ReadOnly);
QImageReader reader(&buffer);
bool first = true;
this->frames_ = readFrames(reader, this->url());
return Success;
});
req.onError([this, weak = weakOf(this)](int) {
auto shared = weak.lock();
if (!shared) return false;
// clear stuff before loading the image again
this->allFrames.clear();
if (this->isAnimated()) {
DebugCount::decrease("animated images");
}
if (this->isLoaded) {
DebugCount::decrease("loaded images");
}
this->frames_ = std::vector<Frame>();
if (reader.imageCount() == -1) {
// An error occured in the reader
Log("An error occured reading the image: '{}'", reader.errorString());
Log("Image url: {}", this->url);
return false;
}
if (reader.imageCount() == 0) {
Log("Error: No images read in the buffer");
// No images read in the buffer. maybe a cache error?
return false;
}
for (int index = 0; index < reader.imageCount(); ++index) {
if (reader.read(&image)) {
auto pixmap = new QPixmap(QPixmap::fromImage(image));
if (first) {
first = false;
this->loadedPixmap = pixmap;
}
Image::FrameData data;
data.duration = std::max(20, reader.nextImageDelay());
data.image = pixmap;
this->allFrames.push_back(data);
}
}
if (this->allFrames.size() != reader.imageCount()) {
// Log("Error: Wrong amount of images read");
// One or more images failed to load from the buffer
// return false;
}
if (this->allFrames.size() > 1) {
if (!this->animated) {
postToThread([this] {
getApp()->emotes->gifTimer.signal.connect([=]() {
this->gifUpdateTimout();
}); // For some reason when Boost signal is in
// thread scope and thread deletes the signal
// doesn't work, so this is the fix.
});
}
this->animated = true;
DebugCount::increase("animated images");
}
this->currentPixmap = this->loadedPixmap;
this->isLoaded = true;
DebugCount::increase("loaded images");
if (!loadedEventQueued) {
loadedEventQueued = true;
QTimer::singleShot(500, [] {
getApp()->windows->incGeneration();
auto app = getApp();
app->windows->layoutChannelViews();
loadedEventQueued = false;
});
}
return true;
return false;
});
req.execute();
}
void Image::gifUpdateTimout()
bool Image::operator==(const Image &other) const
{
if (this->animated) {
this->currentFrameOffset += GIF_FRAME_LENGTH;
if (this->empty() && other.empty()) return true;
if (!this->url_.string.isEmpty() && this->url_ == other.url_) return true;
if (this->frames_.first() == other.frames_.first()) return true;
while (true) {
if (this->currentFrameOffset > this->allFrames.at(this->currentFrame).duration) {
this->currentFrameOffset -= this->allFrames.at(this->currentFrame).duration;
this->currentFrame = (this->currentFrame + 1) % this->allFrames.size();
} else {
break;
}
}
this->currentPixmap = this->allFrames[this->currentFrame].image;
}
return false;
}
const QPixmap *Image::getPixmap()
bool Image::operator!=(const Image &other) const
{
if (!this->isLoading) {
this->isLoading = true;
this->loadImage();
return nullptr;
}
if (this->isLoaded) {
return this->currentPixmap;
} else {
return nullptr;
}
}
qreal Image::getScale() const
{
return this->scale;
}
const QString &Image::getUrl() const
{
return this->url;
}
const QString &Image::getName() const
{
return this->name;
}
const QString &Image::getCopyString() const
{
if (this->copyString.isEmpty()) {
return this->name;
}
return this->copyString;
}
const QString &Image::getTooltip() const
{
return this->tooltip;
}
const QMargins &Image::getMargin() const
{
return this->margin;
}
bool Image::isAnimated() const
{
return this->animated;
}
bool Image::isHat() const
{
return this->ishat;
}
int Image::getWidth() const
{
if (this->currentPixmap == nullptr) {
return 16;
}
return this->currentPixmap->width();
}
int Image::getScaledWidth() const
{
return static_cast<int>((float)this->getWidth() * this->scale *
getApp()->settings->emoteScale.getValue());
}
int Image::getHeight() const
{
if (this->currentPixmap == nullptr) {
return 16;
}
return this->currentPixmap->height();
}
int Image::getScaledHeight() const
{
return static_cast<int>((float)this->getHeight() * this->scale *
getApp()->settings->emoteScale.getValue());
}
void Image::setCopyString(const QString &newCopyString)
{
this->copyString = newCopyString;
return !this->operator==(other);
}
} // namespace chatterino
+75 -54
View File
@@ -1,69 +1,90 @@
#pragma once
#include "common/Common.hpp"
#include <QPixmap>
#include <QString>
#include <boost/noncopyable.hpp>
#include <atomic>
#include <boost/noncopyable.hpp>
#include <memory>
#include <mutex>
#include "common/NullablePtr.hpp"
namespace chatterino {
class Image : public QObject, boost::noncopyable
namespace {
class Frame
{
public:
explicit Image(const QString &_url, qreal _scale = 1, const QString &_name = "",
const QString &_tooltip = "", const QMargins &_margin = QMargins(),
bool isHat = false);
explicit Frame(const QPixmap *nonOwning, int duration = 1);
explicit Frame(std::unique_ptr<QPixmap> owning, int duration = 1);
explicit Image(QPixmap *_currentPixmap, qreal _scale = 1, const QString &_name = "",
const QString &_tooltip = "", const QMargins &_margin = QMargins(),
bool isHat = false);
~Image();
const QPixmap *getPixmap();
qreal getScale() const;
const QString &getUrl() const;
const QString &getName() const;
const QString &getCopyString() const;
const QString &getTooltip() const;
const QMargins &getMargin() const;
bool isAnimated() const;
bool isHat() const;
int getWidth() const;
int getScaledWidth() const;
int getHeight() const;
int getScaledHeight() const;
void setCopyString(const QString &newCopyString);
const QPixmap *pixmap() const;
int duration() const;
private:
struct FrameData {
QPixmap *image;
int duration;
};
static bool loadedEventQueued;
QPixmap *currentPixmap = nullptr;
QPixmap *loadedPixmap = nullptr;
std::vector<FrameData> allFrames;
int currentFrame = 0;
int currentFrameOffset = 0;
QString url;
QString name;
QString copyString;
QString tooltip;
bool animated = false;
QMargins margin;
bool ishat;
qreal scale;
bool isLoading = false;
std::atomic<bool> isLoaded{false};
void loadImage();
void gifUpdateTimout();
const QPixmap *nonOwning_{nullptr};
std::unique_ptr<QPixmap> owning_{};
int duration_{};
};
class Frames
{
public:
Frames();
Frames(std::vector<Frame> &&frames);
~Frames();
Frames(Frames &&other) = default;
Frames &operator=(Frames &&other) = default;
bool animated() const;
void advance();
const QPixmap *current() const;
const QPixmap *first() const;
private:
std::vector<Frame> items_;
int index_{0};
int timeOffset_{0};
};
} // namespace
class Image;
using ImagePtr = std::shared_ptr<Image>;
class Image : public std::enable_shared_from_this<Image>, boost::noncopyable
{
public:
static ImagePtr fromUrl(const Url &url, qreal scale = 1);
static ImagePtr fromOwningPixmap(std::unique_ptr<QPixmap> pixmap, qreal scale = 1);
static ImagePtr fromNonOwningPixmap(QPixmap *pixmap, qreal scale = 1);
static ImagePtr getEmpty();
const Url &url() const;
const QPixmap *pixmap() const;
qreal scale() const;
bool empty() const;
int width() const;
int height() const;
bool animated() const;
bool operator==(const Image &image) const;
bool operator!=(const Image &image) const;
private:
Image();
Image(const Url &url, qreal scale);
Image(std::unique_ptr<QPixmap> owning, qreal scale);
Image(QPixmap *nonOwning, qreal scale);
void load();
Url url_{};
qreal scale_{1};
bool empty_{false};
bool shouldLoad_{false};
Frames frames_{};
QObject object_{};
static std::atomic<bool> loadedEventQueued;
};
} // namespace chatterino
+95
View File
@@ -0,0 +1,95 @@
#include "ImageSet.hpp"
#include "Application.hpp"
#include "singletons/Resources.hpp"
#include "singletons/Settings.hpp"
namespace chatterino {
ImageSet::ImageSet()
: imageX1_(Image::getEmpty())
, imageX2_(Image::getEmpty())
, imageX3_(Image::getEmpty())
{
}
ImageSet::ImageSet(const ImagePtr &image1, const ImagePtr &image2, const ImagePtr &image3)
: imageX1_(image1)
, imageX2_(image2)
, imageX3_(image3)
{
}
ImageSet::ImageSet(const Url &image1, const Url &image2, const Url &image3)
: imageX1_(Image::fromUrl(image1, 1))
, imageX2_(Image::fromUrl(image2, 0.5))
, imageX3_(Image::fromUrl(image3, 0.25))
{
}
void ImageSet::setImage1(const ImagePtr &image)
{
this->imageX1_ = image;
}
void ImageSet::setImage2(const ImagePtr &image)
{
this->imageX2_ = image;
}
void ImageSet::setImage3(const ImagePtr &image)
{
this->imageX3_ = image;
}
const ImagePtr &ImageSet::getImage1() const
{
return this->imageX1_;
}
const ImagePtr &ImageSet::getImage2() const
{
return this->imageX2_;
}
const ImagePtr &ImageSet::getImage3() const
{
return this->imageX3_;
}
const ImagePtr &ImageSet::getImage(float scale) const
{
int quality = getSettings()->preferredEmoteQuality;
if (!quality) {
if (scale > 3.999)
quality = 3;
else if (scale > 1.999)
quality = 2;
else
scale = 1;
}
if (!this->imageX3_->empty() && quality == 3) {
return this->imageX3_;
}
if (!this->imageX2_->empty() && quality == 2) {
return this->imageX3_;
}
return this->imageX1_;
}
bool ImageSet::operator==(const ImageSet &other) const
{
return std::tie(this->imageX1_, this->imageX2_, this->imageX3_) ==
std::tie(other.imageX1_, other.imageX2_, other.imageX3_);
}
bool ImageSet::operator!=(const ImageSet &other) const
{
return !this->operator==(other);
}
} // namespace chatterino
+35
View File
@@ -0,0 +1,35 @@
#pragma once
#include "messages/Image.hpp"
namespace chatterino {
class ImageSet
{
public:
ImageSet();
ImageSet(const ImagePtr &image1, const ImagePtr &image2 = Image::getEmpty(),
const ImagePtr &image3 = Image::getEmpty());
ImageSet(const Url &image1, const Url &image2 = {}, const Url &image3 = {});
void setImage1(const ImagePtr &image);
void setImage2(const ImagePtr &image);
void setImage3(const ImagePtr &image);
const ImagePtr &getImage1() const;
const ImagePtr &getImage2() const;
const ImagePtr &getImage3() const;
const ImagePtr &getImage(float scale) const;
ImagePtr getImage(float scale);
bool operator==(const ImageSet &other) const;
bool operator!=(const ImageSet &other) const;
private:
ImagePtr imageX1_;
ImagePtr imageX2_;
ImagePtr imageX3_;
};
} // namespace chatterino
+1
View File
@@ -1,6 +1,7 @@
#pragma once
#include <QString>
#include <common/Common.hpp>
namespace chatterino {
+27 -30
View File
@@ -60,18 +60,18 @@ MessageElement::Flags MessageElement::getFlags() const
}
// IMAGE
ImageElement::ImageElement(Image *image, MessageElement::Flags flags)
ImageElement::ImageElement(ImagePtr image, MessageElement::Flags flags)
: MessageElement(flags)
, image_(image)
{
this->setTooltip(image->getTooltip());
// this->setTooltip(image->getTooltip());
}
void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags)
{
if (flags & this->getFlags()) {
QSize size(this->image_->getScaledWidth() * container.getScale(),
this->image_->getScaledHeight() * container.getScale());
auto size = QSize(this->image_->width() * container.getScale(),
this->image_->height() * container.getScale());
container.addElement(
(new ImageLayoutElement(*this, this->image_, size))->setLink(this->getLink()));
@@ -79,29 +79,29 @@ void ImageElement::addToContainer(MessageLayoutContainer &container, MessageElem
}
// EMOTE
EmoteElement::EmoteElement(const EmoteData &data, MessageElement::Flags flags)
EmoteElement::EmoteElement(const EmotePtr &emote, MessageElement::Flags flags)
: MessageElement(flags)
, data(data)
, emote_(emote)
{
if (data.isValid()) {
this->setTooltip(data.image1x->getTooltip());
this->textElement_.reset(
new TextElement(data.image1x->getCopyString(), MessageElement::Misc));
}
this->textElement_.reset(new TextElement(emote->getCopyString(), MessageElement::Misc));
this->setTooltip(emote->tooltip.string);
}
EmotePtr EmoteElement::getEmote() const
{
return this->emote_;
}
void EmoteElement::addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags)
{
if (flags & this->getFlags()) {
if (flags & MessageElement::EmoteImages) {
if (!this->data.isValid()) {
return;
}
auto image = this->emote_->images.getImage(container.getScale());
if (image->empty()) return;
Image *image = this->data.getImage(container.getScale());
QSize size(int(container.getScale() * image->getScaledWidth()),
int(container.getScale() * image->getScaledHeight()));
auto size = QSize(int(container.getScale() * image->width()),
int(container.getScale() * image->height()));
container.addElement(
(new ImageLayoutElement(*this, image, size))->setLink(this->getLink()));
@@ -120,7 +120,7 @@ TextElement::TextElement(const QString &text, MessageElement::Flags flags,
, color_(color)
, style_(style)
{
for (QString word : text.split(' ')) {
for (const auto &word : text.split(' ')) {
this->words_.push_back({word, -1});
// fourtf: add logic to store multiple spaces after message
}
@@ -173,7 +173,6 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme
int textLength = text.length();
int wordStart = 0;
int width = metrics.width(text[0]);
int lastWidth = 0;
for (int i = 1; i < textLength; i++) {
int charWidth = metrics.width(text[i]);
@@ -184,7 +183,6 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme
container.breakLine();
wordStart = i;
lastWidth = width;
width = 0;
if (textLength > i + 2) {
width += metrics.width(text[i]);
@@ -196,8 +194,6 @@ void TextElement::addToContainer(MessageLayoutContainer &container, MessageEleme
width += charWidth;
}
UNUSED(lastWidth); // XXX: What should this be used for (if anything)? KKona
container.addElement(
getTextLayoutElement(text.mid(wordStart), width, this->hasTrailingSpace()));
container.breakLine();
@@ -249,14 +245,15 @@ void TwitchModerationElement::addToContainer(MessageLayoutContainer &container,
if (flags & MessageElement::ModeratorTools) {
QSize size(int(container.getScale() * 16), int(container.getScale() * 16));
for (const ModerationAction &m : getApp()->moderationActions->items.getVector()) {
if (m.isImage()) {
container.addElement((new ImageLayoutElement(*this, m.getImage(), size))
->setLink(Link(Link::UserAction, m.getAction())));
for (const auto &action : getApp()->moderationActions->items.getVector()) {
if (auto image = action.getImage()) {
container.addElement((new ImageLayoutElement(*this, image.get(), size))
->setLink(Link(Link::UserAction, action.getAction())));
} else {
container.addElement((new TextIconLayoutElement(*this, m.getLine1(), m.getLine2(),
container.getScale(), size))
->setLink(Link(Link::UserAction, m.getAction())));
container.addElement(
(new TextIconLayoutElement(*this, action.getLine1(), action.getLine2(),
container.getScale(), size))
->setLink(Link(Link::UserAction, action.getAction())));
}
}
}
+6 -7
View File
@@ -1,6 +1,7 @@
#pragma once
#include "common/Emotemap.hpp"
#include "messages/Emote.hpp"
#include "messages/Image.hpp"
#include "messages/Link.hpp"
#include "messages/MessageColor.hpp"
@@ -16,7 +17,6 @@
namespace chatterino {
class Channel;
struct EmoteData;
struct MessageLayoutContainer;
class MessageElement : boost::noncopyable
@@ -137,12 +137,12 @@ private:
class ImageElement : public MessageElement
{
public:
ImageElement(Image *image, MessageElement::Flags flags);
ImageElement(ImagePtr image, MessageElement::Flags flags);
void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags) override;
private:
Image *image_;
ImagePtr image_;
};
// contains a text, it will split it into words
@@ -173,15 +173,14 @@ private:
class EmoteElement : public MessageElement
{
public:
EmoteElement(const EmoteData &data, MessageElement::Flags flags_);
~EmoteElement() override = default;
EmoteElement(const EmotePtr &data, MessageElement::Flags flags_);
void addToContainer(MessageLayoutContainer &container, MessageElement::Flags flags_) override;
const EmoteData data;
EmotePtr getEmote() const;
private:
std::unique_ptr<TextElement> textElement_;
EmotePtr emote_;
};
// contains a text, formated depending on the preferences
+15 -19
View File
@@ -63,16 +63,17 @@ const Link &MessageLayoutElement::getLink() const
// IMAGE
//
ImageLayoutElement::ImageLayoutElement(MessageElement &_creator, Image *_image, const QSize &_size)
: MessageLayoutElement(_creator, _size)
, image(_image)
ImageLayoutElement::ImageLayoutElement(MessageElement &creator, ImagePtr image, const QSize &size)
: MessageLayoutElement(creator, size)
, image_(image)
{
this->trailingSpace = _creator.hasTrailingSpace();
this->trailingSpace = creator.hasTrailingSpace();
}
void ImageLayoutElement::addCopyTextToString(QString &str, int from, int to) const
{
str += this->image->getCopyString();
// str += this->image_->getCopyString();
str += "not implemented";
if (this->hasTrailingSpace()) {
str += " ";
@@ -86,13 +87,12 @@ int ImageLayoutElement::getSelectionIndexCount()
void ImageLayoutElement::paint(QPainter &painter)
{
if (this->image == nullptr) {
if (this->image_ == nullptr) {
return;
}
const QPixmap *pixmap = this->image->getPixmap();
if (pixmap != nullptr && !this->image->isAnimated()) {
auto pixmap = this->image_->pixmap();
if (pixmap && !this->image_->animated()) {
// fourtf: make it use qreal values
painter.drawPixmap(QRectF(this->getRect()), *pixmap, QRectF());
}
@@ -100,19 +100,15 @@ void ImageLayoutElement::paint(QPainter &painter)
void ImageLayoutElement::paintAnimated(QPainter &painter, int yOffset)
{
if (this->image == nullptr) {
if (this->image_ == nullptr) {
return;
}
if (this->image->isAnimated()) {
// qDebug() << this->image->getUrl();
auto pixmap = this->image->getPixmap();
if (pixmap != nullptr) {
// fourtf: make it use qreal values
QRect _rect = this->getRect();
_rect.moveTop(_rect.y() + yOffset);
painter.drawPixmap(QRectF(_rect), *pixmap, QRectF());
if (this->image_->animated()) {
if (auto pixmap = this->image_->pixmap()) {
auto rect = this->getRect();
rect.moveTop(rect.y() + yOffset);
painter.drawPixmap(QRectF(rect), *pixmap, QRectF());
}
}
}
@@ -7,6 +7,7 @@
#include <boost/noncopyable.hpp>
#include <climits>
#include "messages/Image.hpp"
#include "messages/Link.hpp"
#include "messages/MessageColor.hpp"
#include "singletons/Fonts.hpp"
@@ -15,7 +16,6 @@ class QPainter;
namespace chatterino {
class MessageElement;
class Image;
class MessageLayoutElement : boost::noncopyable
{
@@ -52,7 +52,7 @@ private:
class ImageLayoutElement : public MessageLayoutElement
{
public:
ImageLayoutElement(MessageElement &creator_, Image *image, const QSize &size);
ImageLayoutElement(MessageElement &creator, ImagePtr image, const QSize &size);
protected:
void addCopyTextToString(QString &str, int from = 0, int to = INT_MAX) const override;
@@ -63,7 +63,7 @@ protected:
int getXFromIndex(int index) override;
private:
Image *image;
ImagePtr image_;
};
// TEXT
+70 -85
View File
@@ -3,122 +3,107 @@
#include "common/NetworkRequest.hpp"
#include "debug/Log.hpp"
#include "messages/Image.hpp"
#include "messages/ImageSet.hpp"
#include "providers/twitch/TwitchChannel.hpp"
#include <QJsonArray>
#include <QThread>
namespace chatterino {
namespace {
QString getEmoteLink(QString urlTemplate, const QString &id, const QString &emoteScale)
Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale)
{
urlTemplate.detach();
return urlTemplate.replace("{{id}}", id).replace("{{image}}", emoteScale);
return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)};
}
} // namespace
void BTTVEmotes::loadGlobalEmotes()
AccessGuard<const EmoteMap> BttvEmotes::accessGlobalEmotes() const
{
QString url("https://api.betterttv.net/2/emotes");
return this->globalEmotes_.accessConst();
}
boost::optional<EmotePtr> BttvEmotes::getGlobalEmote(const EmoteName &name)
{
auto emotes = this->globalEmotes_.access();
auto it = emotes->find(name);
if (it == emotes->end()) return boost::none;
return it->second;
}
// FOURTF: never returns anything
// boost::optional<EmotePtr> BttvEmotes::getEmote(const EmoteId &id)
//{
// auto cache = this->channelEmoteCache_.access();
// auto it = cache->find(id);
//
// if (it != cache->end()) {
// auto shared = it->second.lock();
// if (shared) {
// return shared;
// }
// }
//
// return boost::none;
//}
void BttvEmotes::loadGlobalEmotes()
{
auto request = NetworkRequest(QString(globalEmoteApiUrl));
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([this](auto result) {
auto root = result.parseJson();
auto emotes = root.value("emotes").toArray();
request.onSuccess([this](auto result) -> Outcome {
// if (auto shared = weak.lock()) {
auto currentEmotes = this->globalEmotes_.access();
QString urlTemplate = "https:" + root.value("urlTemplate").toString();
auto pair = this->parseGlobalEmotes(result.parseJson(), *currentEmotes);
std::vector<QString> codes;
for (const QJsonValue &emote : emotes) {
QString id = emote.toObject().value("id").toString();
QString code = emote.toObject().value("code").toString();
EmoteData emoteData;
emoteData.image1x = new Image(getEmoteLink(urlTemplate, id, "1x"), 1, code,
code + "<br />Global BTTV Emote");
emoteData.image2x = new Image(getEmoteLink(urlTemplate, id, "2x"), 0.5, code,
code + "<br />Global BTTV Emote");
emoteData.image3x = new Image(getEmoteLink(urlTemplate, id, "3x"), 0.25, code,
code + "<br />Global BTTV Emote");
emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id;
this->globalEmotes.insert(code, emoteData);
codes.push_back(code);
if (pair.first) {
*currentEmotes = std::move(pair.second);
}
this->globalEmoteCodes = codes;
return true;
return pair.first;
// }
return Failure;
});
request.execute();
}
void BTTVEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> _map)
std::pair<Outcome, EmoteMap> BttvEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot,
const EmoteMap &currentEmotes)
{
printf("[BTTVEmotes] Reload BTTV Channel Emotes for channel %s\n", qPrintable(channelName));
auto emotes = EmoteMap();
auto jsonEmotes = jsonRoot.value("emotes").toArray();
auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString());
QString url("https://api.betterttv.net/2/channels/" + channelName);
for (const QJsonValue &jsonEmote : jsonEmotes) {
auto id = EmoteId{jsonEmote.toObject().value("id").toString()};
auto name = EmoteName{jsonEmote.toObject().value("code").toString()};
Log("Request bttv channel emotes for {}", channelName);
auto emote = Emote({name,
ImageSet{Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1),
Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5),
Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)},
Tooltip{name.string + "<br />Global Bttv Emote"},
Url{"https://manage.betterttv.net/emotes/" + id.string}});
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([this, channelName, _map](auto result) {
auto rootNode = result.parseJson();
auto map = _map.lock();
if (_map.expired()) {
return false;
auto it = currentEmotes.find(name);
if (it != currentEmotes.end() && *it->second == emote) {
// reuse old shared_ptr if nothing changed
emotes[name] = it->second;
} else {
emotes[name] = std::make_shared<Emote>(std::move(emote));
}
}
map->clear();
auto emotesNode = rootNode.value("emotes").toArray();
QString linkTemplate = "https:" + rootNode.value("urlTemplate").toString();
std::vector<QString> codes;
for (const QJsonValue &emoteNode : emotesNode) {
QJsonObject emoteObject = emoteNode.toObject();
QString id = emoteObject.value("id").toString();
QString code = emoteObject.value("code").toString();
// emoteObject.value("imageType").toString();
auto emote = this->channelEmoteCache_.getOrAdd(id, [&] {
EmoteData emoteData;
QString link = linkTemplate;
link.detach();
emoteData.image1x = new Image(link.replace("{{id}}", id).replace("{{image}}", "1x"),
1, code, code + "<br />Channel BTTV Emote");
link = linkTemplate;
link.detach();
emoteData.image2x = new Image(link.replace("{{id}}", id).replace("{{image}}", "2x"),
0.5, code, code + "<br />Channel BTTV Emote");
link = linkTemplate;
link.detach();
emoteData.image3x = new Image(link.replace("{{id}}", id).replace("{{image}}", "3x"),
0.25, code, code + "<br />Channel BTTV Emote");
emoteData.pageLink = "https://manage.betterttv.net/emotes/" + id;
return emoteData;
});
this->channelEmotes.insert(code, emote);
map->insert(code, emote);
codes.push_back(code);
}
this->channelEmoteCodes[channelName] = codes;
return true;
});
request.execute();
return {Success, std::move(emotes)};
}
} // namespace chatterino
+17 -12
View File
@@ -1,27 +1,32 @@
#pragma once
#include "common/Emotemap.hpp"
#include "common/SimpleSignalVector.hpp"
#include "util/ConcurrentMap.hpp"
#include <memory>
#include <map>
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "messages/EmoteCache.hpp"
namespace chatterino {
class BTTVEmotes
class BttvEmotes final : std::enable_shared_from_this<BttvEmotes>
{
public:
EmoteMap globalEmotes;
SimpleSignalVector<QString> globalEmoteCodes;
static constexpr const char *globalEmoteApiUrl = "https://api.betterttv.net/2/emotes";
EmoteMap channelEmotes;
std::map<QString, SimpleSignalVector<QString>> channelEmoteCodes;
public:
// BttvEmotes();
AccessGuard<const EmoteMap> accessGlobalEmotes() const;
boost::optional<EmotePtr> getGlobalEmote(const EmoteName &name);
boost::optional<EmotePtr> getEmote(const EmoteId &id);
void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> channelEmoteMap);
private:
EmoteMap channelEmoteCache_;
std::pair<Outcome, EmoteMap> parseGlobalEmotes(const QJsonObject &jsonRoot,
const EmoteMap &currentEmotes);
UniqueAccess<EmoteMap> globalEmotes_;
// UniqueAccess<WeakEmoteIdMap> channelEmoteCache_;
};
} // namespace chatterino
@@ -0,0 +1,76 @@
#include "LoadBttvChannelEmote.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include "common/Common.hpp"
#include "common/NetworkRequest.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
namespace chatterino {
static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale);
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(const QJsonObject &jsonRoot);
void loadBttvChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback)
{
auto request = NetworkRequest(QString(bttvChannelEmoteApiUrl) + channelName);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([callback = std::move(callback)](auto result) -> Outcome {
auto pair = bttvParseChannelEmotes(result.parseJson());
if (pair.first == Success) callback(std::move(pair.second));
return pair.first;
});
request.execute();
}
static std::pair<Outcome, EmoteMap> bttvParseChannelEmotes(const QJsonObject &jsonRoot)
{
static UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<const Emote>>> cache_;
auto cache = cache_.access();
auto emotes = EmoteMap();
auto jsonEmotes = jsonRoot.value("emotes").toArray();
auto urlTemplate = QString("https:" + jsonRoot.value("urlTemplate").toString());
for (auto jsonEmote_ : jsonEmotes) {
auto jsonEmote = jsonEmote_.toObject();
auto id = EmoteId{jsonEmote.value("id").toString()};
auto name = EmoteName{jsonEmote.value("code").toString()};
// emoteObject.value("imageType").toString();
auto emote = Emote({name,
ImageSet{Image::fromUrl(getEmoteLink(urlTemplate, id, "1x"), 1),
Image::fromUrl(getEmoteLink(urlTemplate, id, "2x"), 0.5),
Image::fromUrl(getEmoteLink(urlTemplate, id, "3x"), 0.25)},
Tooltip{name.string + "<br />Channel Bttv Emote"},
Url{"https://manage.betterttv.net/emotes/" + id.string}});
auto shared = (*cache)[id].lock();
if (shared && *shared == emote) {
// reuse old shared_ptr if nothing changed
emotes[name] = shared;
} else {
(*cache)[id] = emotes[name] = std::make_shared<Emote>(std::move(emote));
}
}
return {Success, std::move(emotes)};
}
static Url getEmoteLink(QString urlTemplate, const EmoteId &id, const QString &emoteScale)
{
urlTemplate.detach();
return {urlTemplate.replace("{{id}}", id.string).replace("{{image}}", emoteScale)};
}
} // namespace chatterino
@@ -0,0 +1,14 @@
#pragma once
#include <functional>
class QString;
namespace chatterino {
class EmoteMap;
constexpr const char *bttvChannelEmoteApiUrl = "https://api.betterttv.net/2/channels/";
void loadBttvChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback);
} // namespace chatterino
@@ -0,0 +1,50 @@
#include "ChatterinoBadges.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include "common/NetworkRequest.hpp"
namespace chatterino {
ChatterinoBadges::ChatterinoBadges()
{
}
boost::optional<EmotePtr> ChatterinoBadges::getBadge(const UserName &username)
{
return this->badges.access()->get(username);
}
void ChatterinoBadges::loadChatterinoBadges()
{
static QString url("https://fourtf.com/chatterino/badges.json");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) {
auto jsonRoot = result.parseJson();
auto badges = this->badges.access();
auto replacement = badges->makeReplacment();
for (auto jsonBadge_ : jsonRoot.value("badges").toArray()) {
auto jsonBadge = jsonBadge_.toObject();
auto emote = Emote{EmoteName{}, ImageSet{Url{jsonBadge.value("image").toString()}},
Tooltip{jsonBadge.value("tooltip").toString()}, Url{}};
for (auto jsonUser : jsonBadge.value("users").toArray()) {
replacement.add(UserName{jsonUser.toString()}, std::move(emote));
}
}
replacement.apply();
return Success;
});
req.execute();
}
} // namespace chatterino
@@ -0,0 +1,25 @@
#pragma once
#include <boost/optional.hpp>
#include <unordered_map>
#include "common/Common.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "messages/EmoteCache.hpp"
namespace chatterino {
class ChatterinoBadges
{
public:
ChatterinoBadges();
boost::optional<EmotePtr> getBadge(const UserName &username);
private:
void loadChatterinoBadges();
UniqueAccess<EmoteCache<UserName>> badges;
};
} // namespace chatterino
+16 -8
View File
@@ -4,7 +4,12 @@
#include "debug/Log.hpp"
#include "singletons/Settings.hpp"
#include <rapidjson/error/en.h>
#include <rapidjson/error/error.h>
#include <rapidjson/rapidjson.h>
#include <QFile>
#include <boost/variant.hpp>
#include <memory>
namespace chatterino {
@@ -146,7 +151,7 @@ void Emojis::loadEmojis()
emojiData->shortCodes[0] + "_" + toneNameIt->second);
this->emojiShortCodeToEmoji_.insert(variationEmojiData->shortCodes[0],
variationEmojiData);
variationEmojiData);
this->shortCodes.push_back(variationEmojiData->shortCodes[0]);
this->emojiFirstByte_[variationEmojiData->value.at(0)].append(variationEmojiData);
@@ -260,14 +265,16 @@ void Emojis::loadEmojiSet()
urlPrefix = it->second;
}
QString url = urlPrefix + code + ".png";
emoji->emoteData.image1x =
new Image(url, 0.35, emoji->value, ":" + emoji->shortCodes[0] + ":<br/>Emoji");
emoji->emote = std::make_shared<Emote>(
Emote{EmoteName{emoji->value}, ImageSet{Image::fromUrl({url}, 0.35)},
Tooltip{":" + emoji->shortCodes[0] + ":<br/>Emoji"}, Url{}});
});
});
}
void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, const QString &text)
std::vector<boost::variant<EmotePtr, QString>> Emojis::parse(const QString &text)
{
auto result = std::vector<boost::variant<EmotePtr, QString>>();
int lastParsedEmojiEndIndex = 0;
for (auto i = 0; i < text.length(); ++i) {
@@ -327,12 +334,11 @@ void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, con
if (charactersFromLastParsedEmoji > 0) {
// Add characters inbetween emojis
parsedWords.emplace_back(
EmoteData(), text.mid(lastParsedEmojiEndIndex, charactersFromLastParsedEmoji));
result.emplace_back(text.mid(lastParsedEmojiEndIndex, charactersFromLastParsedEmoji));
}
// Push the emoji as a word to parsedWords
parsedWords.push_back(std::tuple<EmoteData, QString>(matchedEmoji->emoteData, QString()));
result.emplace_back(matchedEmoji->emote);
lastParsedEmojiEndIndex = currentParsedEmojiEndIndex;
@@ -341,8 +347,10 @@ void Emojis::parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, con
if (lastParsedEmojiEndIndex < text.length()) {
// Add remaining characters
parsedWords.emplace_back(EmoteData(), text.mid(lastParsedEmojiEndIndex));
result.emplace_back(text.mid(lastParsedEmojiEndIndex));
}
return result;
}
QString Emojis::replaceShortCodes(const QString &text)
+6 -3
View File
@@ -2,12 +2,15 @@
#include "common/Emotemap.hpp"
#include "common/SimpleSignalVector.hpp"
#include "messages/Emote.hpp"
#include "util/ConcurrentMap.hpp"
#include <QMap>
#include <QRegularExpression>
#include <boost/variant.hpp>
#include <map>
#include <set>
#include <vector>
namespace chatterino {
@@ -26,7 +29,7 @@ struct EmojiData {
std::vector<EmojiData> variations;
EmoteData emoteData;
EmotePtr emote;
};
using EmojiMap = ConcurrentMap<QString, std::shared_ptr<EmojiData>>;
@@ -36,7 +39,7 @@ class Emojis
public:
void initialize();
void load();
void parse(std::vector<std::tuple<EmoteData, QString>> &parsedWords, const QString &text);
std::vector<boost::variant<EmotePtr, QString>> parse(const QString &text);
EmojiMap emojis;
std::vector<QString> shortCodes;
+116 -90
View File
@@ -1,142 +1,168 @@
#include "providers/ffz/FfzEmotes.hpp"
#include <QJsonArray>
#include "common/NetworkRequest.hpp"
#include "debug/Log.hpp"
#include "messages/Image.hpp"
namespace chatterino {
namespace {
QString getEmoteLink(const QJsonObject &urls, const QString &emoteScale)
Url getEmoteLink(const QJsonObject &urls, const QString &emoteScale)
{
auto emote = urls.value(emoteScale);
if (emote.isUndefined()) {
return "";
return {""};
}
assert(emote.isString());
return "https:" + emote.toString();
return {"https:" + emote.toString()};
}
void fillInEmoteData(const QJsonObject &urls, const QString &code, const QString &tooltip,
EmoteData &emoteData)
void fillInEmoteData(const QJsonObject &urls, const EmoteName &name, const QString &tooltip,
Emote &emoteData)
{
QString url1x = getEmoteLink(urls, "1");
QString url2x = getEmoteLink(urls, "2");
QString url3x = getEmoteLink(urls, "4");
auto url1x = getEmoteLink(urls, "1");
auto url2x = getEmoteLink(urls, "2");
auto url3x = getEmoteLink(urls, "4");
assert(!url1x.isEmpty());
emoteData.image1x = new Image(url1x, 1, code, tooltip);
if (!url2x.isEmpty()) {
emoteData.image2x = new Image(url2x, 0.5, code, tooltip);
}
if (!url3x.isEmpty()) {
emoteData.image3x = new Image(url3x, 0.25, code, tooltip);
}
//, code, tooltip
emoteData.name = name;
emoteData.images =
ImageSet{Image::fromUrl(url1x, 1), Image::fromUrl(url2x, 0.5), Image::fromUrl(url3x, 0.25)};
emoteData.tooltip = {tooltip};
}
} // namespace
void FFZEmotes::loadGlobalEmotes()
AccessGuard<const EmoteCache<EmoteName>> FfzEmotes::accessGlobalEmotes() const
{
return this->globalEmotes_.accessConst();
}
boost::optional<EmotePtr> FfzEmotes::getEmote(const EmoteId &id)
{
auto cache = this->channelEmoteCache_.access();
auto it = cache->find(id);
if (it != cache->end()) {
auto shared = it->second.lock();
if (shared) {
return shared;
}
}
return boost::none;
}
boost::optional<EmotePtr> FfzEmotes::getGlobalEmote(const EmoteName &name)
{
return this->globalEmotes_.access()->get(name);
}
void FfzEmotes::loadGlobalEmotes()
{
QString url("https://api.frankerfacez.com/v1/set/global");
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(30000);
request.onSuccess([this](auto result) {
auto root = result.parseJson();
auto sets = root.value("sets").toObject();
std::vector<QString> codes;
for (const QJsonValue &set : sets) {
auto emoticons = set.toObject().value("emoticons").toArray();
for (const QJsonValue &emote : emoticons) {
QJsonObject object = emote.toObject();
QString code = object.value("name").toString();
int id = object.value("id").toInt();
QJsonObject urls = object.value("urls").toObject();
EmoteData emoteData;
fillInEmoteData(urls, code, code + "<br/>Global FFZ Emote", emoteData);
emoteData.pageLink =
QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
this->globalEmotes.insert(code, emoteData);
codes.push_back(code);
}
this->globalEmoteCodes = codes;
}
return true;
});
request.onSuccess(
[this](auto result) -> Outcome { return this->parseGlobalEmotes(result.parseJson()); });
request.execute();
}
void FFZEmotes::loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> _map)
Outcome FfzEmotes::parseGlobalEmotes(const QJsonObject &jsonRoot)
{
printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", qPrintable(channelName));
auto jsonSets = jsonRoot.value("sets").toObject();
auto emotes = this->globalEmotes_.access();
auto replacement = emotes->makeReplacment();
QString url("https://api.frankerfacez.com/v1/room/" + channelName);
for (auto jsonSet : jsonSets) {
auto jsonEmotes = jsonSet.toObject().value("emoticons").toArray();
NetworkRequest request(url);
request.setCaller(QThread::currentThread());
request.setTimeout(3000);
request.onSuccess([this, channelName, _map](auto result) {
auto rootNode = result.parseJson();
auto map = _map.lock();
for (auto jsonEmoteValue : jsonEmotes) {
auto jsonEmote = jsonEmoteValue.toObject();
if (_map.expired()) {
return false;
auto name = EmoteName{jsonEmote.value("name").toString()};
auto id = EmoteId{jsonEmote.value("id").toString()};
auto urls = jsonEmote.value("urls").toObject();
auto emote = Emote();
fillInEmoteData(urls, name, name.string + "<br/>Global FFZ Emote", emote);
emote.homePage = Url{QString("https://www.frankerfacez.com/emoticon/%1-%2")
.arg(id.string)
.arg(name.string)};
replacement.add(name, emote);
}
}
map->clear();
return Success;
}
auto setsNode = rootNode.value("sets").toObject();
void FfzEmotes::loadChannelEmotes(const QString &channelName,
std::function<void(EmoteMap &&)> callback)
{
// printf("[FFZEmotes] Reload FFZ Channel Emotes for channel %s\n", qPrintable(channelName));
std::vector<QString> codes;
for (const QJsonValue &setNode : setsNode) {
auto emotesNode = setNode.toObject().value("emoticons").toArray();
// QString url("https://api.frankerfacez.com/v1/room/" + channelName);
for (const QJsonValue &emoteNode : emotesNode) {
QJsonObject emoteObject = emoteNode.toObject();
// NetworkRequest request(url);
// request.setCaller(QThread::currentThread());
// request.setTimeout(3000);
// request.onSuccess([this, channelName, _map](auto result) -> Outcome {
// return this->parseChannelEmotes(result.parseJson());
//});
// margins
int id = emoteObject.value("id").toInt();
QString code = emoteObject.value("name").toString();
// request.execute();
}
QJsonObject urls = emoteObject.value("urls").toObject();
Outcome parseChannelEmotes(const QJsonObject &jsonRoot)
{
// auto rootNode = result.parseJson();
// auto map = _map.lock();
auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, &urls] {
EmoteData emoteData;
fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote", emoteData);
emoteData.pageLink =
QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
// if (_map.expired()) {
// return false;
//}
return emoteData;
});
// map->clear();
this->channelEmotes.insert(code, emote);
map->insert(code, emote);
codes.push_back(code);
}
// auto setsNode = rootNode.value("sets").toObject();
this->channelEmoteCodes[channelName] = codes;
}
// std::vector<QString> codes;
// for (const QJsonValue &setNode : setsNode) {
// auto emotesNode = setNode.toObject().value("emoticons").toArray();
return true;
});
// for (const QJsonValue &emoteNode : emotesNode) {
// QJsonObject emoteObject = emoteNode.toObject();
request.execute();
// // margins
// int id = emoteObject.value("id").toInt();
// QString code = emoteObject.value("name").toString();
// QJsonObject urls = emoteObject.value("urls").toObject();
// auto emote = this->channelEmoteCache_.getOrAdd(id, [id, &code, &urls] {
// EmoteData emoteData;
// fillInEmoteData(urls, code, code + "<br/>Channel FFZ Emote", emoteData);
// emoteData.pageLink =
// QString("https://www.frankerfacez.com/emoticon/%1-%2").arg(id).arg(code);
// return emoteData;
// });
// this->channelEmotes.insert(code, emote);
// map->insert(code, emote);
// codes.push_back(code);
// }
// this->channelEmoteCodes[channelName] = codes;
//}
return Success;
}
} // namespace chatterino
+22 -13
View File
@@ -1,27 +1,36 @@
#pragma once
#include "common/Emotemap.hpp"
#include "common/SimpleSignalVector.hpp"
#include "util/ConcurrentMap.hpp"
#include <memory>
#include <map>
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "messages/EmoteCache.hpp"
namespace chatterino {
class FFZEmotes
class FfzEmotes final : std::enable_shared_from_this<FfzEmotes>
{
public:
EmoteMap globalEmotes;
SimpleSignalVector<QString> globalEmoteCodes;
static constexpr const char *globalEmoteApiUrl = "https://api.frankerfacez.com/v1/set/global";
static constexpr const char *channelEmoteApiUrl = "https://api.betterttv.net/2/channels/";
EmoteMap channelEmotes;
std::map<QString, SimpleSignalVector<QString>> channelEmoteCodes;
public:
// FfzEmotes();
static std::shared_ptr<FfzEmotes> create();
AccessGuard<const EmoteCache<EmoteName>> accessGlobalEmotes() const;
boost::optional<EmotePtr> getGlobalEmote(const EmoteName &name);
boost::optional<EmotePtr> getEmote(const EmoteId &id);
void loadGlobalEmotes();
void loadChannelEmotes(const QString &channelName, std::weak_ptr<EmoteMap> channelEmoteMap);
void loadChannelEmotes(const QString &channelName, std::function<void(EmoteMap &&)> callback);
private:
ConcurrentMap<int, EmoteData> channelEmoteCache_;
protected:
Outcome parseGlobalEmotes(const QJsonObject &jsonRoot);
Outcome parseChannelEmotes(const QJsonObject &jsonRoot);
UniqueAccess<EmoteCache<EmoteName>> globalEmotes_;
UniqueAccess<WeakEmoteIdMap> channelEmoteCache_;
};
} // namespace chatterino
+19 -26
View File
@@ -35,26 +35,18 @@ AbstractIrcServer::AbstractIrcServer()
// this->writeConnection->reconnectRequested.connect([this] { this->connect(); });
}
IrcConnection *AbstractIrcServer::getReadConnection() const
{
return this->readConnection_.get();
}
IrcConnection *AbstractIrcServer::getWriteConnection() const
{
return this->writeConnection_.get();
}
void AbstractIrcServer::connect()
{
this->disconnect();
// if (this->hasSeparateWriteConnection()) {
this->initializeConnection(this->writeConnection_.get(), false, true);
this->initializeConnection(this->readConnection_.get(), true, false);
// } else {
// this->initializeConnection(this->readConnection.get(), true, true);
// }
bool separateWriteConnection = this->hasSeparateWriteConnection();
if (separateWriteConnection) {
this->initializeConnection(this->writeConnection_.get(), false, true);
this->initializeConnection(this->readConnection_.get(), true, false);
} else {
this->initializeConnection(this->readConnection_.get(), true, true);
}
// fourtf: this should be asynchronous
{
@@ -62,13 +54,9 @@ void AbstractIrcServer::connect()
std::lock_guard<std::mutex> lock2(this->channelMutex);
for (std::weak_ptr<Channel> &weak : this->channels.values()) {
std::shared_ptr<Channel> chan = weak.lock();
if (!chan) {
continue;
if (auto channel = std::shared_ptr<Channel>(weak.lock())) {
this->readConnection_->sendRaw("JOIN #" + channel->getName());
}
this->writeConnection_->sendRaw("JOIN #" + chan->name);
this->readConnection_->sendRaw("JOIN #" + chan->name);
}
this->writeConnection_->open();
@@ -88,13 +76,18 @@ void AbstractIrcServer::disconnect()
}
void AbstractIrcServer::sendMessage(const QString &channelName, const QString &message)
{
this->sendRawMessage("PRIVMSG #" + channelName + " :" + message);
}
void AbstractIrcServer::sendRawMessage(const QString &rawMessage)
{
std::lock_guard<std::mutex> locker(this->connectionMutex_);
// fourtf: trim the message if it's sent from twitch chat
if (this->writeConnection_) {
this->writeConnection_->sendRaw("PRIVMSG #" + channelName + " :" + message);
if (this->hasSeparateWriteConnection()) {
this->writeConnection_->sendRaw(rawMessage);
} else {
this->readConnection_->sendRaw(rawMessage);
}
}
+2 -3
View File
@@ -17,13 +17,11 @@ public:
virtual ~AbstractIrcServer() = default;
// connection
IrcConnection *getReadConnection() const;
IrcConnection *getWriteConnection() const;
void connect();
void disconnect();
void sendMessage(const QString &channelName, const QString &message);
void sendRawMessage(const QString &rawMessage);
// channels
std::shared_ptr<Channel> getOrAddChannel(const QString &dirtyChannelName);
@@ -54,6 +52,7 @@ protected:
virtual std::shared_ptr<Channel> getCustomChannel(const QString &channelName);
virtual bool hasSeparateWriteConnection() const = 0;
virtual QString cleanChannelName(const QString &dirtyChannelName);
QMap<QString, std::weak_ptr<Channel>> channels;
+11 -6
View File
@@ -9,18 +9,23 @@ IrcConnection::IrcConnection(QObject *parent)
this->pingTimer_.setInterval(5000);
this->pingTimer_.start();
QObject::connect(&this->pingTimer_, &QTimer::timeout, [this] {
if (!this->recentlyReceivedMessage_.load()) {
this->sendRaw("PING");
this->reconnectTimer_.start();
if (this->isConnected()) {
if (!this->recentlyReceivedMessage_.load()) {
this->sendRaw("PING");
this->reconnectTimer_.start();
}
this->recentlyReceivedMessage_ = false;
}
this->recentlyReceivedMessage_ = false;
});
// reconnect after x seconds without receiving a message
this->reconnectTimer_.setInterval(5000);
this->reconnectTimer_.setSingleShot(true);
QObject::connect(&this->reconnectTimer_, &QTimer::timeout,
[this] { reconnectRequested.invoke(); });
QObject::connect(&this->reconnectTimer_, &QTimer::timeout, [this] {
if (this->isConnected()) {
reconnectRequested.invoke();
}
});
QObject::connect(this, &Communi::IrcConnection::messageReceived, [this](Communi::IrcMessage *) {
this->recentlyReceivedMessage_ = true;
+7 -8
View File
@@ -94,29 +94,28 @@ void IrcMessageHandler::handleRoomStateMessage(Communi::IrcMessage *message)
auto roomId = it.value().toString();
twitchChannel->setRoomId(roomId);
app->resources->loadChannelData(roomId);
}
// Room modes
{
auto roomModes = twitchChannel->accessRoomModes();
auto roomModes = *twitchChannel->accessRoomModes();
if ((it = tags.find("emote-only")) != tags.end()) {
roomModes->emoteOnly = it.value() == "1";
roomModes.emoteOnly = it.value() == "1";
}
if ((it = tags.find("subs-only")) != tags.end()) {
roomModes->submode = it.value() == "1";
roomModes.submode = it.value() == "1";
}
if ((it = tags.find("slow")) != tags.end()) {
roomModes->slowMode = it.value().toInt();
roomModes.slowMode = it.value().toInt();
}
if ((it = tags.find("r9k")) != tags.end()) {
roomModes->r9k = it.value() == "1";
roomModes.r9k = it.value() == "1";
}
if ((it = tags.find("broadcaster-lang")) != tags.end()) {
roomModes->broadcasterLang = it.value().toString();
roomModes.broadcasterLang = it.value().toString();
}
twitchChannel->setRoomModes(roomModes);
}
twitchChannel->roomModesChanged.invoke();
+7 -6
View File
@@ -4,6 +4,7 @@
#include "debug/Log.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include <QJsonArray>
#include <cassert>
namespace chatterino {
@@ -36,32 +37,32 @@ void PartialTwitchUser::getId(std::function<void(QString)> successCallback, cons
request.setCaller(caller);
request.makeAuthorizedV5(getDefaultClientID());
request.onSuccess([successCallback](auto result) {
request.onSuccess([successCallback](auto result) -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray()) {
Log("API Error while getting user id, users is not an array");
return false;
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 1) {
Log("API Error while getting user id, users array size is not 1");
return false;
return Failure;
}
if (!users[0].isObject()) {
Log("API Error while getting user id, first user is not an object");
return false;
return Failure;
}
auto firstUser = users[0].toObject();
auto id = firstUser.value("_id");
if (!id.isString()) {
Log("API Error: while getting user id, first user object `_id` key is not a "
"string");
return false;
return Failure;
}
successCallback(id.toString());
return true;
return Success;
});
request.execute();
+169 -22
View File
@@ -1,13 +1,45 @@
#include "providers/twitch/TwitchAccount.hpp"
#include <QThread>
#include "Application.hpp"
#include "common/NetworkRequest.hpp"
#include "debug/Log.hpp"
#include "providers/twitch/PartialTwitchUser.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include "singletons/Emotes.hpp"
#include "util/RapidjsonHelpers.hpp"
namespace chatterino {
namespace {
EmoteName cleanUpCode(const EmoteName &dirtyEmoteCode)
{
auto cleanCode = dirtyEmoteCode.string;
cleanCode.detach();
static QMap<QString, QString> emoteNameReplacements{
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"},
{"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"},
{"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
auto it = emoteNameReplacements.find(dirtyEmoteCode.string);
if (it != emoteNameReplacements.end()) {
cleanCode = it.value();
}
cleanCode.replace("&lt;", "<");
cleanCode.replace("&gt;", ">");
return {cleanCode};
}
} // namespace
TwitchAccount::TwitchAccount(const QString &username, const QString &oauthToken,
const QString &oauthClient, const QString &userID)
: Account(ProviderId::Twitch)
@@ -78,20 +110,20 @@ void TwitchAccount::loadIgnores()
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject()) {
return false;
return Failure;
}
auto blocksIt = document.FindMember("blocks");
if (blocksIt == document.MemberEnd()) {
return false;
return Failure;
}
const auto &blocks = blocksIt->value;
if (!blocks.IsArray()) {
return false;
return Failure;
}
{
@@ -116,7 +148,7 @@ void TwitchAccount::loadIgnores()
}
}
return true;
return Success;
});
req.execute();
@@ -148,25 +180,25 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
return true;
});
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
if (!document.IsObject()) {
onFinished(IgnoreResult_Failed, "Bad JSON data while ignoring user " + targetName);
return false;
return Failure;
}
auto userIt = document.FindMember("user");
if (userIt == document.MemberEnd()) {
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (missing user) " + targetName);
return false;
return Failure;
}
TwitchUser ignoredUser;
if (!rj::getSafe(userIt->value, ignoredUser)) {
onFinished(IgnoreResult_Failed,
"Bad JSON data while ignoring user (invalid user) " + targetName);
return false;
return Failure;
}
{
std::lock_guard<std::mutex> lock(this->ignoresMutex_);
@@ -177,12 +209,12 @@ void TwitchAccount::ignoreByID(const QString &targetUserID, const QString &targe
existingUser.update(ignoredUser);
onFinished(IgnoreResult_AlreadyIgnored,
"User " + targetName + " is already ignored");
return false;
return Failure;
}
}
onFinished(IgnoreResult_Success, "Successfully ignored user " + targetName);
return true;
return Success;
});
req.execute();
@@ -217,7 +249,7 @@ void TwitchAccount::unignoreByID(
return true;
});
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
TwitchUser ignoredUser;
ignoredUser.id = targetUserID;
@@ -228,7 +260,7 @@ void TwitchAccount::unignoreByID(
}
onFinished(UnignoreResult_Success, "Successfully unignored user " + targetName);
return true;
return Success;
});
req.execute();
@@ -254,10 +286,10 @@ void TwitchAccount::checkFollow(const QString targetUserID,
return true;
});
req.onSuccess([=](auto result) {
req.onSuccess([=](auto result) -> Outcome {
auto document = result.parseRapidJson();
onFinished(FollowResult_Following);
return true;
return Success;
});
req.execute();
@@ -274,10 +306,10 @@ void TwitchAccount::followUser(const QString userID, std::function<void()> succe
request.makeAuthorizedV5(this->getOAuthClient(), this->getOAuthToken());
// TODO: Properly check result of follow request
request.onSuccess([successCallback](auto result) {
request.onSuccess([successCallback](auto result) -> Outcome {
successCallback();
return true;
return Success;
});
request.execute();
@@ -301,10 +333,10 @@ void TwitchAccount::unfollowUser(const QString userID, std::function<void()> suc
return true;
});
request.onSuccess([successCallback](const auto &document) {
request.onSuccess([successCallback](const auto &document) -> Outcome {
successCallback();
return true;
return Success;
});
request.execute();
@@ -317,7 +349,7 @@ std::set<TwitchUser> TwitchAccount::getIgnores() const
return this->ignores_;
}
void TwitchAccount::loadEmotes(std::function<void(const rapidjson::Document &)> cb)
void TwitchAccount::loadEmotes()
{
Log("Loading Twitch emotes for user {}", this->getUserName());
@@ -346,11 +378,126 @@ void TwitchAccount::loadEmotes(std::function<void(const rapidjson::Document &)>
return true;
});
req.onSuccess([=](auto result) {
cb(result.parseRapidJson());
req.onSuccess([=](auto result) -> Outcome {
this->parseEmotes(result.parseRapidJson());
return Success;
});
req.execute();
}
AccessGuard<const TwitchAccount::TwitchAccountEmoteData> TwitchAccount::accessEmotes() const
{
return this->emotes_.accessConst();
}
void TwitchAccount::parseEmotes(const rapidjson::Document &root)
{
auto emoteData = this->emotes_.access();
emoteData->emoteSets.clear();
emoteData->allEmoteNames.clear();
auto emoticonSets = root.FindMember("emoticon_sets");
if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject()) {
Log("No emoticon_sets in load emotes response");
return;
}
for (const auto &emoteSetJSON : emoticonSets->value.GetObject()) {
auto emoteSet = std::make_shared<EmoteSet>();
emoteSet->key = emoteSetJSON.name.GetString();
this->loadEmoteSetData(emoteSet);
for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) {
if (!emoteJSON.IsObject()) {
Log("Emote value was invalid");
return;
}
uint64_t idNumber;
if (!rj::getSafe(emoteJSON, "id", idNumber)) {
Log("No ID key found in Emote value");
return;
}
EmoteName code;
if (!rj::getSafe(emoteJSON, "code", code)) {
Log("No code key found in Emote value");
return;
}
auto id = EmoteId{QString::number(idNumber)};
auto cleanCode = cleanUpCode(code);
emoteSet->emotes.emplace_back(TwitchEmote{id, cleanCode});
emoteData->allEmoteNames.push_back(cleanCode);
auto emote = getApp()->emotes->twitch.getOrCreateEmote(id, code);
emoteData->emotes.emplace(code, emote);
}
emoteData->emoteSets.emplace_back(emoteSet);
}
};
void TwitchAccount::loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet)
{
if (!emoteSet) {
Log("null emote set sent");
return;
}
auto staticSetIt = this->staticEmoteSets.find(emoteSet->key);
if (staticSetIt != this->staticEmoteSets.end()) {
const auto &staticSet = staticSetIt->second;
emoteSet->channelName = staticSet.channelName;
emoteSet->text = staticSet.text;
return;
}
NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
"/");
req.setUseQuickLoadCache(true);
req.onError([](int errorCode) -> bool {
Log("Error code {} while loading emote set data", errorCode);
return true;
});
req.onSuccess([emoteSet](auto result) -> Outcome {
auto root = result.parseRapidJson();
if (!root.IsObject()) {
return Failure;
}
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName)) {
return Failure;
}
if (!rj::getSafe(root, "type", type)) {
return Failure;
}
Log("Loaded twitch emote set data for {}!", emoteSet->key);
if (type == "sub") {
emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName);
} else {
emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName);
}
emoteSet->channelName = channelName;
return Success;
});
req.execute();
}
+32 -1
View File
@@ -1,6 +1,8 @@
#pragma once
#include "common/UniqueAccess.hpp"
#include "controllers/accounts/Account.hpp"
#include "messages/Emote.hpp"
#include "providers/twitch/TwitchUser.hpp"
#include <rapidjson/document.h>
@@ -33,6 +35,28 @@ enum FollowResult {
class TwitchAccount : public Account
{
public:
struct TwitchEmote {
EmoteId id;
EmoteName name;
};
struct EmoteSet {
QString key;
QString channelName;
QString text;
std::vector<TwitchEmote> emotes;
};
std::map<QString, EmoteSet> staticEmoteSets;
struct TwitchAccountEmoteData {
std::vector<std::shared_ptr<EmoteSet>> emoteSets;
std::vector<EmoteName> allEmoteNames;
EmoteMap emotes;
};
TwitchAccount(const QString &username, const QString &oauthToken_, const QString &oauthClient_,
const QString &_userID);
@@ -70,11 +94,15 @@ public:
std::set<TwitchUser> getIgnores() const;
void loadEmotes(std::function<void(const rapidjson::Document &)> cb);
void loadEmotes();
AccessGuard<const TwitchAccountEmoteData> accessEmotes() const;
QColor color;
private:
void parseEmotes(const rapidjson::Document &document);
void loadEmoteSetData(std::shared_ptr<EmoteSet> emoteSet);
QString oauthClient_;
QString oauthToken_;
QString userName_;
@@ -83,6 +111,9 @@ private:
mutable std::mutex ignoresMutex_;
std::set<TwitchUser> ignores_;
// std::map<UserId, TwitchAccountEmoteData> emotes;
UniqueAccess<TwitchAccountEmoteData> emotes_;
};
} // namespace chatterino
+6 -6
View File
@@ -16,23 +16,23 @@ void TwitchApi::findUserId(const QString user, std::function<void(QString)> succ
request.setCaller(QThread::currentThread());
request.makeAuthorizedV5(getDefaultClientID());
request.setTimeout(30000);
request.onSuccess([successCallback](auto result) mutable {
request.onSuccess([successCallback](auto result) mutable -> Outcome {
auto root = result.parseJson();
if (!root.value("users").isArray()) {
Log("API Error while getting user id, users is not an array");
successCallback("");
return false;
return Failure;
}
auto users = root.value("users").toArray();
if (users.size() != 1) {
Log("API Error while getting user id, users array size is not 1");
successCallback("");
return false;
return Failure;
}
if (!users[0].isObject()) {
Log("API Error while getting user id, first user is not an object");
successCallback("");
return false;
return Failure;
}
auto firstUser = users[0].toObject();
auto id = firstUser.value("_id");
@@ -40,10 +40,10 @@ void TwitchApi::findUserId(const QString user, std::function<void(QString)> succ
Log("API Error: while getting user id, first user object `_id` key is not a "
"string");
successCallback("");
return false;
return Failure;
}
successCallback(id.toString());
return true;
return Success;
});
request.execute();
+58
View File
@@ -0,0 +1,58 @@
#include "TwitchBadges.hpp"
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include "common/NetworkRequest.hpp"
namespace chatterino {
TwitchBadges::TwitchBadges()
{
}
void TwitchBadges::initialize(Settings &settings, Paths &paths)
{
this->loadTwitchBadges();
}
void TwitchBadges::loadTwitchBadges()
{
static QString url("https://badges.twitch.tv/v1/badges/global/display?language=en");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) -> Outcome {
auto root = result.parseJson();
QJsonObject sets = root.value("badge_sets").toObject();
for (QJsonObject::iterator it = sets.begin(); it != sets.end(); ++it) {
QJsonObject versions = it.value().toObject().value("versions").toObject();
for (auto versionIt = std::begin(versions); versionIt != std::end(versions);
++versionIt) {
auto emote =
Emote{{""},
ImageSet{
Image::fromUrl({root.value("image_url_1x").toString()}, 1),
Image::fromUrl({root.value("image_url_2x").toString()}, 0.5),
Image::fromUrl({root.value("image_url_4x").toString()}, 0.25),
},
Tooltip{root.value("description").toString()},
Url{root.value("clickURL").toString()}};
// "title"
// "clickAction"
QJsonObject versionObj = versionIt.value().toObject();
this->badges.emplace(versionIt.key(), std::make_shared<Emote>(emote));
}
}
return Success;
});
req.execute();
}
} // namespace chatterino
+26
View File
@@ -0,0 +1,26 @@
#pragma once
#include <QString>
#include <messages/Emote.hpp>
#include <unordered_map>
#include "util/QStringHash.hpp"
namespace chatterino {
class Settings;
class Paths;
class TwitchBadges
{
public:
TwitchBadges();
void initialize(Settings &settings, Paths &paths);
private:
void loadTwitchBadges();
std::unordered_map<QString, EmotePtr> badges;
};
} // namespace chatterino
+188 -53
View File
@@ -5,33 +5,34 @@
#include "controllers/accounts/AccountController.hpp"
#include "debug/Log.hpp"
#include "messages/Message.hpp"
#include "providers/bttv/LoadBttvChannelEmote.hpp"
#include "providers/twitch/PubsubClient.hpp"
#include "providers/twitch/TwitchCommon.hpp"
#include "providers/twitch/TwitchMessageBuilder.hpp"
#include "providers/twitch/TwitchParseCheerEmotes.hpp"
#include "singletons/Emotes.hpp"
#include "singletons/Settings.hpp"
#include "util/PostToThread.hpp"
#include <IrcConnection>
#include <QJsonArray>
#include <QJsonObject>
#include <QJsonValue>
#include <QThread>
#include <QTimer>
namespace chatterino {
TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection *readConnection)
: Channel(channelName, Channel::Type::Twitch)
, bttvEmotes_(new EmoteMap)
, ffzEmotes_(new EmoteMap)
TwitchChannel::TwitchChannel(const QString &name)
: Channel(name, Channel::Type::Twitch)
, subscriptionUrl_("https://www.twitch.tv/subs/" + name)
, channelUrl_("https://twitch.tv/" + name)
, popoutPlayerUrl_("https://player.twitch.tv/?channel=" + name)
, mod_(false)
, readConnection_(readConnection)
{
Log("[TwitchChannel:{}] Opened", this->name);
Log("[TwitchChannel:{}] Opened", name);
this->refreshChannelEmotes();
// this->refreshChannelEmotes();
// this->refreshViewerList();
this->managedConnect(getApp()->accounts->twitch.currentUserChanged,
@@ -39,13 +40,17 @@ TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection
// pubsub
this->userStateChanged.connect([=] { this->refreshPubsub(); });
this->roomIdChanged.connect([=] { this->refreshPubsub(); });
this->managedConnect(getApp()->accounts->twitch.currentUserChanged,
[=] { this->refreshPubsub(); });
this->refreshPubsub();
// room id loaded -> refresh live status
this->roomIdChanged.connect([this]() { this->refreshLiveStatus(); });
this->roomIdChanged.connect([this]() {
this->refreshPubsub();
this->refreshLiveStatus();
this->loadBadges();
this->loadCheerEmotes();
});
// timers
QObject::connect(&this->chattersListTimer_, &QTimer::timeout,
@@ -69,7 +74,7 @@ TwitchChannel::TwitchChannel(const QString &channelName, Communi::IrcConnection
bool TwitchChannel::isEmpty() const
{
return this->name.isEmpty();
return this->getName().isEmpty();
}
bool TwitchChannel::canSendMessage() const
@@ -79,12 +84,15 @@ bool TwitchChannel::canSendMessage() const
void TwitchChannel::refreshChannelEmotes()
{
auto app = getApp();
Log("[TwitchChannel:{}] Reloading channel emotes", this->name);
app->emotes->bttv.loadChannelEmotes(this->name, this->bttvEmotes_);
app->emotes->ffz.loadChannelEmotes(this->name, this->ffzEmotes_);
loadBttvChannelEmotes(this->getName(), [this, weak = weakOf<Channel>(this)](auto &&emoteMap) {
if (auto shared = weak.lock()) //
*this->bttvEmotes_.access() = emoteMap;
});
getApp()->emotes->ffz.loadChannelEmotes(this->getName(),
[this, weak = weakOf<Channel>(this)](auto &&emoteMap) {
if (auto shared = weak.lock())
*this->ffzEmotes_.access() = emoteMap;
});
}
void TwitchChannel::sendMessage(const QString &message)
@@ -100,7 +108,7 @@ void TwitchChannel::sendMessage(const QString &message)
return;
}
Log("[TwitchChannel:{}] Send message: {}", this->name, message);
Log("[TwitchChannel:{}] Send message: {}", this->getName(), message);
// Do last message processing
QString parsedMessage = app->emotes->emojis.replaceShortCodes(message);
@@ -120,7 +128,7 @@ void TwitchChannel::sendMessage(const QString &message)
}
bool messageSent = false;
this->sendMessageSignal.invoke(this->name, parsedMessage, messageSent);
this->sendMessageSignal.invoke(this->getName(), parsedMessage, messageSent);
if (messageSent) {
qDebug() << "sent";
@@ -146,7 +154,7 @@ bool TwitchChannel::isBroadcaster() const
{
auto app = getApp();
return this->name == app->accounts->twitch.getCurrent()->getUserName();
return this->getName() == app->accounts->twitch.getCurrent()->getUserName();
}
void TwitchChannel::addRecentChatter(const std::shared_ptr<Message> &message)
@@ -222,9 +230,9 @@ void TwitchChannel::setRoomId(const QString &id)
this->loadRecentMessages();
}
const AccessGuard<TwitchChannel::RoomModes> TwitchChannel::accessRoomModes() const
AccessGuard<const TwitchChannel::RoomModes> TwitchChannel::accessRoomModes() const
{
return this->roomModes_.access();
return this->roomModes_.accessConst();
}
void TwitchChannel::setRoomModes(const RoomModes &_roomModes)
@@ -239,19 +247,37 @@ bool TwitchChannel::isLive() const
return this->streamStatus_.access()->live;
}
const AccessGuard<TwitchChannel::StreamStatus> TwitchChannel::accessStreamStatus() const
AccessGuard<const TwitchChannel::StreamStatus> TwitchChannel::accessStreamStatus() const
{
return this->streamStatus_.access();
return this->streamStatus_.accessConst();
}
const EmoteMap &TwitchChannel::getFfzEmotes() const
boost::optional<EmotePtr> TwitchChannel::getBttvEmote(const EmoteName &name) const
{
return *this->ffzEmotes_;
auto emotes = this->bttvEmotes_.access();
auto it = emotes->find(name);
if (it == emotes->end()) return boost::none;
return it->second;
}
const EmoteMap &TwitchChannel::getBttvEmotes() const
boost::optional<EmotePtr> TwitchChannel::getFfzEmote(const EmoteName &name) const
{
return *this->bttvEmotes_;
auto emotes = this->bttvEmotes_.access();
auto it = emotes->find(name);
if (it == emotes->end()) return boost::none;
return it->second;
}
AccessGuard<const EmoteMap> TwitchChannel::accessBttvEmotes() const
{
return this->bttvEmotes_.accessConst();
}
AccessGuard<const EmoteMap> TwitchChannel::accessFfzEmotes() const
{
return this->ffzEmotes_.accessConst();
}
const QString &TwitchChannel::getSubscriptionUrl()
@@ -290,12 +316,12 @@ void TwitchChannel::refreshLiveStatus()
auto roomID = this->getRoomId();
if (roomID.isEmpty()) {
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->name);
Log("[TwitchChannel:{}] Refreshing live status (Missing ID)", this->getName());
this->setLive(false);
return;
}
Log("[TwitchChannel:{}] Refreshing live status", this->name);
Log("[TwitchChannel:{}] Refreshing live status", this->getName());
QString url("https://api.twitch.tv/kraken/streams/" + roomID);
@@ -306,9 +332,9 @@ void TwitchChannel::refreshLiveStatus()
request.setCaller(QThread::currentThread());
//>>>>>>> 9bfbdefd2f0972a738230d5b95a009f73b1dd933
request.onSuccess([this, weak = this->weak_from_this()](auto result) {
request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared) return false;
if (!shared) return Failure;
return this->parseLiveStatus(result.parseRapidJson());
});
@@ -316,16 +342,16 @@ void TwitchChannel::refreshLiveStatus()
request.execute();
}
bool TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
Outcome TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
{
if (!document.IsObject()) {
Log("[TwitchChannel:refreshLiveStatus] root is not an object");
return false;
return Failure;
}
if (!document.HasMember("stream")) {
Log("[TwitchChannel:refreshLiveStatus] Missing stream in root");
return false;
return Failure;
}
const auto &stream = document["stream"];
@@ -333,21 +359,21 @@ bool TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
if (!stream.IsObject()) {
// Stream is offline (stream is most likely null)
this->setLive(false);
return false;
return Failure;
}
if (!stream.HasMember("viewers") || !stream.HasMember("game") || !stream.HasMember("channel") ||
!stream.HasMember("created_at")) {
Log("[TwitchChannel:refreshLiveStatus] Missing members in stream");
this->setLive(false);
return false;
return Failure;
}
const rapidjson::Value &streamChannel = stream["channel"];
if (!streamChannel.IsObject() || !streamChannel.HasMember("status")) {
Log("[TwitchChannel:refreshLiveStatus] Missing member \"status\" in channel");
return false;
return Failure;
}
// Stream is live
@@ -385,7 +411,7 @@ bool TwitchChannel::parseLiveStatus(const rapidjson::Document &document)
// Signal all listeners that the stream status has been updated
this->liveStatusChanged.invoke();
return true;
return Success;
}
void TwitchChannel::loadRecentMessages()
@@ -397,30 +423,28 @@ void TwitchChannel::loadRecentMessages()
request.makeAuthorizedV5(getDefaultClientID());
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = this->weak_from_this()](auto result) {
// channel still exists?
request.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
ChannelPtr shared = weak.lock();
if (!shared) return false;
if (!shared) return Failure;
// parse json
return this->parseRecentMessages(result.parseJson());
});
request.execute();
}
bool TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
Outcome TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
{
QJsonArray jsonMessages = jsonRoot.value("messages").toArray();
if (jsonMessages.empty()) {
return false;
}
if (jsonMessages.empty()) return Failure;
std::vector<MessagePtr> messages;
for (const auto jsonMessage : jsonMessages) {
auto content = jsonMessage.toString().toUtf8();
auto message = Communi::IrcMessage::fromData(content, this->readConnection_);
// passing nullptr as the channel makes the message invalid but we don't check for that
// anyways
auto message = Communi::IrcMessage::fromData(content, nullptr);
auto privMsg = dynamic_cast<Communi::IrcPrivateMessage *>(message);
assert(privMsg);
@@ -433,7 +457,7 @@ bool TwitchChannel::parseRecentMessages(const QJsonObject &jsonRoot)
this->addMessagesAtStart(messages);
return true;
return Success;
}
void TwitchChannel::refreshPubsub()
@@ -459,13 +483,13 @@ void TwitchChannel::refreshViewerList()
}
// get viewer list
NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->name + "/chatters");
NetworkRequest request("https://tmi.twitch.tv/group/user/" + this->getName() + "/chatters");
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = this->weak_from_this()](auto result) {
request.onSuccess([this, weak = this->weak_from_this()](auto result) -> Outcome {
// channel still exists?
auto shared = weak.lock();
if (!shared) return false;
if (!shared) return Failure;
return this->parseViewerList(result.parseJson());
});
@@ -473,7 +497,7 @@ void TwitchChannel::refreshViewerList()
request.execute();
}
bool TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
Outcome TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
{
static QStringList categories = {"moderators", "staff", "admins", "global_mods", "viewers"};
@@ -486,7 +510,118 @@ bool TwitchChannel::parseViewerList(const QJsonObject &jsonRoot)
}
}
return true;
return Success;
}
void TwitchChannel::loadBadges()
{
auto url = Url{"https://badges.twitch.tv/v1/badges/channels/" + this->getRoomId() +
"/display?language=en"};
NetworkRequest req(url.string);
req.setCaller(QThread::currentThread());
req.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto shared = weak.lock();
if (!shared) return Failure;
auto badgeSets = this->badgeSets_.access();
auto jsonRoot = result.parseJson();
auto _ = jsonRoot["badge_sets"].toObject();
for (auto jsonBadgeSet = _.begin(); jsonBadgeSet != _.end(); jsonBadgeSet++) {
auto &versions = (*badgeSets)[jsonBadgeSet.key()];
auto _ = jsonBadgeSet->toObject()["versions"].toObject();
for (auto jsonVersion_ = _.begin(); jsonVersion_ != _.end(); jsonVersion_++) {
auto jsonVersion = jsonVersion_->toObject();
auto emote = std::make_shared<Emote>(
Emote{EmoteName{},
ImageSet{Image::fromUrl({jsonVersion["image_url_1x"].toString()}),
Image::fromUrl({jsonVersion["image_url_2x"].toString()}),
Image::fromUrl({jsonVersion["image_url_4x"].toString()})},
Tooltip{jsonRoot["description"].toString()},
Url{jsonVersion["clickURL"].toString()}});
versions.emplace(jsonVersion_.key(), emote);
};
}
return Success;
});
req.execute();
}
void TwitchChannel::loadCheerEmotes()
{
auto url = Url{"https://api.twitch.tv/kraken/bits/actions?channel_id=" + this->getRoomId()};
auto request = NetworkRequest::twitchRequest(url.string);
request.setCaller(QThread::currentThread());
request.onSuccess([this, weak = weakOf<Channel>(this)](auto result) -> Outcome {
auto cheerEmoteSets = ParseCheermoteSets(result.parseRapidJson());
for (auto &set : cheerEmoteSets) {
auto cheerEmoteSet = CheerEmoteSet();
cheerEmoteSet.regex = QRegularExpression("^" + set.prefix.toLower() + "([1-9][0-9]*)$");
for (auto &tier : set.tiers) {
CheerEmote cheerEmote;
cheerEmote.color = QColor(tier.color);
cheerEmote.minBits = tier.minBits;
// TODO(pajlada): We currently hardcode dark here :|
// We will continue to do so for now since we haven't had to
// solve that anywhere else
cheerEmote.animatedEmote =
std::make_shared<Emote>(Emote{EmoteName{"cheer emote"},
ImageSet{
tier.images["dark"]["animated"]["1"],
tier.images["dark"]["animated"]["2"],
tier.images["dark"]["animated"]["4"],
},
Tooltip{}, Url{}});
cheerEmote.staticEmote =
std::make_shared<Emote>(Emote{EmoteName{"cheer emote"},
ImageSet{
tier.images["dark"]["static"]["1"],
tier.images["dark"]["static"]["2"],
tier.images["dark"]["static"]["4"],
},
Tooltip{}, Url{}});
cheerEmoteSet.cheerEmotes.emplace_back(cheerEmote);
}
std::sort(cheerEmoteSet.cheerEmotes.begin(), cheerEmoteSet.cheerEmotes.end(),
[](const auto &lhs, const auto &rhs) {
return lhs.minBits < rhs.minBits; //
});
this->cheerEmoteSets_.emplace_back(cheerEmoteSet);
}
return Success;
});
request.execute();
}
boost::optional<EmotePtr> TwitchChannel::getTwitchBadge(const QString &set,
const QString &version) const
{
auto badgeSets = this->badgeSets_.access();
auto it = badgeSets->find(set);
if (it != badgeSets->end()) {
auto it2 = it->second.find(version);
if (it2 != it->second.end()) {
return it2->second;
}
}
return boost::none;
}
} // namespace chatterino
+37 -11
View File
@@ -6,12 +6,14 @@
#include "common/Common.hpp"
#include "common/MutexValue.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "singletons/Emotes.hpp"
#include "util/ConcurrentMap.hpp"
#include <pajlada/signals/signalholder.hpp>
#include <mutex>
#include <unordered_map>
namespace chatterino {
@@ -64,16 +66,20 @@ public:
QString getRoomId() const;
void setRoomId(const QString &id);
const AccessGuard<RoomModes> accessRoomModes() const;
AccessGuard<const RoomModes> accessRoomModes() const;
void setRoomModes(const RoomModes &roomModes_);
const AccessGuard<StreamStatus> accessStreamStatus() const;
AccessGuard<const StreamStatus> accessStreamStatus() const;
const EmoteMap &getFfzEmotes() const;
const EmoteMap &getBttvEmotes() const;
boost::optional<EmotePtr> getBttvEmote(const EmoteName &name) const;
boost::optional<EmotePtr> getFfzEmote(const EmoteName &name) const;
AccessGuard<const EmoteMap> accessBttvEmotes() const;
AccessGuard<const EmoteMap> accessFfzEmotes() const;
const QString &getSubscriptionUrl();
const QString &getChannelUrl();
const QString &getPopoutPlayerUrl();
boost::optional<EmotePtr> getTwitchBadge(const QString &set, const QString &version) const;
// Signals
pajlada::Signals::NoArgSignal roomIdChanged;
pajlada::Signals::NoArgSignal liveStatusChanged;
@@ -86,26 +92,43 @@ private:
QString localizedName;
};
explicit TwitchChannel(const QString &channelName, Communi::IrcConnection *readConnection);
struct CheerEmote {
// a Cheermote indicates one tier
QColor color;
int minBits;
EmotePtr animatedEmote;
EmotePtr staticEmote;
};
struct CheerEmoteSet {
QRegularExpression regex;
std::vector<CheerEmote> cheerEmotes;
};
explicit TwitchChannel(const QString &channelName);
// Methods
void refreshLiveStatus();
bool parseLiveStatus(const rapidjson::Document &document);
Outcome parseLiveStatus(const rapidjson::Document &document);
void refreshPubsub();
void refreshViewerList();
bool parseViewerList(const QJsonObject &jsonRoot);
Outcome parseViewerList(const QJsonObject &jsonRoot);
void loadRecentMessages();
bool parseRecentMessages(const QJsonObject &jsonRoot);
Outcome parseRecentMessages(const QJsonObject &jsonRoot);
void setLive(bool newLiveStatus);
void loadBadges();
void loadCheerEmotes();
// Twitch data
UniqueAccess<StreamStatus> streamStatus_;
UniqueAccess<UserState> userState_;
UniqueAccess<RoomModes> roomModes_;
const std::shared_ptr<EmoteMap> bttvEmotes_;
const std::shared_ptr<EmoteMap> ffzEmotes_;
UniqueAccess<EmoteMap> bttvEmotes_;
UniqueAccess<EmoteMap> ffzEmotes_;
const QString subscriptionUrl_;
const QString channelUrl_;
const QString popoutPlayerUrl_;
@@ -118,13 +141,16 @@ private:
UniqueAccess<QStringList> partedUsers_;
bool partedUsersMergeQueued_ = false;
// "subscribers": { "0": ... "3": ... "6": ...
UniqueAccess<std::map<QString, std::map<QString, EmotePtr>>> badgeSets_;
std::vector<CheerEmoteSet> cheerEmoteSets_;
// --
QByteArray messageSuffix_;
QString lastSentMessage_;
QObject lifetimeGuard_;
QTimer liveStatusTimer_;
QTimer chattersListTimer_;
Communi::IrcConnection *readConnection_ = nullptr;
friend class TwitchServer;
};
+36 -200
View File
@@ -6,228 +6,64 @@
#include "messages/Image.hpp"
#include "util/RapidjsonHelpers.hpp"
#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
namespace chatterino {
namespace {
QString getEmoteLink(const QString &id, const QString &emoteScale)
{
QString value = TWITCH_EMOTE_TEMPLATE;
value.detach();
return value.replace("{id}", id).replace("{scale}", emoteScale);
}
QString cleanUpCode(const QString &dirtyEmoteCode)
{
QString cleanCode = dirtyEmoteCode;
// clang-format off
static QMap<QString, QString> emoteNameReplacements{
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"},
{"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"},
{"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
// clang-format on
auto it = emoteNameReplacements.find(dirtyEmoteCode);
if (it != emoteNameReplacements.end()) {
cleanCode = it.value();
}
cleanCode.replace("&lt;", "<");
cleanCode.replace("&gt;", ">");
return cleanCode;
}
} // namespace
TwitchEmotes::TwitchEmotes()
{
{
EmoteSet emoteSet;
emoteSet.key = "19194";
emoteSet.text = "Twitch Prime Emotes";
this->staticEmoteSets[emoteSet.key] = std::move(emoteSet);
}
{
EmoteSet emoteSet;
emoteSet.key = "0";
emoteSet.text = "Twitch Global Emotes";
this->staticEmoteSets[emoteSet.key] = std::move(emoteSet);
}
}
// id is used for lookup
// emoteName is used for giving a name to the emote in case it doesn't exist
EmoteData TwitchEmotes::getEmoteById(const QString &id, const QString &emoteName)
EmotePtr TwitchEmotes::getOrCreateEmote(const EmoteId &id, const EmoteName &name_)
{
QString _emoteName = emoteName;
_emoteName.replace("<", "&lt;");
_emoteName.replace(">", "&gt;");
// clang-format off
static QMap<QString, QString> emoteNameReplacements{
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"},
{"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"},
{"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
static QMap<QString, QString> replacements{
{"[oO](_|\\.)[oO]", "O_o"}, {"\\&gt\\;\\(", "&gt;("}, {"\\&lt\\;3", "&lt;3"},
{"\\:-?(o|O)", ":O"}, {"\\:-?(p|P)", ":P"}, {"\\:-?[\\\\/]", ":/"},
{"\\:-?[z|Z|\\|]", ":Z"}, {"\\:-?\\(", ":("}, {"\\:-?\\)", ":)"},
{"\\:-?D", ":D"}, {"\\;-?(p|P)", ";P"}, {"\\;-?\\)", ";)"},
{"R-?\\)", "R)"}, {"B-?\\)", "B)"},
};
// clang-format on
auto it = emoteNameReplacements.find(_emoteName);
if (it != emoteNameReplacements.end()) {
_emoteName = it.value();
auto name = name_.string;
name.detach();
// replace < >
name.replace("<", "&lt;");
name.replace(">", "&gt;");
// replace regexes
auto it = replacements.find(name);
if (it != replacements.end()) {
name = it.value();
}
return twitchEmoteFromCache_.getOrAdd(id, [&emoteName, &_emoteName, &id] {
EmoteData newEmoteData;
auto cleanCode = cleanUpCode(emoteName);
newEmoteData.image1x =
new Image(getEmoteLink(id, "1.0"), 1, emoteName, _emoteName + "<br/>Twitch Emote");
newEmoteData.image1x->setCopyString(cleanCode);
// search in cache or create new emote
auto cache = this->twitchEmotesCache_.access();
auto shared = (*cache)[id].lock();
newEmoteData.image2x =
new Image(getEmoteLink(id, "2.0"), .5, emoteName, _emoteName + "<br/>Twitch Emote");
newEmoteData.image2x->setCopyString(cleanCode);
if (!shared) {
(*cache)[id] = shared =
std::make_shared<Emote>(Emote{EmoteName{name},
ImageSet{
Image::fromUrl(getEmoteLink(id, "1.0"), 1),
Image::fromUrl(getEmoteLink(id, "2.0"), 0.5),
Image::fromUrl(getEmoteLink(id, "3.0"), 0.25),
},
Tooltip{name}, Url{}});
}
newEmoteData.image3x =
new Image(getEmoteLink(id, "3.0"), .25, emoteName, _emoteName + "<br/>Twitch Emote");
newEmoteData.image3x->setCopyString(cleanCode);
return newEmoteData;
});
return shared;
}
void TwitchEmotes::refresh(const std::shared_ptr<TwitchAccount> &user)
Url TwitchEmotes::getEmoteLink(const EmoteId &id, const QString &emoteScale)
{
const auto &roomID = user->getUserId();
TwitchAccountEmoteData &emoteData = this->emotes[roomID];
if (emoteData.filled) {
Log("Emotes are already loaded for room id {}", roomID);
return;
}
auto loadEmotes = [=, &emoteData](const rapidjson::Document &root) {
emoteData.emoteSets.clear();
emoteData.emoteCodes.clear();
auto emoticonSets = root.FindMember("emoticon_sets");
if (emoticonSets == root.MemberEnd() || !emoticonSets->value.IsObject()) {
Log("No emoticon_sets in load emotes response");
return;
}
for (const auto &emoteSetJSON : emoticonSets->value.GetObject()) {
auto emoteSet = std::make_shared<EmoteSet>();
emoteSet->key = emoteSetJSON.name.GetString();
this->loadSetData(emoteSet);
for (const rapidjson::Value &emoteJSON : emoteSetJSON.value.GetArray()) {
if (!emoteJSON.IsObject()) {
Log("Emote value was invalid");
return;
}
QString id, code;
uint64_t idNumber;
if (!rj::getSafe(emoteJSON, "id", idNumber)) {
Log("No ID key found in Emote value");
return;
}
if (!rj::getSafe(emoteJSON, "code", code)) {
Log("No code key found in Emote value");
return;
}
id = QString::number(idNumber);
auto cleanCode = cleanUpCode(code);
emoteSet->emotes.emplace_back(id, cleanCode);
emoteData.emoteCodes.push_back(cleanCode);
EmoteData emote = this->getEmoteById(id, code);
emoteData.emotes.insert(code, emote);
}
emoteData.emoteSets.emplace_back(emoteSet);
}
emoteData.filled = true;
};
user->loadEmotes(loadEmotes);
return {
QString(TWITCH_EMOTE_TEMPLATE).replace("{id}", id.string).replace("{scale}", emoteScale)};
}
void TwitchEmotes::loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet)
AccessGuard<std::unordered_map<EmoteName, EmotePtr>> TwitchEmotes::accessAll()
{
if (!emoteSet) {
Log("null emote set sent");
return;
}
auto staticSetIt = this->staticEmoteSets.find(emoteSet->key);
if (staticSetIt != this->staticEmoteSets.end()) {
const auto &staticSet = staticSetIt->second;
emoteSet->channelName = staticSet.channelName;
emoteSet->text = staticSet.text;
return;
}
NetworkRequest req("https://braize.pajlada.com/chatterino/twitchemotes/set/" + emoteSet->key +
"/");
req.setUseQuickLoadCache(true);
req.onError([](int errorCode) -> bool {
Log("Error code {} while loading emote set data", errorCode);
return true;
});
req.onSuccess([emoteSet](auto result) -> bool {
auto root = result.parseRapidJson();
if (!root.IsObject()) {
return false;
}
std::string emoteSetID;
QString channelName;
QString type;
if (!rj::getSafe(root, "channel_name", channelName)) {
return false;
}
if (!rj::getSafe(root, "type", type)) {
return false;
}
Log("Loaded twitch emote set data for {}!", emoteSet->key);
if (type == "sub") {
emoteSet->text = QString("Twitch Subscriber Emote (%1)").arg(channelName);
} else {
emoteSet->text = QString("Twitch Account Emote (%1)").arg(channelName);
}
emoteSet->channelName = channelName;
return true;
});
req.execute();
return this->twitchEmotes_.access();
}
} // namespace chatterino
+11 -50
View File
@@ -1,14 +1,17 @@
#pragma once
#include <QString>
#include <unordered_map>
#include "common/Emotemap.hpp"
#include "common/UniqueAccess.hpp"
#include "messages/Emote.hpp"
#include "providers/twitch/EmoteValue.hpp"
#include "providers/twitch/TwitchAccount.hpp"
#include "providers/twitch/TwitchEmotes.hpp"
#include "util/ConcurrentMap.hpp"
#include <map>
#include <QString>
#define TWITCH_EMOTE_TEMPLATE "https://static-cdn.jtvnw.net/emoticons/v1/{id}/{scale}"
namespace chatterino {
@@ -17,55 +20,13 @@ class TwitchEmotes
public:
TwitchEmotes();
EmoteData getEmoteById(const QString &id, const QString &emoteName);
/// Twitch emotes
void refresh(const std::shared_ptr<TwitchAccount> &user);
struct TwitchEmote {
TwitchEmote(const QString &_id, const QString &_code)
: id(_id)
, code(_code)
{
}
// i.e. "403921"
QString id;
// i.e. "forsenE"
QString code;
};
struct EmoteSet {
QString key;
QString channelName;
QString text;
std::vector<TwitchEmote> emotes;
};
std::map<QString, EmoteSet> staticEmoteSets;
struct TwitchAccountEmoteData {
std::vector<std::shared_ptr<EmoteSet>> emoteSets;
std::vector<QString> emoteCodes;
EmoteMap emotes;
bool filled = false;
};
// Key is the user ID
std::map<QString, TwitchAccountEmoteData> emotes;
EmotePtr getOrCreateEmote(const EmoteId &id, const EmoteName &name);
Url getEmoteLink(const EmoteId &id, const QString &emoteScale);
AccessGuard<std::unordered_map<EmoteName, EmotePtr>> accessAll();
private:
void loadSetData(std::shared_ptr<TwitchEmotes::EmoteSet> emoteSet);
// emote code
ConcurrentMap<QString, EmoteValue *> twitchEmotes_;
// emote id
ConcurrentMap<QString, EmoteData> twitchEmoteFromCache_;
UniqueAccess<std::unordered_map<EmoteName, EmotePtr>> twitchEmotes_;
UniqueAccess<std::unordered_map<EmoteId, std::weak_ptr<Emote>>> twitchEmotesCache_;
};
} // namespace chatterino
+283 -252
View File
@@ -16,6 +16,7 @@
#include <QApplication>
#include <QDebug>
#include <QMediaPlayer>
#include <boost/variant.hpp>
namespace chatterino {
@@ -83,7 +84,7 @@ MessagePtr TwitchMessageBuilder::build()
// PARSING
this->parseUsername();
if (this->userName == this->channel->name) {
if (this->userName == this->channel->getName()) {
this->senderIsBroadcaster = true;
}
@@ -143,14 +144,15 @@ MessagePtr TwitchMessageBuilder::build()
// highlights
this->parseHighlights(isPastMsg);
QString bits;
// QString bits;
auto iterator = this->tags.find("bits");
if (iterator != this->tags.end()) {
bits = iterator.value().toString();
this->hasBits_ = true;
// bits = iterator.value().toString();
}
// twitch emotes
std::vector<std::pair<long, EmoteData>> twitchEmotes;
std::vector<std::pair<int, EmotePtr>> twitchEmotes;
iterator = this->tags.find("emotes");
if (iterator != this->tags.end()) {
@@ -164,112 +166,141 @@ MessagePtr TwitchMessageBuilder::build()
[](const auto &a, const auto &b) { return a.first < b.first; });
}
auto currentTwitchEmote = twitchEmotes.begin();
// words
QStringList splits = this->originalMessage_.split(' ');
long int i = 0;
this->addWords(splits, twitchEmotes);
for (QString split : splits) {
MessageColor textColor =
this->action_ ? MessageColor(this->usernameColor_) : MessageColor(MessageColor::Text);
this->message_->searchText = this->userName + ": " + this->originalMessage_;
// twitch emote
return this->getMessage();
}
void TwitchMessageBuilder::addWords(const QStringList &words,
const std::vector<std::pair<int, EmotePtr>> &twitchEmotes)
{
auto i = int();
auto currentTwitchEmote = twitchEmotes.begin();
for (const auto &word : words) {
// check if it's a twitch emote twitch emote
if (currentTwitchEmote != twitchEmotes.end() && currentTwitchEmote->first == i) {
auto emoteImage = currentTwitchEmote->second;
this->emplace<EmoteElement>(emoteImage, MessageElement::TwitchEmote);
i += split.length() + 1;
currentTwitchEmote = std::next(currentTwitchEmote);
i += word.length() + 1;
currentTwitchEmote++;
continue;
}
// split words
std::vector<std::tuple<EmoteData, QString>> parsed;
// Parse emojis and take all non-emojis and put them in parsed as full text-words
app->emotes->emojis.parse(parsed, split);
for (const auto &tuple : parsed) {
const EmoteData &emoteData = std::get<0>(tuple);
if (!emoteData.isValid()) { // is text
QString string = std::get<1>(tuple);
if (!bits.isEmpty() && this->tryParseCheermote(string)) {
// This string was parsed as a cheermote
continue;
}
// TODO: Implement ignored emotes
// Format of ignored emotes:
// Emote name: "forsenPuke" - if string in ignoredEmotes
// Will match emote regardless of source (i.e. bttv, ffz)
// Emote source + name: "bttv:nyanPls"
if (this->tryAppendEmote(string)) {
// Successfully appended an emote
continue;
}
// Actually just text
QString linkString = this->matchLink(string);
Link link;
if (linkString.isEmpty()) {
if (string.startsWith('@')) {
this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
FontStyle::ChatMediumBold);
this->emplace<TextElement>(string, TextElement::NonBoldUsername, textColor);
} else {
this->emplace<TextElement>(string, TextElement::Text, textColor);
}
} else {
static QRegularExpression domainRegex(
R"(^(?:(?:ftp|http)s?:\/\/)?([^\/:]+)(?:\/.*)?$)",
QRegularExpression::CaseInsensitiveOption);
QString lowercaseLinkString;
auto match = domainRegex.match(string);
if (match.isValid()) {
lowercaseLinkString = string.mid(0, match.capturedStart(1)) +
match.captured(1).toLower() +
string.mid(match.capturedEnd(1));
} else {
lowercaseLinkString = string;
}
link = Link(Link::Url, linkString);
textColor = MessageColor(MessageColor::Link);
this->emplace<TextElement>(lowercaseLinkString, TextElement::LowercaseLink,
textColor)
->setLink(link);
this->emplace<TextElement>(string, TextElement::OriginalLink, textColor)
->setLink(link);
}
} else { // is emoji
this->emplace<EmoteElement>(emoteData, EmoteElement::EmojiAll);
}
for (auto &variant : getApp()->emotes->emojis.parse(word)) {
boost::apply_visitor(/*overloaded{[&](EmotePtr arg) { this->addTextOrEmoji(arg); },
[&](const QString &arg) { this->addTextOrEmoji(arg); }}*/
[&](auto &&arg) { this->addTextOrEmoji(arg); }, variant);
}
for (int j = 0; j < split.size(); j++) {
for (int j = 0; j < word.size(); j++) {
i++;
if (split.at(j).isHighSurrogate()) {
if (word.at(j).isHighSurrogate()) {
j++;
}
}
i++;
}
}
this->message_->searchText = this->userName + ": " + this->originalMessage_;
void TwitchMessageBuilder::addTextOrEmoji(EmotePtr emote)
{
this->emplace<EmoteElement>(emote, EmoteElement::EmojiAll);
}
return this->getMessage();
void TwitchMessageBuilder::addTextOrEmoji(const QString &string_)
{
auto string = QString(string_);
if (this->hasBits_ && this->tryParseCheermote(string)) {
// This string was parsed as a cheermote
return;
}
// TODO: Implement ignored emotes
// Format of ignored emotes:
// Emote name: "forsenPuke" - if string in ignoredEmotes
// Will match emote regardless of source (i.e. bttv, ffz)
// Emote source + name: "bttv:nyanPls"
if (this->tryAppendEmote({string})) {
// Successfully appended an emote
return;
}
// Actually just text
auto linkString = this->matchLink(string);
auto link = Link();
auto textColor =
this->action_ ? MessageColor(this->usernameColor_) : MessageColor(MessageColor::Text);
if (linkString.isEmpty()) {
if (string.startsWith('@')) {
this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
FontStyle::ChatMediumBold);
this->emplace<TextElement>(string, TextElement::NonBoldUsername, textColor);
} else {
this->emplace<TextElement>(string, TextElement::Text, textColor);
}
} else {
static QRegularExpression domainRegex(
R"(^(?:(?:ftp|http)s?:\/\/)?([^\/:]+)(?:\/.*)?$)",
QRegularExpression::CaseInsensitiveOption);
QString lowercaseLinkString;
auto match = domainRegex.match(string);
if (match.isValid()) {
lowercaseLinkString = string.mid(0, match.capturedStart(1)) +
match.captured(1).toLower() + string.mid(match.capturedEnd(1));
} else {
lowercaseLinkString = string;
}
link = Link(Link::Url, linkString);
textColor = MessageColor(MessageColor::Link);
this->emplace<TextElement>(lowercaseLinkString, TextElement::LowercaseLink, textColor)
->setLink(link);
this->emplace<TextElement>(string, TextElement::OriginalLink, textColor)->setLink(link);
}
// if (!linkString.isEmpty()) {
// if (getApp()->settings->lowercaseLink) {
// QRegularExpression httpRegex("\\bhttps?://",
// QRegularExpression::CaseInsensitiveOption); QRegularExpression ftpRegex("\\bftps?://",
// QRegularExpression::CaseInsensitiveOption); QRegularExpression
// getDomain("\\/\\/([^\\/]*)"); QString tempString = string;
// if (!string.contains(httpRegex)) {
// if (!string.contains(ftpRegex)) {
// tempString.insert(0, "http://");
// }
// }
// QString domain = getDomain.match(tempString).captured(1);
// string.replace(domain, domain.toLower());
// }
// link = Link(Link::Url, linkString);
// textColor = MessageColor(MessageColor::Link);
//}
// if (string.startsWith('@')) {
// this->emplace<TextElement>(string, TextElement::BoldUsername, textColor,
// FontStyle::ChatMediumBold) //
// ->setLink(link);
// this->emplace<TextElement>(string, TextElement::NonBoldUsername,
// textColor) //
// ->setLink(link);
//} else {
// this->emplace<TextElement>(string, TextElement::Text, textColor) //
// ->setLink(link);
//}
}
void TwitchMessageBuilder::parseMessageID()
@@ -300,8 +331,8 @@ void TwitchMessageBuilder::parseRoomID()
void TwitchMessageBuilder::appendChannelName()
{
QString channelName("#" + this->channel->name);
Link link(Link::Url, this->channel->name + "\n" + this->messageID);
QString channelName("#" + this->channel->getName());
Link link(Link::Url, this->channel->getName() + "\n" + this->messageID);
this->emplace<TextElement>(channelName, MessageElement::ChannelName, MessageColor::System) //
->setLink(link);
@@ -530,71 +561,64 @@ void TwitchMessageBuilder::parseHighlights(bool isPastMsg)
void TwitchMessageBuilder::appendTwitchEmote(const Communi::IrcMessage *ircMessage,
const QString &emote,
std::vector<std::pair<long int, EmoteData>> &vec)
std::vector<std::pair<int, EmotePtr>> &vec)
{
auto app = getApp();
if (!emote.contains(':')) {
return;
}
QStringList parameters = emote.split(':');
auto parameters = emote.split(':');
if (parameters.length() < 2) {
return;
}
const auto &id = parameters.at(0);
auto id = EmoteId{parameters.at(0)};
QStringList occurences = parameters.at(1).split(',');
auto occurences = parameters.at(1).split(',');
for (QString occurence : occurences) {
QStringList coords = occurence.split('-');
auto coords = occurence.split('-');
if (coords.length() < 2) {
return;
}
int start = coords.at(0).toInt();
int end = coords.at(1).toInt();
auto start = coords.at(0).toInt();
auto end = coords.at(1).toInt();
if (start >= end || start < 0 || end > this->originalMessage_.length()) {
return;
}
QString name = this->originalMessage_.mid(start, end - start + 1);
auto name = EmoteName{this->originalMessage_.mid(start, end - start + 1)};
vec.push_back(
std::pair<long int, EmoteData>(start, app->emotes->twitch.getEmoteById(id, name)));
vec.push_back(std::make_pair(start, app->emotes->twitch.getOrCreateEmote(id, name)));
}
}
bool TwitchMessageBuilder::tryAppendEmote(QString &emoteString)
Outcome TwitchMessageBuilder::tryAppendEmote(const EmoteName &name)
{
auto app = getApp();
EmoteData emoteData;
auto flags = MessageElement::Flags::None;
auto emote = boost::optional<EmotePtr>{};
auto appendEmote = [&](MessageElement::Flags flags) {
this->emplace<EmoteElement>(emoteData, flags);
return true;
};
if (app->emotes->bttv.globalEmotes.tryGet(emoteString, emoteData)) {
// BTTV Global Emote
return appendEmote(MessageElement::BttvEmote);
} else if (this->twitchChannel != nullptr &&
this->twitchChannel->getBttvEmotes().tryGet(emoteString, emoteData)) {
// BTTV Channel Emote
return appendEmote(MessageElement::BttvEmote);
} else if (app->emotes->ffz.globalEmotes.tryGet(emoteString, emoteData)) {
// FFZ Global Emote
return appendEmote(MessageElement::FfzEmote);
} else if (this->twitchChannel != nullptr &&
this->twitchChannel->getFfzEmotes().tryGet(emoteString, emoteData)) {
// FFZ Channel Emote
return appendEmote(MessageElement::FfzEmote);
if ((emote = getApp()->emotes->bttv.getGlobalEmote(name))) {
flags = MessageElement::BttvEmote;
} else if (twitchChannel && (emote = this->twitchChannel->getBttvEmote(name))) {
flags = MessageElement::BttvEmote;
} else if ((emote = getApp()->emotes->ffz.getGlobalEmote(name))) {
flags = MessageElement::FfzEmote;
} else if (twitchChannel && (emote = this->twitchChannel->getFfzEmote(name))) {
flags = MessageElement::FfzEmote;
}
return false;
if (emote) {
this->emplace<EmoteElement>(emote.get(), flags);
return Success;
}
return Failure;
}
// fourtf: this is ugly
@@ -603,8 +627,6 @@ void TwitchMessageBuilder::appendTwitchBadges()
{
auto app = getApp();
const auto &channelResources = app->resources->channels[this->roomID_];
auto iterator = this->tags.find("badges");
if (iterator == this->tags.end()) {
@@ -620,68 +642,75 @@ void TwitchMessageBuilder::appendTwitchBadges()
}
if (badge.startsWith("bits/")) {
if (!app->resources->dynamicBadgesLoaded) {
// Do nothing
continue;
}
// if (!app->resources->dynamicBadgesLoaded) {
// // Do nothing
// continue;
// }
QString cheerAmountQS = badge.mid(5);
std::string versionKey = cheerAmountQS.toStdString();
QString tooltip = QString("Twitch cheer ") + cheerAmountQS;
QString cheerAmount = badge.mid(5);
QString tooltip = QString("Twitch cheer ") + cheerAmount;
// Try to fetch channel-specific bit badge
try {
const auto &badge = channelResources.badgeSets.at("bits").versions.at(versionKey);
this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
->setTooltip(tooltip);
continue;
if (twitchChannel)
if (const auto &badge =
this->twitchChannel->getTwitchBadge("bits", cheerAmount)) {
this->emplace<EmoteElement>(badge.get(), MessageElement::BadgeVanity)
->setTooltip(tooltip);
continue;
}
} catch (const std::out_of_range &) {
// Channel does not contain a special bit badge for this version
}
// Use default bit badge
try {
const auto &badge = app->resources->badgeSets.at("bits").versions.at(versionKey);
this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
->setTooltip(tooltip);
} catch (const std::out_of_range &) {
Log("No default bit badge for version {} found", versionKey);
continue;
}
// try {
// const auto &badge = app->resources->badgeSets.at("bits").versions.at(cheerAmount);
// this->emplace<ImageElement>(badge.badgeImage1x, MessageElement::BadgeVanity)
// ->setTooltip(tooltip);
//} catch (const std::out_of_range &) {
// Log("No default bit badge for version {} found", cheerAmount);
// continue;
//}
} else if (badge == "staff/1") {
this->emplace<ImageElement>(app->resources->badgeStaff,
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.staff),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Staff");
} else if (badge == "admin/1") {
this->emplace<ImageElement>(app->resources->badgeAdmin,
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.admin),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Admin");
} else if (badge == "global_mod/1") {
this->emplace<ImageElement>(app->resources->badgeGlobalModerator,
MessageElement::BadgeGlobalAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.globalmod),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Global Moderator");
} else if (badge == "moderator/1") {
// TODO: Implement custom FFZ moderator badge
this->emplace<ImageElement>(app->resources->badgeModerator,
MessageElement::BadgeChannelAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.moderator),
MessageElement::BadgeChannelAuthority)
->setTooltip("Twitch Channel Moderator");
} else if (badge == "turbo/1") {
this->emplace<ImageElement>(app->resources->badgeTurbo,
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.turbo),
MessageElement::BadgeGlobalAuthority)
->setTooltip("Twitch Turbo Subscriber");
} else if (badge == "broadcaster/1") {
this->emplace<ImageElement>(app->resources->badgeBroadcaster,
MessageElement::BadgeChannelAuthority)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.broadcaster),
MessageElement::BadgeChannelAuthority)
->setTooltip("Twitch Broadcaster");
} else if (badge == "premium/1") {
this->emplace<ImageElement>(app->resources->badgePremium, MessageElement::BadgeVanity)
this->emplace<ImageElement>(Image::fromNonOwningPixmap(&app->resources->twitch.prime),
MessageElement::BadgeVanity)
->setTooltip("Twitch Prime Subscriber");
} else if (badge.startsWith("partner/")) {
int index = badge.midRef(8).toInt();
switch (index) {
case 1: {
this->emplace<ImageElement>(app->resources->badgeVerified,
MessageElement::BadgeVanity)
this->emplace<ImageElement>(
Image::fromNonOwningPixmap(&app->resources->twitch.verified),
MessageElement::BadgeVanity)
->setTooltip("Twitch Verified");
} break;
default: {
@@ -689,140 +718,142 @@ void TwitchMessageBuilder::appendTwitchBadges()
} break;
}
} else if (badge.startsWith("subscriber/")) {
if (channelResources.loaded == false) {
// qDebug() << "Channel resources are not loaded, can't add the subscriber badge";
continue;
}
// if (channelResources.loaded == false) {
// // qDebug() << "Channel resources are not loaded, can't add the
// subscriber
// // badge";
// continue;
// }
auto badgeSetIt = channelResources.badgeSets.find("subscriber");
if (badgeSetIt == channelResources.badgeSets.end()) {
// Fall back to default badge
this->emplace<ImageElement>(app->resources->badgeSubscriber,
MessageElement::BadgeSubscription)
->setTooltip("Twitch Subscriber");
continue;
}
// auto badgeSetIt = channelResources.badgeSets.find("subscriber");
// if (badgeSetIt == channelResources.badgeSets.end()) {
// // Fall back to default badge
// this->emplace<ImageElement>(app->resources->badgeSubscriber,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch Subscriber");
// continue;
//}
const auto &badgeSet = badgeSetIt->second;
// const auto &badgeSet = badgeSetIt->second;
std::string versionKey = badge.mid(11).toStdString();
// std::string versionKey = badge.mid(11).toStdString();
auto badgeVersionIt = badgeSet.versions.find(versionKey);
// auto badgeVersionIt = badgeSet.versions.find(versionKey);
if (badgeVersionIt == badgeSet.versions.end()) {
// Fall back to default badge
this->emplace<ImageElement>(app->resources->badgeSubscriber,
MessageElement::BadgeSubscription)
->setTooltip("Twitch Subscriber");
continue;
}
// if (badgeVersionIt == badgeSet.versions.end()) {
// // Fall back to default badge
// this->emplace<ImageElement>(app->resources->badgeSubscriber,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch Subscriber");
// continue;
//}
auto &badgeVersion = badgeVersionIt->second;
// auto &badgeVersion = badgeVersionIt->second;
this->emplace<ImageElement>(badgeVersion.badgeImage1x,
MessageElement::BadgeSubscription)
->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
// this->emplace<ImageElement>(badgeVersion.badgeImage1x,
// MessageElement::BadgeSubscription)
// ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
} else {
if (!app->resources->dynamicBadgesLoaded) {
// Do nothing
continue;
}
// if (!app->resources->dynamicBadgesLoaded) {
// // Do nothing
// continue;
//}
QStringList parts = badge.split('/');
// QStringList parts = badge.split('/');
if (parts.length() != 2) {
qDebug() << "Bad number of parts: " << parts.length() << " in " << parts;
continue;
}
// if (parts.length() != 2) {
// qDebug() << "Bad number of parts: " << parts.length() << " in " << parts;
// continue;
//}
MessageElement::Flags badgeType = MessageElement::Flags::BadgeVanity;
// MessageElement::Flags badgeType = MessageElement::Flags::BadgeVanity;
std::string badgeSetKey = parts[0].toStdString();
std::string versionKey = parts[1].toStdString();
// std::string badgeSetKey = parts[0].toStdString();
// std::string versionKey = parts[1].toStdString();
try {
auto &badgeSet = app->resources->badgeSets.at(badgeSetKey);
// try {
// auto &badgeSet = app->resources->badgeSets.at(badgeSetKey);
try {
auto &badgeVersion = badgeSet.versions.at(versionKey);
// try {
// auto &badgeVersion = badgeSet.versions.at(versionKey);
this->emplace<ImageElement>(badgeVersion.badgeImage1x, badgeType)
->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
} catch (const std::exception &e) {
qDebug() << "Exception caught:" << e.what()
<< "when trying to fetch badge version " << versionKey.c_str();
}
} catch (const std::exception &e) {
qDebug() << "No badge set with key" << badgeSetKey.c_str()
<< ". Exception: " << e.what();
}
// this->emplace<ImageElement>(badgeVersion.badgeImage1x, badgeType)
// ->setTooltip("Twitch " + QString::fromStdString(badgeVersion.title));
// } catch (const std::exception &e) {
// qDebug() << "Exception caught:" << e.what()
// << "when trying to fetch badge version " << versionKey.c_str();
// }
//} catch (const std::exception &e) {
// qDebug() << "No badge set with key" << badgeSetKey.c_str()
// << ". Exception: " << e.what();
//}
}
}
}
void TwitchMessageBuilder::appendChatterinoBadges()
{
auto app = getApp();
// auto app = getApp();
auto &badges = app->resources->chatterinoBadges;
auto it = badges.find(this->userName.toStdString());
// auto &badges = app->resources->chatterinoBadges;
// auto it = badges.find(this->userName.toStdString());
if (it == badges.end()) {
return;
}
// if (it == badges.end()) {
// return;
// }
const auto badge = it->second;
// const auto badge = it->second;
this->emplace<ImageElement>(badge->image, MessageElement::BadgeChatterino)
->setTooltip(QString::fromStdString(badge->tooltip));
// this->emplace<ImageElement>(badge->image, MessageElement::BadgeChatterino)
// ->setTooltip(QString::fromStdString(badge->tooltip));
}
bool TwitchMessageBuilder::tryParseCheermote(const QString &string)
Outcome TwitchMessageBuilder::tryParseCheermote(const QString &string)
{
auto app = getApp();
// Try to parse custom cheermotes
const auto &channelResources = app->resources->channels[this->roomID_];
if (channelResources.loaded) {
for (const auto &cheermoteSet : channelResources.cheermoteSets) {
auto match = cheermoteSet.regex.match(string);
if (!match.hasMatch()) {
continue;
}
QString amount = match.captured(1);
bool ok = false;
int numBits = amount.toInt(&ok);
if (!ok) {
Log("Error parsing bit amount in tryParseCheermote");
return false;
}
// auto app = getApp();
//// Try to parse custom cheermotes
// const auto &channelResources = app->resources->channels[this->roomID_];
// if (channelResources.loaded) {
// for (const auto &cheermoteSet : channelResources.cheermoteSets) {
// auto match = cheermoteSet.regex.match(string);
// if (!match.hasMatch()) {
// continue;
// }
// QString amount = match.captured(1);
// bool ok = false;
// int numBits = amount.toInt(&ok);
// if (!ok) {
// Log("Error parsing bit amount in tryParseCheermote");
// return Failure;
// }
auto savedIt = cheermoteSet.cheermotes.end();
// auto savedIt = cheermoteSet.cheermotes.end();
// Fetch cheermote that matches our numBits
for (auto it = cheermoteSet.cheermotes.begin(); it != cheermoteSet.cheermotes.end();
++it) {
if (numBits >= it->minBits) {
savedIt = it;
} else {
break;
}
}
// // Fetch cheermote that matches our numBits
// for (auto it = cheermoteSet.cheermotes.begin(); it != cheermoteSet.cheermotes.end();
// ++it) {
// if (numBits >= it->minBits) {
// savedIt = it;
// } else {
// break;
// }
// }
if (savedIt == cheermoteSet.cheermotes.end()) {
Log("Error getting a cheermote from a cheermote set for the bit amount {}",
numBits);
return false;
}
// if (savedIt == cheermoteSet.cheermotes.end()) {
// Log("Error getting a cheermote from a cheermote set for the bit amount {}",
// numBits);
// return Failure;
// }
const auto &cheermote = *savedIt;
// const auto &cheermote = *savedIt;
this->emplace<EmoteElement>(cheermote.emoteDataAnimated, EmoteElement::BitsAnimated);
this->emplace<TextElement>(amount, EmoteElement::Text, cheermote.color);
// this->emplace<EmoteElement>(cheermote.animatedEmote, EmoteElement::BitsAnimated);
// this->emplace<TextElement>(amount, EmoteElement::Text, cheermote.color);
return true;
}
}
// return Success;
// }
//}
return false;
return Failure;
}
} // namespace chatterino
@@ -51,14 +51,20 @@ private:
void parseHighlights(bool isPastMsg);
void appendTwitchEmote(const Communi::IrcMessage *ircMessage, const QString &emote,
std::vector<std::pair<long, EmoteData>> &vec);
bool tryAppendEmote(QString &emoteString);
std::vector<std::pair<int, EmotePtr>> &vec);
Outcome tryAppendEmote(const EmoteName &name);
void addWords(const QStringList &words,
const std::vector<std::pair<int, EmotePtr>> &twitchEmotes);
void addTextOrEmoji(EmotePtr emote);
void addTextOrEmoji(const QString &value);
void appendTwitchBadges();
void appendChatterinoBadges();
bool tryParseCheermote(const QString &string);
Outcome tryParseCheermote(const QString &string);
QString roomID_;
bool hasBits_ = false;
QColor usernameColor_;
const QString originalMessage_;
@@ -0,0 +1,264 @@
#include "TwitchParseCheerEmotes.hpp"
#include <rapidjson/document.h>
#include <QString>
#include <vector>
namespace chatterino {
namespace {
template <typename Type>
inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.Is<Type>()) {
return false;
}
out = value.Get<Type>();
return true;
}
template <>
inline bool ReadValue<QString>(const rapidjson::Value &object, const char *key, QString &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.IsString()) {
return false;
}
out = value.GetString();
return true;
}
template <>
inline bool ReadValue<std::vector<QString>>(const rapidjson::Value &object, const char *key,
std::vector<QString> &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.IsArray()) {
return false;
}
for (const rapidjson::Value &innerValue : value.GetArray()) {
if (!innerValue.IsString()) {
return false;
}
out.emplace_back(innerValue.GetString());
}
return true;
}
// Parse a single cheermote set (or "action") from the twitch api
inline bool ParseSingleCheermoteSet(JSONCheermoteSet &set, const rapidjson::Value &action)
{
if (!action.IsObject()) {
return false;
}
if (!ReadValue(action, "prefix", set.prefix)) {
return false;
}
if (!ReadValue(action, "scales", set.scales)) {
return false;
}
if (!ReadValue(action, "backgrounds", set.backgrounds)) {
return false;
}
if (!ReadValue(action, "states", set.states)) {
return false;
}
if (!ReadValue(action, "type", set.type)) {
return false;
}
if (!ReadValue(action, "updated_at", set.updatedAt)) {
return false;
}
if (!ReadValue(action, "priority", set.priority)) {
return false;
}
// Tiers
if (!action.HasMember("tiers")) {
return false;
}
const auto &tiersValue = action["tiers"];
if (!tiersValue.IsArray()) {
return false;
}
for (const rapidjson::Value &tierValue : tiersValue.GetArray()) {
JSONCheermoteSet::CheermoteTier tier;
if (!tierValue.IsObject()) {
return false;
}
if (!ReadValue(tierValue, "min_bits", tier.minBits)) {
return false;
}
if (!ReadValue(tierValue, "id", tier.id)) {
return false;
}
if (!ReadValue(tierValue, "color", tier.color)) {
return false;
}
// Images
if (!tierValue.HasMember("images")) {
return false;
}
const auto &imagesValue = tierValue["images"];
if (!imagesValue.IsObject()) {
return false;
}
// Read images object
for (const auto &imageBackgroundValue : imagesValue.GetObject()) {
QString background = imageBackgroundValue.name.GetString();
bool backgroundExists = false;
for (const auto &bg : set.backgrounds) {
if (background == bg) {
backgroundExists = true;
break;
}
}
if (!backgroundExists) {
continue;
}
const rapidjson::Value &imageBackgroundStates = imageBackgroundValue.value;
if (!imageBackgroundStates.IsObject()) {
continue;
}
// Read each key which represents a background
for (const auto &imageBackgroundState : imageBackgroundStates.GetObject()) {
QString state = imageBackgroundState.name.GetString();
bool stateExists = false;
for (const auto &_state : set.states) {
if (state == _state) {
stateExists = true;
break;
}
}
if (!stateExists) {
continue;
}
const rapidjson::Value &imageScalesValue = imageBackgroundState.value;
if (!imageScalesValue.IsObject()) {
continue;
}
// Read each key which represents a scale
for (const auto &imageScaleValue : imageScalesValue.GetObject()) {
QString scale = imageScaleValue.name.GetString();
bool scaleExists = false;
for (const auto &_scale : set.scales) {
if (scale == _scale) {
scaleExists = true;
break;
}
}
if (!scaleExists) {
continue;
}
const rapidjson::Value &imageScaleURLValue = imageScaleValue.value;
if (!imageScaleURLValue.IsString()) {
continue;
}
QString url = imageScaleURLValue.GetString();
bool ok = false;
qreal scaleNumber = scale.toFloat(&ok);
if (!ok) {
continue;
}
qreal chatterinoScale = 1 / scaleNumber;
auto image = Image::fromUrl({url}, chatterinoScale);
// TODO(pajlada): Fill in name and tooltip
tier.images[background][state][scale] = image;
}
}
}
set.tiers.emplace_back(tier);
}
return true;
}
} // namespace
// Look through the results of https://api.twitch.tv/kraken/bits/actions?channel_id=11148817 for
// cheermote sets or "Actions" as they are called in the API
std::vector<JSONCheermoteSet> ParseCheermoteSets(const rapidjson::Document &d)
{
std::vector<JSONCheermoteSet> sets;
if (!d.IsObject()) {
return sets;
}
if (!d.HasMember("actions")) {
return sets;
}
const auto &actionsValue = d["actions"];
if (!actionsValue.IsArray()) {
return sets;
}
for (const auto &action : actionsValue.GetArray()) {
JSONCheermoteSet set;
bool res = ParseSingleCheermoteSet(set, action);
if (res) {
sets.emplace_back(set);
}
}
return sets;
}
} // namespace chatterino
@@ -0,0 +1,36 @@
#pragma once
#include <rapidjson/document.h>
#include <QString>
#include <map>
#include <vector>
#include "messages/Image.hpp"
namespace chatterino {
struct JSONCheermoteSet {
QString prefix;
std::vector<QString> scales;
std::vector<QString> backgrounds;
std::vector<QString> states;
QString type;
QString updatedAt;
int priority;
struct CheermoteTier {
int minBits;
QString id;
QString color;
// Background State Scale
std::map<QString, std::map<QString, std::map<QString, ImagePtr>>> images;
};
std::vector<CheermoteTier> tiers;
};
std::vector<JSONCheermoteSet> ParseCheermoteSets(const rapidjson::Document &d);
} // namespace chatterino
+16 -11
View File
@@ -28,26 +28,26 @@ TwitchServer::TwitchServer()
qDebug() << "init TwitchServer";
this->pubsub = new PubSub;
// getSettings()->twitchSeperateWriteConnection.connect([this](auto, auto) { this->connect(); },
// this->signalHolder_, false);
}
void TwitchServer::initialize(Application &app)
void TwitchServer::initialize(Settings &settings, Paths &paths)
{
this->app = &app;
app.accounts->twitch.currentUserChanged.connect(
getApp()->accounts->twitch.currentUserChanged.connect(
[this]() { postToThread([this] { this->connect(); }); });
}
void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead, bool isWrite)
{
assert(this->app);
this->singleConnection_ = isRead == isWrite;
std::shared_ptr<TwitchAccount> account = getApp()->accounts->twitch.getCurrent();
qDebug() << "logging in as" << account->getUserName();
QString username = account->getUserName();
// QString oauthClient = account->getOAuthClient();
QString oauthToken = account->getOAuthToken();
if (!oauthToken.startsWith("oauth:")) {
@@ -60,9 +60,6 @@ void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead,
if (!account->isAnon()) {
connection->setPassword(oauthToken);
// fourtf: ignored users
// this->refreshIgnoredUsers(username, oauthClient, oauthToken);
}
connection->sendCommand(Communi::IrcCommand::createCapability("REQ", "twitch.tv/membership"));
@@ -75,7 +72,7 @@ void TwitchServer::initializeConnection(IrcConnection *connection, bool isRead,
std::shared_ptr<Channel> TwitchServer::createChannel(const QString &channelName)
{
TwitchChannel *channel = new TwitchChannel(channelName, this->getReadConnection());
TwitchChannel *channel = new TwitchChannel(channelName);
channel->sendMessageSignal.connect([this, channel](auto &chan, auto &msg, bool &sent) {
this->onMessageSendRequested(channel, msg, sent);
@@ -91,6 +88,8 @@ void TwitchServer::privateMessageReceived(Communi::IrcPrivateMessage *message)
void TwitchServer::messageReceived(Communi::IrcMessage *message)
{
qDebug() << message->toData();
// this->readConnection
if (message->type() == Communi::IrcMessage::Type::Private) {
// We already have a handler for private messages
@@ -179,6 +178,12 @@ QString TwitchServer::cleanChannelName(const QString &dirtyChannelName)
return dirtyChannelName.toLower();
}
bool TwitchServer::hasSeparateWriteConnection() const
{
return true;
// return getSettings()->twitchSeperateWriteConnection;
}
void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString &message,
bool &sent)
{
@@ -227,7 +232,7 @@ void TwitchServer::onMessageSendRequested(TwitchChannel *channel, const QString
lastMessage.push(now);
}
this->sendMessage(channel->name, message);
this->sendMessage(channel->getName(), message);
sent = true;
}
+18 -12
View File
@@ -12,17 +12,19 @@
namespace chatterino {
class Settings;
class Paths;
class PubSub;
class TwitchServer : public AbstractIrcServer, public Singleton
class TwitchServer final : public AbstractIrcServer, public Singleton
{
public:
TwitchServer();
virtual ~TwitchServer() override = default;
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
// fourtf: ugh
void forEachChannelAndSpecialChannels(std::function<void(ChannelPtr)> func);
std::shared_ptr<Channel> getChannelOrEmptyByID(const QString &channelID);
@@ -36,27 +38,31 @@ public:
PubSub *pubsub;
protected:
void initializeConnection(IrcConnection *connection, bool isRead, bool isWrite) override;
std::shared_ptr<Channel> createChannel(const QString &channelName) override;
virtual void initializeConnection(IrcConnection *connection, bool isRead,
bool isWrite) override;
virtual std::shared_ptr<Channel> createChannel(const QString &channelName) override;
void privateMessageReceived(Communi::IrcPrivateMessage *message) override;
void messageReceived(Communi::IrcMessage *message) override;
void writeConnectionMessageReceived(Communi::IrcMessage *message) override;
virtual void privateMessageReceived(Communi::IrcPrivateMessage *message) override;
virtual void messageReceived(Communi::IrcMessage *message) override;
virtual void writeConnectionMessageReceived(Communi::IrcMessage *message) override;
std::shared_ptr<Channel> getCustomChannel(const QString &channelname) override;
virtual std::shared_ptr<Channel> getCustomChannel(const QString &channelname) override;
QString cleanChannelName(const QString &dirtyChannelName) override;
virtual QString cleanChannelName(const QString &dirtyChannelName) override;
virtual bool hasSeparateWriteConnection() const override;
private:
void onMessageSendRequested(TwitchChannel *channel, const QString &message, bool &sent);
Application *app = nullptr;
std::mutex lastMessageMutex_;
std::queue<std::chrono::steady_clock::time_point> lastMessagePleb_;
std::queue<std::chrono::steady_clock::time_point> lastMessageMod_;
std::chrono::steady_clock::time_point lastErrorTimeSpeed_;
std::chrono::steady_clock::time_point lastErrorTimeAmount_;
bool singleConnection_ = false;
pajlada::Signals::SignalHolder signalHolder_;
};
} // namespace chatterino
+9
View File
@@ -0,0 +1,9 @@
#include "Badges.hpp"
namespace chatterino {
Badges::Badges()
{
}
} // namespace chatterino
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#include <unordered_map>
#include "common/Singleton.hpp"
#include "messages/Emote.hpp"
namespace chatterino {
class Badges : public Singleton
{
public:
Badges();
};
} // namespace chatterino
+7 -8
View File
@@ -5,15 +5,14 @@
namespace chatterino {
void Emotes::initialize(Application &app)
Emotes::Emotes()
{
const auto refreshTwitchEmotes = [this, &app] {
auto currentUser = app.accounts->twitch.getCurrent();
assert(currentUser);
this->twitch.refresh(currentUser);
};
app.accounts->twitch.currentUserChanged.connect(refreshTwitchEmotes);
refreshTwitchEmotes();
}
void Emotes::initialize(Settings &settings, Paths &paths)
{
getApp()->accounts->twitch.currentUserChanged.connect(
[] { getApp()->accounts->twitch.getCurrent()->loadEmotes(); });
this->emojis.load();
this->bttv.loadGlobalEmotes();
+8 -3
View File
@@ -12,16 +12,21 @@
namespace chatterino {
class Settings;
class Paths;
class Emotes final : public Singleton
{
public:
virtual void initialize(Application &app) override;
Emotes();
virtual void initialize(Settings &settings, Paths &paths) override;
bool isIgnoredEmote(const QString &emote);
TwitchEmotes twitch;
BTTVEmotes bttv;
FFZEmotes ffz;
BttvEmotes bttv;
FfzEmotes ffz;
Emojis emojis;
GIFTimer gifTimer;
+5 -15
View File
@@ -29,40 +29,30 @@ Fonts::Fonts()
this->fontsByType_.resize(size_t(EndType));
}
void Fonts::initialize(Application &app)
void Fonts::initialize(Settings &, Paths &)
{
this->chatFontFamily.connect([this, &app](const std::string &, auto) {
this->chatFontFamily.connect([this](const std::string &, auto) {
assertInGuiThread();
if (app.windows) {
app.windows->incGeneration();
}
for (auto &map : this->fontsByType_) {
map.clear();
}
this->fontChanged.invoke();
});
this->chatFontSize.connect([this, &app](const int &, auto) {
this->chatFontSize.connect([this](const int &, auto) {
assertInGuiThread();
if (app.windows) {
app.windows->incGeneration();
}
for (auto &map : this->fontsByType_) {
map.clear();
}
this->fontChanged.invoke();
});
getSettings()->boldScale.connect([this, &app](const int &, auto) {
getSettings()->boldScale.connect([this](const int &, auto) {
assertInGuiThread();
if (app.windows) {
app.windows->incGeneration();
}
getApp()->windows->incGeneration();
for (auto &map : this->fontsByType_) {
map.clear();
+4 -1
View File
@@ -13,12 +13,15 @@
namespace chatterino {
class Settings;
class Paths;
class Fonts final : public Singleton
{
public:
Fonts();
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
// font data gets set in createFontData(...)
enum Type : uint8_t {
+1 -1
View File
@@ -12,7 +12,7 @@
namespace chatterino {
void Logging::initialize(Application &app)
void Logging::initialize(Settings &settings, Paths &paths)
{
}
+1 -1
View File
@@ -18,7 +18,7 @@ class Logging : public Singleton
public:
Logging() = default;
virtual void initialize(Application &app) override;
virtual void initialize(Settings &settings, Paths &paths) override;
void addMessage(const QString &channelName, MessagePtr message);
+51 -58
View File
@@ -31,29 +31,12 @@ namespace ipc = boost::interprocess;
namespace chatterino {
// fourtf: don't add this class to the application class
NativeMessaging::NativeMessaging()
{
qDebug() << "init NativeMessagingManager";
}
void registerNmManifest(Paths &paths, const QString &manifestFilename,
const QString &registryKeyName, const QJsonDocument &document);
void NativeMessaging::writeByteArray(QByteArray a)
void registerNmHost(Paths &paths)
{
char *data = a.data();
uint32_t size;
size = a.size();
std::cout.write(reinterpret_cast<char *>(&size), 4);
std::cout.write(data, a.size());
std::cout.flush();
}
void NativeMessaging::registerHost()
{
auto app = getApp();
if (app->paths->isPortable()) {
return;
}
if (paths.isPortable()) return;
auto getBaseDocument = [&] {
QJsonObject obj;
@@ -65,22 +48,6 @@ void NativeMessaging::registerHost()
return obj;
};
auto registerManifest = [&](const QString &manifestFilename, const QString &registryKeyName,
const QJsonDocument &document) {
// save the manifest
QString manifestPath = app->paths->miscDirectory + manifestFilename;
QFile file(manifestPath);
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.write(document.toJson());
file.flush();
#ifdef Q_OS_WIN
// clang-format off
QProcess::execute("REG ADD \"" + registryKeyName + "\" /ve /t REG_SZ /d \"" + manifestPath + "\" /f");
// clang-format on
#endif
};
// chrome
{
QJsonDocument document;
@@ -90,8 +57,8 @@ void NativeMessaging::registerHost()
obj.insert("allowed_origins", allowed_origins_arr);
document.setObject(obj);
registerManifest(
"/native-messaging-manifest-chrome.json",
registerNmManifest(
paths, "/native-messaging-manifest-chrome.json",
"HKCU\\Software\\Google\\Chrome\\NativeMessagingHosts\\com.chatterino.chatterino",
document);
}
@@ -105,24 +72,40 @@ void NativeMessaging::registerHost()
obj.insert("allowed_extensions", allowed_extensions);
document.setObject(obj);
registerManifest("/native-messaging-manifest-firefox.json",
"HKCU\\Software\\Mozilla\\NativeMessagingHosts\\com.chatterino.chatterino",
document);
registerNmManifest(
paths, "/native-messaging-manifest-firefox.json",
"HKCU\\Software\\Mozilla\\NativeMessagingHosts\\com.chatterino.chatterino", document);
}
}
void NativeMessaging::openGuiMessageQueue()
void registerNmManifest(Paths &paths, const QString &manifestFilename,
const QString &registryKeyName, const QJsonDocument &document)
{
static ReceiverThread thread;
(void)registryKeyName;
if (thread.isRunning()) {
thread.exit();
}
// save the manifest
QString manifestPath = paths.miscDirectory + manifestFilename;
QFile file(manifestPath);
file.open(QIODevice::WriteOnly | QIODevice::Truncate);
file.write(document.toJson());
file.flush();
thread.start();
#ifdef Q_OS_WIN
// clang-format off
QProcess::execute("REG ADD \"" + registryKeyName + "\" /ve /t REG_SZ /d \"" + manifestPath + "\" /f");
// clang-format on
#endif
}
void NativeMessaging::sendToGuiProcess(const QByteArray &array)
std::string &getNmQueueName(Paths &paths)
{
static std::string name = "chatterino_gui" + paths.applicationFilePathHash.toStdString();
return name;
}
// CLIENT
void NativeMessagingClient::sendMessage(const QByteArray &array)
{
try {
ipc::message_queue messageQueue(ipc::open_only, "chatterino_gui");
@@ -133,7 +116,24 @@ void NativeMessaging::sendToGuiProcess(const QByteArray &array)
}
}
void NativeMessaging::ReceiverThread::run()
void NativeMessagingClient::writeToCout(const QByteArray &array)
{
auto *data = array.data();
auto size = uint32_t(array.size());
std::cout.write(reinterpret_cast<char *>(&size), 4);
std::cout.write(data, size);
std::cout.flush();
}
// SERVER
void NativeMessagingServer::start()
{
this->thread.start();
}
void NativeMessagingServer::ReceiverThread::run()
{
ipc::message_queue::remove("chatterino_gui");
@@ -157,7 +157,7 @@ void NativeMessaging::ReceiverThread::run()
}
}
void NativeMessaging::ReceiverThread::handleMessage(const QJsonObject &root)
void NativeMessagingServer::ReceiverThread::handleMessage(const QJsonObject &root)
{
auto app = getApp();
@@ -231,11 +231,4 @@ void NativeMessaging::ReceiverThread::handleMessage(const QJsonObject &root)
}
}
std::string &NativeMessaging::getGuiMessageQueueName()
{
static std::string name =
"chatterino_gui" + Paths::getInstance()->applicationFilePathHash.toStdString();
return name;
}
} // namespace chatterino
+18 -11
View File
@@ -1,16 +1,28 @@
#pragma once
#include "common/Singleton.hpp"
#include <QThread>
class Application;
class Paths;
namespace chatterino {
class NativeMessaging final
void registerNmHost(Application &app);
std::string &getNmQueueName(Paths &paths);
class NativeMessagingClient final
{
public:
// fourtf: don't add this class to the application class
NativeMessaging();
void sendMessage(const QByteArray &array);
void writeToCout(const QByteArray &array);
};
class NativeMessagingServer final
{
public:
void start();
private:
class ReceiverThread : public QThread
{
public:
@@ -20,12 +32,7 @@ public:
void handleMessage(const QJsonObject &root);
};
void writeByteArray(QByteArray a);
void registerHost();
void openGuiMessageQueue();
void sendToGuiProcess(const QByteArray &array);
static std::string &getGuiMessageQueueName();
ReceiverThread thread;
};
} // namespace chatterino
+3 -15
View File
@@ -14,6 +14,8 @@ Paths *Paths::instance = nullptr;
Paths::Paths()
{
this->instance = this;
this->initAppFilePathHash();
this->initCheckPortable();
@@ -21,20 +23,6 @@ Paths::Paths()
this->initSubDirectories();
}
void Paths::initInstance()
{
assert(!instance);
instance = new Paths();
}
Paths *Paths::getInstance()
{
assert(instance);
return instance;
}
bool Paths::createFolder(const QString &folderPath)
{
return QDir().mkpath(folderPath);
@@ -116,7 +104,7 @@ void Paths::initSubDirectories()
Paths *getPaths()
{
return Paths::getInstance();
return Paths::instance;
}
} // namespace chatterino
+4 -6
View File
@@ -7,11 +7,10 @@ namespace chatterino {
class Paths
{
Paths();
public:
static void initInstance();
static Paths *getInstance();
static Paths *instance;
Paths();
// Root directory for the configuration files. %APPDATA%/chatterino or ExecutablePath for
// portable mode
@@ -41,10 +40,9 @@ private:
void initAppDataDirectory();
void initSubDirectories();
static Paths *instance;
boost::optional<bool> portable_;
};
Paths *getPaths();
[[deprecated]] Paths *getPaths();
} // namespace chatterino
-480
View File
@@ -1,481 +1 @@
#include "singletons/Resources.hpp"
#include "common/NetworkRequest.hpp"
#include <QDebug>
#include <QIcon>
#include <QJsonArray>
#include <QPixmap>
#include <QThread>
namespace chatterino {
namespace {
inline Image *lli(const char *pixmapPath, qreal scale = 1)
{
return new Image(new QPixmap(pixmapPath), scale);
}
template <typename Type>
inline bool ReadValue(const rapidjson::Value &object, const char *key, Type &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.Is<Type>()) {
return false;
}
out = value.Get<Type>();
return true;
}
template <>
inline bool ReadValue<QString>(const rapidjson::Value &object, const char *key, QString &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.IsString()) {
return false;
}
out = value.GetString();
return true;
}
template <>
inline bool ReadValue<std::vector<QString>>(const rapidjson::Value &object, const char *key,
std::vector<QString> &out)
{
if (!object.HasMember(key)) {
return false;
}
const auto &value = object[key];
if (!value.IsArray()) {
return false;
}
for (const rapidjson::Value &innerValue : value.GetArray()) {
if (!innerValue.IsString()) {
return false;
}
out.emplace_back(innerValue.GetString());
}
return true;
}
// Parse a single cheermote set (or "action") from the twitch api
inline bool ParseSingleCheermoteSet(Resources::JSONCheermoteSet &set,
const rapidjson::Value &action)
{
if (!action.IsObject()) {
return false;
}
if (!ReadValue(action, "prefix", set.prefix)) {
return false;
}
if (!ReadValue(action, "scales", set.scales)) {
return false;
}
if (!ReadValue(action, "backgrounds", set.backgrounds)) {
return false;
}
if (!ReadValue(action, "states", set.states)) {
return false;
}
if (!ReadValue(action, "type", set.type)) {
return false;
}
if (!ReadValue(action, "updated_at", set.updatedAt)) {
return false;
}
if (!ReadValue(action, "priority", set.priority)) {
return false;
}
// Tiers
if (!action.HasMember("tiers")) {
return false;
}
const auto &tiersValue = action["tiers"];
if (!tiersValue.IsArray()) {
return false;
}
for (const rapidjson::Value &tierValue : tiersValue.GetArray()) {
Resources::JSONCheermoteSet::CheermoteTier tier;
if (!tierValue.IsObject()) {
return false;
}
if (!ReadValue(tierValue, "min_bits", tier.minBits)) {
return false;
}
if (!ReadValue(tierValue, "id", tier.id)) {
return false;
}
if (!ReadValue(tierValue, "color", tier.color)) {
return false;
}
// Images
if (!tierValue.HasMember("images")) {
return false;
}
const auto &imagesValue = tierValue["images"];
if (!imagesValue.IsObject()) {
return false;
}
// Read images object
for (const auto &imageBackgroundValue : imagesValue.GetObject()) {
QString background = imageBackgroundValue.name.GetString();
bool backgroundExists = false;
for (const auto &bg : set.backgrounds) {
if (background == bg) {
backgroundExists = true;
break;
}
}
if (!backgroundExists) {
continue;
}
const rapidjson::Value &imageBackgroundStates = imageBackgroundValue.value;
if (!imageBackgroundStates.IsObject()) {
continue;
}
// Read each key which represents a background
for (const auto &imageBackgroundState : imageBackgroundStates.GetObject()) {
QString state = imageBackgroundState.name.GetString();
bool stateExists = false;
for (const auto &_state : set.states) {
if (state == _state) {
stateExists = true;
break;
}
}
if (!stateExists) {
continue;
}
const rapidjson::Value &imageScalesValue = imageBackgroundState.value;
if (!imageScalesValue.IsObject()) {
continue;
}
// Read each key which represents a scale
for (const auto &imageScaleValue : imageScalesValue.GetObject()) {
QString scale = imageScaleValue.name.GetString();
bool scaleExists = false;
for (const auto &_scale : set.scales) {
if (scale == _scale) {
scaleExists = true;
break;
}
}
if (!scaleExists) {
continue;
}
const rapidjson::Value &imageScaleURLValue = imageScaleValue.value;
if (!imageScaleURLValue.IsString()) {
continue;
}
QString url = imageScaleURLValue.GetString();
bool ok = false;
qreal scaleNumber = scale.toFloat(&ok);
if (!ok) {
continue;
}
qreal chatterinoScale = 1 / scaleNumber;
auto image = new Image(url, chatterinoScale);
// TODO(pajlada): Fill in name and tooltip
tier.images[background][state][scale] = image;
}
}
}
set.tiers.emplace_back(tier);
}
return true;
}
// Look through the results of https://api.twitch.tv/kraken/bits/actions?channel_id=11148817 for
// cheermote sets or "Actions" as they are called in the API
inline void ParseCheermoteSets(std::vector<Resources::JSONCheermoteSet> &sets,
const rapidjson::Document &d)
{
if (!d.IsObject()) {
return;
}
if (!d.HasMember("actions")) {
return;
}
const auto &actionsValue = d["actions"];
if (!actionsValue.IsArray()) {
return;
}
for (const auto &action : actionsValue.GetArray()) {
Resources::JSONCheermoteSet set;
bool res = ParseSingleCheermoteSet(set, action);
if (res) {
sets.emplace_back(set);
}
}
}
} // namespace
Resources::Resources()
: badgeStaff(lli(":/images/staff_bg.png"))
, badgeAdmin(lli(":/images/admin_bg.png"))
, badgeGlobalModerator(lli(":/images/globalmod_bg.png"))
, badgeModerator(lli(":/images/moderator_bg.png"))
, badgeTurbo(lli(":/images/turbo_bg.png"))
, badgeBroadcaster(lli(":/images/broadcaster_bg.png"))
, badgePremium(lli(":/images/twitchprime_bg.png"))
, badgeVerified(lli(":/images/verified.png", 0.25))
, badgeSubscriber(lli(":/images/subscriber.png", 0.25))
, badgeCollapsed(lli(":/images/collapse.png"))
, cheerBadge100000(lli(":/images/cheer100000"))
, cheerBadge10000(lli(":/images/cheer10000"))
, cheerBadge5000(lli(":/images/cheer5000"))
, cheerBadge1000(lli(":/images/cheer1000"))
, cheerBadge100(lli(":/images/cheer100"))
, cheerBadge1(lli(":/images/cheer1"))
, moderationmode_enabled(lli(":/images/moderatormode_enabled"))
, moderationmode_disabled(lli(":/images/moderatormode_disabled"))
, splitHeaderContext(lli(":/images/tool_moreCollapser_off16.png"))
, buttonBan(lli(":/images/button_ban.png", 0.25))
, buttonTimeout(lli(":/images/button_timeout.png", 0.25))
, pajaDank(lli(":/images/pajaDank.png", 0.25))
, ppHop(new Image("https://fourtf.com/ppHop.gif", 0.25))
{
this->split.left = QIcon(":/images/split/splitleft.png");
this->split.right = QIcon(":/images/split/splitright.png");
this->split.up = QIcon(":/images/split/splitup.png");
this->split.down = QIcon(":/images/split/splitdown.png");
this->split.move = QIcon(":/images/split/splitmove.png");
this->buttons.ban = QPixmap(":/images/buttons/ban.png");
this->buttons.unban = QPixmap(":/images/buttons/unban.png");
this->buttons.mod = QPixmap(":/images/buttons/mod.png");
this->buttons.unmod = QPixmap(":/images/buttons/unmod.png");
qDebug() << "init ResourceManager";
}
void Resources::initialize(Application &app)
{
this->loadDynamicTwitchBadges();
this->loadChatterinoBadges();
}
Resources::BadgeVersion::BadgeVersion(QJsonObject &&root)
: badgeImage1x(new Image(root.value("image_url_1x").toString()))
, badgeImage2x(new Image(root.value("image_url_2x").toString()))
, badgeImage4x(new Image(root.value("image_url_4x").toString()))
, description(root.value("description").toString().toStdString())
, title(root.value("title").toString().toStdString())
, clickAction(root.value("clickAction").toString().toStdString())
, clickURL(root.value("clickURL").toString().toStdString())
{
}
void Resources::loadChannelData(const QString &roomID, bool bypassCache)
{
QString url = "https://badges.twitch.tv/v1/badges/channels/" + roomID + "/display?language=en";
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this, roomID](auto result) {
auto root = result.parseJson();
QJsonObject sets = root.value("badge_sets").toObject();
Resources::Channel &ch = this->channels[roomID];
for (QJsonObject::iterator it = sets.begin(); it != sets.end(); ++it) {
QJsonObject versions = it.value().toObject().value("versions").toObject();
auto &badgeSet = ch.badgeSets[it.key().toStdString()];
auto &versionsMap = badgeSet.versions;
for (auto versionIt = std::begin(versions); versionIt != std::end(versions);
++versionIt) {
std::string kkey = versionIt.key().toStdString();
QJsonObject versionObj = versionIt.value().toObject();
BadgeVersion v(std::move(versionObj));
versionsMap.emplace(kkey, v);
}
}
ch.loaded = true;
return true;
});
req.execute();
QString cheermoteUrl = "https://api.twitch.tv/kraken/bits/actions?channel_id=" + roomID;
auto request = NetworkRequest::twitchRequest(cheermoteUrl);
request.setCaller(QThread::currentThread());
request.onSuccess([this, roomID](auto result) {
auto d = result.parseRapidJson();
Resources::Channel &ch = this->channels[roomID];
ParseCheermoteSets(ch.jsonCheermoteSets, d);
for (auto &set : ch.jsonCheermoteSets) {
CheermoteSet cheermoteSet;
cheermoteSet.regex = QRegularExpression("^" + set.prefix.toLower() + "([1-9][0-9]*)$");
for (auto &tier : set.tiers) {
Cheermote cheermote;
cheermote.color = QColor(tier.color);
cheermote.minBits = tier.minBits;
// TODO(pajlada): We currently hardcode dark here :|
// We will continue to do so for now since we haven't had to
// solve that anywhere else
cheermote.emoteDataAnimated.image1x = tier.images["dark"]["animated"]["1"];
cheermote.emoteDataAnimated.image2x = tier.images["dark"]["animated"]["2"];
cheermote.emoteDataAnimated.image3x = tier.images["dark"]["animated"]["4"];
cheermote.emoteDataStatic.image1x = tier.images["dark"]["static"]["1"];
cheermote.emoteDataStatic.image2x = tier.images["dark"]["static"]["2"];
cheermote.emoteDataStatic.image3x = tier.images["dark"]["static"]["4"];
cheermoteSet.cheermotes.emplace_back(cheermote);
}
std::sort(cheermoteSet.cheermotes.begin(), cheermoteSet.cheermotes.end(),
[](const auto &lhs, const auto &rhs) {
return lhs.minBits < rhs.minBits; //
});
ch.cheermoteSets.emplace_back(cheermoteSet);
}
return true;
});
request.execute();
}
void Resources::loadDynamicTwitchBadges()
{
static QString url("https://badges.twitch.tv/v1/badges/global/display?language=en");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) {
auto root = result.parseJson();
QJsonObject sets = root.value("badge_sets").toObject();
for (QJsonObject::iterator it = sets.begin(); it != sets.end(); ++it) {
QJsonObject versions = it.value().toObject().value("versions").toObject();
auto &badgeSet = this->badgeSets[it.key().toStdString()];
auto &versionsMap = badgeSet.versions;
for (auto versionIt = std::begin(versions); versionIt != std::end(versions);
++versionIt) {
std::string kkey = versionIt.key().toStdString();
QJsonObject versionObj = versionIt.value().toObject();
BadgeVersion v(std::move(versionObj));
versionsMap.emplace(kkey, v);
}
}
this->dynamicBadgesLoaded = true;
return true;
});
req.execute();
}
void Resources::loadChatterinoBadges()
{
this->chatterinoBadges.clear();
static QString url("https://fourtf.com/chatterino/badges.json");
NetworkRequest req(url);
req.setCaller(QThread::currentThread());
req.onSuccess([this](auto result) {
auto root = result.parseJson();
QJsonArray badgeVariants = root.value("badges").toArray();
for (QJsonArray::iterator it = badgeVariants.begin(); it != badgeVariants.end(); ++it) {
QJsonObject badgeVariant = it->toObject();
const std::string badgeVariantTooltip =
badgeVariant.value("tooltip").toString().toStdString();
const QString &badgeVariantImageURL = badgeVariant.value("image").toString();
auto badgeVariantPtr = std::make_shared<ChatterinoBadge>(
badgeVariantTooltip, new Image(badgeVariantImageURL));
QJsonArray badgeVariantUsers = badgeVariant.value("users").toArray();
for (QJsonArray::iterator it = badgeVariantUsers.begin(); it != badgeVariantUsers.end();
++it) {
const std::string username = it->toString().toStdString();
this->chatterinoBadges[username] =
std::shared_ptr<ChatterinoBadge>(badgeVariantPtr);
}
}
return true;
});
req.execute();
}
} // namespace chatterino
+1 -158
View File
@@ -1,160 +1,3 @@
#pragma once
#include "common/Singleton.hpp"
#include "common/Emotemap.hpp"
#include <QIcon>
#include <QRegularExpression>
#include <map>
#include <memory>
#include <mutex>
namespace chatterino {
class Resources : public Singleton
{
public:
Resources();
~Resources() = delete;
virtual void initialize(Application &app) override;
struct {
QIcon left;
QIcon right;
QIcon up;
QIcon down;
QIcon move;
} split;
struct {
QPixmap ban;
QPixmap unban;
QPixmap mod;
QPixmap unmod;
} buttons;
Image *badgeStaff;
Image *badgeAdmin;
Image *badgeGlobalModerator;
Image *badgeModerator;
Image *badgeTurbo;
Image *badgeBroadcaster;
Image *badgePremium;
Image *badgeVerified;
Image *badgeSubscriber;
Image *badgeCollapsed;
Image *cheerBadge100000;
Image *cheerBadge10000;
Image *cheerBadge5000;
Image *cheerBadge1000;
Image *cheerBadge100;
Image *cheerBadge1;
Image *moderationmode_enabled;
Image *moderationmode_disabled;
Image *splitHeaderContext;
std::map<std::string, Image *> cheerBadges;
struct BadgeVersion {
BadgeVersion() = delete;
explicit BadgeVersion(QJsonObject &&root);
Image *badgeImage1x;
Image *badgeImage2x;
Image *badgeImage4x;
std::string description;
std::string title;
std::string clickAction;
std::string clickURL;
};
struct BadgeSet {
std::map<std::string, BadgeVersion> versions;
};
std::map<std::string, BadgeSet> badgeSets;
bool dynamicBadgesLoaded = false;
Image *buttonBan;
Image *buttonTimeout;
Image *pajaDank;
Image *ppHop;
struct JSONCheermoteSet {
QString prefix;
std::vector<QString> scales;
std::vector<QString> backgrounds;
std::vector<QString> states;
QString type;
QString updatedAt;
int priority;
struct CheermoteTier {
int minBits;
QString id;
QString color;
// Background State Scale
std::map<QString, std::map<QString, std::map<QString, Image *>>> images;
};
std::vector<CheermoteTier> tiers;
};
struct Cheermote {
// a Cheermote indicates one tier
QColor color;
int minBits;
EmoteData emoteDataAnimated;
EmoteData emoteDataStatic;
};
struct CheermoteSet {
QRegularExpression regex;
std::vector<Cheermote> cheermotes;
};
struct Channel {
std::map<std::string, BadgeSet> badgeSets;
std::vector<JSONCheermoteSet> jsonCheermoteSets;
std::vector<CheermoteSet> cheermoteSets;
bool loaded = false;
};
// channelId
std::map<QString, Channel> channels;
// Chatterino badges
struct ChatterinoBadge {
ChatterinoBadge(const std::string &_tooltip, Image *_image)
: tooltip(_tooltip)
, image(_image)
{
}
std::string tooltip;
Image *image;
};
// username
std::map<std::string, std::shared_ptr<ChatterinoBadge>> chatterinoBadges;
void loadChannelData(const QString &roomID, bool bypassCache = false);
void loadDynamicTwitchBadges();
void loadChatterinoBadges();
};
} // namespace chatterino
#include "autogenerated/ResourcesAutogen.hpp"

Some files were not shown because too many files have changed in this diff Show More