Compare commits

..

4 Commits

Author SHA1 Message Date
WarmUpTill
c8f4e524ba Make deps/exprtk dependency optional 2026-09-28 21:10:59 +02:00
WarmUpTill
b104f98d02 Fix Twitch token status not reflecting reality when cached user ID empty 2026-09-25 19:43:24 +02:00
WarmUpTill
abc8c3708f Fix Twitch token being treated as invalid after load with broken config
Some checks failed
debian-build / build (push) Has been cancelled
Push to master / Check Formatting 🔍 (push) Has been cancelled
Push to master / Build Project 🧱 (push) Has been cancelled
Push to master / Create Release 🛫 (push) Has been cancelled
2026-09-23 09:32:30 +02:00
TheRealAlexV
3b63db2bde Fix crash in SendWebsocketVendorEvent during OBS shutdown
Some checks failed
debian-build / build (push) Has been cancelled
Push to master / Check Formatting 🔍 (push) Has been cancelled
Push to master / Build Project 🧱 (push) Has been cancelled
Push to master / Create Release 🛫 (push) Has been cancelled
Guard the vendor event emission with obs_get_module("obs-websocket").
During obs_shutdown() modules are unloaded one-by-one; obs-websocket is
unloaded before advanced-scene-switcher, so the proc handler pointer (_ph)
cached in obs-websocket-api.h is already stale when FreeSceneSwitcher()
runs its stop steps. proc_handler_call() then dereferences freed memory
(use-after-free in pthread_mutex_unlock).

The existing OBSIsShuttingDown() guard does not catch this path: the
forced-exit that follows a "Source Cleanup Error" (scene collection
switch) never fires the SCRIPTING_SHUTDOWN frontend event, so the
plugin's obsIsShuttingDown flag is not set. obs_get_module() returns NULL
once the module is unloaded, which is the reliable signal that
obs-websocket's proc handler is gone.

Refs: #1404
2026-09-13 11:08:04 +02:00
16 changed files with 119 additions and 296 deletions

View File

@@ -383,8 +383,18 @@ target_precompile_headers(${LIB_NAME} PRIVATE
"${CMAKE_CURRENT_SOURCE_DIR}/lib/pch.hpp") "${CMAKE_CURRENT_SOURCE_DIR}/lib/pch.hpp")
target_include_directories( target_include_directories(
${LIB_NAME} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/deps/obs-websocket/lib" ${LIB_NAME} PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/deps/obs-websocket/lib")
"${CMAKE_CURRENT_SOURCE_DIR}/deps/exprtk")
if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/deps/exprtk/exprtk.hpp")
target_include_directories(${LIB_NAME}
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/deps/exprtk")
target_compile_definitions(${LIB_NAME} PRIVATE EXPRTK_SUPPORT=1)
else()
message(
STATUS
"${PROJECT_NAME}: deps/exprtk not found - math expression support disabled"
)
endif()
if(NOT nlohmann_json_DIR if(NOT nlohmann_json_DIR
AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/deps/json/CMakeLists.txt") AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/deps/json/CMakeLists.txt")

View File

@@ -420,10 +420,11 @@ static bool queueWithNameExists(const std::string &name)
return !GetWeakActionQueueByName(name).expired(); return !GetWeakActionQueueByName(name).expired();
} }
static void static void signalImportedQueues(void *varsPtr)
signalImportedQueues(const std::vector<std::shared_ptr<Item>> &queues)
{ {
for (const auto &queue : queues) { auto queues = std::unique_ptr<std::vector<std::shared_ptr<Item>>>(
static_cast<std::vector<std::shared_ptr<Item>> *>(varsPtr));
for (const auto &queue : *queues) {
ActionQueueSignalManager::Instance()->Add( ActionQueueSignalManager::Instance()->Add(
QString::fromStdString(queue->Name())); QString::fromStdString(queue->Name()));
} }
@@ -435,7 +436,7 @@ void ImportQueues(obs_data_t *data)
obs_data_get_array(data, "actionQueues"); obs_data_get_array(data, "actionQueues");
size_t count = obs_data_array_count(array); size_t count = obs_data_array_count(array);
std::vector<std::shared_ptr<Item>> importedQueues; auto importedQueues = new std::vector<std::shared_ptr<Item>>;
for (size_t i = 0; i < count; i++) { for (size_t i = 0; i < count; i++) {
OBSDataAutoRelease arrayElement = obs_data_array_item(array, i); OBSDataAutoRelease arrayElement = obs_data_array_item(array, i);
@@ -445,11 +446,10 @@ void ImportQueues(obs_data_t *data)
continue; continue;
} }
queues.emplace_back(queue); queues.emplace_back(queue);
importedQueues.emplace_back(queue); importedQueues->emplace_back(queue);
} }
QueueUITask( QueueUITask(signalImportedQueues, importedQueues);
[importedQueues]() { signalImportedQueues(importedQueues); });
} }
std::weak_ptr<ActionQueue> GetWeakActionQueueByName(const std::string &name) std::weak_ptr<ActionQueue> GetWeakActionQueueByName(const std::string &name)

View File

@@ -2,13 +2,16 @@
#include "obs-module-helper.hpp" #include "obs-module-helper.hpp"
#include <climits> #include <climits>
#ifdef EXPRTK_SUPPORT
#include <exprtk.hpp> #include <exprtk.hpp>
#include <random> #include <random>
#endif
namespace advss { namespace advss {
std::variant<double, std::string> EvalMathExpression(const std::string &expr) std::variant<double, std::string> EvalMathExpression(const std::string &expr)
{ {
#ifdef EXPRTK_SUPPORT
static auto randomFunc = []() { static auto randomFunc = []() {
thread_local std::mt19937 gen(std::random_device{}()); thread_local std::mt19937 gen(std::random_device{}());
thread_local std::uniform_real_distribution<double> dis(0.0, thread_local std::uniform_real_distribution<double> dis(0.0,
@@ -26,6 +29,7 @@ std::variant<double, std::string> EvalMathExpression(const std::string &expr)
if (parser.compile(expr, expression)) { if (parser.compile(expr, expression)) {
return expression.value(); return expression.value();
} }
#endif
return std::string(obs_module_text( return std::string(obs_module_text(
"AdvSceneSwitcher.math.expressionFail")) + "AdvSceneSwitcher.math.expressionFail")) +
" \"" + expr + "\""; " \"" + expr + "\"";

View File

@@ -734,10 +734,12 @@ TempVarSignalManager *TempVarSignalManager::Instance()
void NotifyUIAboutTempVarChange(MacroSegment *segment) void NotifyUIAboutTempVarChange(MacroSegment *segment)
{ {
IncrementTempVarInUseGeneration(); IncrementTempVarInUseGeneration();
QueueUITask([segment]() { QueueUITask(
TempVarSignalManager::Instance()->SegmentTempVarsChanged( [](void *segment) {
segment); TempVarSignalManager::Instance()->SegmentTempVarsChanged(
}); (MacroSegment *)segment);
},
segment);
} }
TempVarOutputMappingsWidget::TempVarOutputMappingsWidget(QWidget *parent) TempVarOutputMappingsWidget::TempVarOutputMappingsWidget(QWidget *parent)

View File

@@ -184,9 +184,9 @@ std::string GetThemeTypeName()
#endif #endif
} }
void QueueUITaskRaw(void (*task)(void *param), void *param, bool wait) void QueueUITask(void (*task)(void *param), void *param)
{ {
obs_queue_task(OBS_TASK_UI, task, param, wait); obs_queue_task(OBS_TASK_UI, task, param, false);
} }
bool IsCursorInWidgetArea(QWidget *widget) bool IsCursorInWidgetArea(QWidget *widget)

View File

@@ -6,10 +6,7 @@
#include <QIcon> #include <QIcon>
#include <QString> #include <QString>
#include <memory>
#include <string> #include <string>
#include <type_traits>
#include <utility>
class QAbstractButton; class QAbstractButton;
class QComboBox; class QComboBox;
@@ -41,23 +38,7 @@ EXPORT void DisplayTrayMessage(const QString &title, const QString &msg,
EXPORT std::string GetThemeTypeName(); EXPORT std::string GetThemeTypeName();
EXPORT QWidget *GetSettingsWindow(); EXPORT QWidget *GetSettingsWindow();
EXPORT void QueueUITaskRaw(void (*task)(void *param), void *param, EXPORT void QueueUITask(void (*task)(void *param), void *param);
bool wait = false);
// Runs func on the main/UI thread; blocks if wait is true.
template<typename F> void QueueUITask(F &&func, bool wait = false)
{
using FnType = std::decay_t<F>;
auto *heapFunc = new FnType(std::forward<F>(func));
QueueUITaskRaw(
[](void *param) {
std::unique_ptr<FnType> fn(
static_cast<FnType *>(param));
(*fn)();
},
heapFunc, wait);
}
bool IsCursorInWidgetArea(QWidget *widget); bool IsCursorInWidgetArea(QWidget *widget);

View File

@@ -127,9 +127,10 @@ void RegisterWebsocketRequest(
void SendWebsocketVendorEvent(const std::string &eventName, obs_data_t *data) void SendWebsocketVendorEvent(const std::string &eventName, obs_data_t *data)
{ {
if (OBSIsShuttingDown()) { if (OBSIsShuttingDown() || !obs_get_module("obs-websocket")) {
return; return;
} }
obs_websocket_vendor_emit_event(vendor, eventName.c_str(), data); obs_websocket_vendor_emit_event(vendor, eventName.c_str(), data);
} }

View File

@@ -504,10 +504,11 @@ void LoadVariables(obs_data_t *obj)
} }
} }
static void static void signalImportedVariables(void *varsPtr)
signalImportedVariables(const std::vector<std::shared_ptr<Item>> &vars)
{ {
for (const auto &var : vars) { auto vars = std::unique_ptr<std::vector<std::shared_ptr<Item>>>(
static_cast<std::vector<std::shared_ptr<Item>> *>(varsPtr));
for (const auto &var : *vars) {
VariableSignalManager::Instance()->Add( VariableSignalManager::Instance()->Add(
QString::fromStdString(var->Name())); QString::fromStdString(var->Name()));
} }
@@ -518,7 +519,7 @@ void ImportVariables(obs_data_t *data)
OBSDataArrayAutoRelease array = obs_data_get_array(data, "variables"); OBSDataArrayAutoRelease array = obs_data_get_array(data, "variables");
size_t count = obs_data_array_count(array); size_t count = obs_data_array_count(array);
std::vector<std::shared_ptr<Item>> importedVars; auto importedVars = new std::vector<std::shared_ptr<Item>>;
for (size_t i = 0; i < count; i++) { for (size_t i = 0; i < count; i++) {
OBSDataAutoRelease arrayElement = obs_data_array_item(array, i); OBSDataAutoRelease arrayElement = obs_data_array_item(array, i);
@@ -530,11 +531,10 @@ void ImportVariables(obs_data_t *data)
} }
GetVariables().emplace_back(var); GetVariables().emplace_back(var);
importedVars.emplace_back(var); importedVars->emplace_back(var);
} }
QueueUITask( QueueUITask(signalImportedVariables, importedVars);
[importedVars]() { signalImportedVariables(importedVars); });
} }
std::chrono::high_resolution_clock::time_point GetLastVariableChangeTime() std::chrono::high_resolution_clock::time_point GetLastVariableChangeTime()

View File

@@ -17,6 +17,20 @@ bool MacroActionSceneCollection::_registered = MacroActionFactory::Register(
MacroActionSceneCollectionEdit::Create, MacroActionSceneCollectionEdit::Create,
"AdvSceneSwitcher.action.sceneCollection"}); "AdvSceneSwitcher.action.sceneCollection"});
template<typename F> void QueueUITaskLambda(F &&func)
{
using FnType = std::decay_t<F>;
auto *heapFunc = new FnType(std::forward<F>(func));
QueueUITask(
[](void *param) {
std::unique_ptr<FnType> fn(
static_cast<FnType *>(param));
(*fn)();
},
heapFunc);
}
bool MacroActionSceneCollection::PerformAction() bool MacroActionSceneCollection::PerformAction()
{ {
// Changing the scene collection will also reload the settings of the // Changing the scene collection will also reload the settings of the
@@ -27,7 +41,7 @@ bool MacroActionSceneCollection::PerformAction()
} }
const auto collectionName = _sceneCollection; const auto collectionName = _sceneCollection;
QueueUITask([collectionName]() { QueueUITaskLambda([collectionName]() {
obs_frontend_set_current_scene_collection( obs_frontend_set_current_scene_collection(
collectionName.c_str()); collectionName.c_str());
}); });

View File

@@ -185,6 +185,20 @@ static void closeSourceDialog(obs_source_t *source, bool accept,
} }
} }
template<typename F> void QueueUITaskLambda(F &&func)
{
using FnType = std::decay_t<F>;
auto *heapFunc = new FnType(std::forward<F>(func));
QueueUITask(
[](void *param) {
std::unique_ptr<FnType> fn(
static_cast<FnType *>(param));
(*fn)();
},
heapFunc);
}
bool MacroActionSource::PerformAction() bool MacroActionSource::PerformAction()
{ {
OBSSource s = obs_weak_source_get_source(_source.GetSource()); OBSSource s = obs_weak_source_get_source(_source.GetSource());
@@ -257,17 +271,17 @@ bool MacroActionSource::PerformAction()
break; break;
} }
QueueUITask([&]() { QueueUITaskLambda([&]() {
closeSourceDialog(s, true, "OBSBasicInteraction"); closeSourceDialog(s, true, "OBSBasicInteraction");
}); });
break; break;
case Action::CLOSE_FILTER_DIALOG: case Action::CLOSE_FILTER_DIALOG:
QueueUITask([&]() { QueueUITaskLambda([&]() {
closeSourceDialog(s, _acceptDialog, "OBSBasicFilters"); closeSourceDialog(s, _acceptDialog, "OBSBasicFilters");
}); });
break; break;
case Action::CLOSE_PROPERTIES_DIALOG: case Action::CLOSE_PROPERTIES_DIALOG:
QueueUITask([&]() { QueueUITaskLambda([&]() {
closeSourceDialog(s, _acceptDialog, closeSourceDialog(s, _acceptDialog,
"OBSBasicProperties"); "OBSBasicProperties");
}); });

View File

@@ -5,74 +5,8 @@
#include <QFileDialog> #include <QFileDialog>
#ifdef __APPLE__
#include <spawn.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
#include <poll.h>
#include <csignal>
#include <cerrno>
#include <chrono>
#include <thread>
#include <vector>
extern char **environ;
#endif
namespace advss { namespace advss {
#ifdef __APPLE__
// QProcess uses fork(), which is unsafe to call in OBS's multi-threaded,
// CEF/XPC-using process (see fork(2)). posix_spawn() avoids fork() entirely.
namespace {
std::vector<char *> BuildArgv(const std::string &path, const QStringList &args,
std::vector<std::string> &storage)
{
storage.push_back(path);
for (auto &arg : args) {
storage.push_back(arg.toStdString());
}
std::vector<char *> argv;
argv.reserve(storage.size() + 1);
for (auto &arg : storage) {
argv.push_back(const_cast<char *>(arg.c_str()));
}
argv.push_back(nullptr);
return argv;
}
bool DrainPipe(int fd, std::string &buffer)
{
char chunk[4096];
while (true) {
ssize_t n = read(fd, chunk, sizeof(chunk));
if (n > 0) {
buffer.append(chunk, static_cast<size_t>(n));
continue;
}
if (n == 0) {
return false; // EOF
}
if (errno == EINTR) {
continue;
}
return true; // EAGAIN/EWOULDBLOCK
}
}
std::string TrimTrailingNewline(const std::string &s)
{
static const QRegularExpression regex("(\\r\\n|\\r|\\n)$");
return QString::fromStdString(s).remove(regex).toStdString();
}
} // namespace
#endif
bool ProcessConfig::Save(obs_data_t *obj) const bool ProcessConfig::Save(obs_data_t *obj) const
{ {
auto data = obs_data_create(); auto data = obs_data_create();
@@ -116,44 +50,11 @@ QStringList ProcessConfig::Args() const
return result; return result;
} }
#ifdef __APPLE__
bool ProcessConfig::StartProcessDetached() const
{
auto path = Path();
auto workDir = WorkingDir();
std::vector<std::string> argStorage;
auto argv = BuildArgv(path, Args(), argStorage);
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
if (!workDir.empty()) {
posix_spawn_file_actions_addchdir_np(&actions, workDir.c_str());
}
pid_t pid = 0;
int rc = posix_spawn(&pid, path.c_str(), &actions, nullptr, argv.data(),
environ);
posix_spawn_file_actions_destroy(&actions);
if (rc != 0) {
return false;
}
std::thread([pid]() {
int status = 0;
while (waitpid(pid, &status, 0) == -1 && errno == EINTR) {
}
}).detach();
return true;
}
#else
bool ProcessConfig::StartProcessDetached() const bool ProcessConfig::StartProcessDetached() const
{ {
return QProcess::startDetached(QString::fromStdString(Path()), Args(), return QProcess::startDetached(QString::fromStdString(Path()), Args(),
QString::fromStdString(WorkingDir())); QString::fromStdString(WorkingDir()));
} }
#endif
void ProcessConfig::ResolveVariables() void ProcessConfig::ResolveVariables()
{ {
@@ -162,139 +63,6 @@ void ProcessConfig::ResolveVariables()
_args.ResolveVariables(); _args.ResolveVariables();
} }
#ifdef __APPLE__
std::variant<int, ProcessConfig::ProcStartError>
ProcessConfig::StartProcessAndWait(int timeout)
{
ResetFinishedProcessData();
vblog(LOG_INFO, "run \"%s\" with a timeout of %d ms", Path().c_str(),
timeout);
int outPipe[2];
int errPipe[2];
if (pipe(outPipe) != 0 || pipe(errPipe) != 0) {
vblog(LOG_INFO, "failed to start \"%s\"!", Path().c_str());
return ProcStartError::FAILED_TO_START;
}
auto path = Path();
auto workDir = WorkingDir();
std::vector<std::string> argStorage;
auto argv = BuildArgv(path, Args(), argStorage);
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
posix_spawn_file_actions_addclose(&actions, outPipe[0]);
posix_spawn_file_actions_addclose(&actions, errPipe[0]);
posix_spawn_file_actions_adddup2(&actions, outPipe[1], STDOUT_FILENO);
posix_spawn_file_actions_adddup2(&actions, errPipe[1], STDERR_FILENO);
posix_spawn_file_actions_addclose(&actions, outPipe[1]);
posix_spawn_file_actions_addclose(&actions, errPipe[1]);
if (!workDir.empty()) {
posix_spawn_file_actions_addchdir_np(&actions, workDir.c_str());
}
pid_t pid = 0;
int rc = posix_spawn(&pid, path.c_str(), &actions, nullptr, argv.data(),
environ);
posix_spawn_file_actions_destroy(&actions);
close(outPipe[1]);
close(errPipe[1]);
if (rc != 0) {
close(outPipe[0]);
close(errPipe[0]);
vblog(LOG_INFO, "failed to start \"%s\"!", Path().c_str());
return ProcStartError::FAILED_TO_START;
}
SetProcessId(std::to_string(pid));
fcntl(outPipe[0], F_SETFL, O_NONBLOCK);
fcntl(errPipe[0], F_SETFL, O_NONBLOCK);
std::string outBuf;
std::string errBuf;
bool outDone = false;
bool errDone = false;
auto deadline = std::chrono::steady_clock::now() +
std::chrono::milliseconds(timeout);
while (!outDone || !errDone) {
auto remaining =
std::chrono::duration_cast<std::chrono::milliseconds>(
deadline - std::chrono::steady_clock::now())
.count();
if (remaining <= 0) {
break;
}
struct pollfd fds[2];
int n = 0;
int outIdx = -1;
int errIdx = -1;
if (!outDone) {
fds[n] = {outPipe[0], POLLIN, 0};
outIdx = n++;
}
if (!errDone) {
fds[n] = {errPipe[0], POLLIN, 0};
errIdx = n++;
}
int pr = poll(fds, n, static_cast<int>(remaining));
if (pr < 0) {
if (errno == EINTR) {
continue;
}
break;
}
if (outIdx >= 0 && fds[outIdx].revents != 0) {
if (!DrainPipe(outPipe[0], outBuf)) {
outDone = true;
}
}
if (errIdx >= 0 && fds[errIdx].revents != 0) {
if (!DrainPipe(errPipe[0], errBuf)) {
errDone = true;
}
}
}
close(outPipe[0]);
close(errPipe[0]);
if (!outDone || !errDone) {
vblog(LOG_INFO,
"timeout while running \"%s\"\nAttempting to kill process!",
Path().c_str());
kill(pid, SIGKILL);
int status = 0;
while (waitpid(pid, &status, 0) == -1 && errno == EINTR) {
}
_processOutputStream = TrimTrailingNewline(outBuf);
_processErrorStream = TrimTrailingNewline(errBuf);
return ProcStartError::TIMEOUT;
}
int status = 0;
while (waitpid(pid, &status, 0) == -1 && errno == EINTR) {
}
_processOutputStream = TrimTrailingNewline(outBuf);
_processErrorStream = TrimTrailingNewline(errBuf);
if (WIFEXITED(status)) {
int exitCode = WEXITSTATUS(status);
_processExitCode = std::to_string(exitCode);
return exitCode;
}
vblog(LOG_INFO, "process \"%s\" crashed!", Path().c_str());
return ProcStartError::CRASH;
}
#else
std::variant<int, ProcessConfig::ProcStartError> std::variant<int, ProcessConfig::ProcStartError>
ProcessConfig::StartProcessAndWait(int timeout) ProcessConfig::StartProcessAndWait(int timeout)
{ {
@@ -333,7 +101,6 @@ ProcessConfig::StartProcessAndWait(int timeout)
vblog(LOG_INFO, "process \"%s\" crashed!", Path().c_str()); vblog(LOG_INFO, "process \"%s\" crashed!", Path().c_str());
return ProcStartError::CRASH; return ProcStartError::CRASH;
} }
#endif
void ProcessConfig::SetFinishedProcessData(QProcess &process) void ProcessConfig::SetFinishedProcessData(QProcess &process)
{ {

View File

@@ -233,7 +233,12 @@ void TwitchToken::Load(obs_data_t *obj)
{ {
Item::Load(obj); Item::Load(obj);
_token = obs_data_get_string(obj, "token"); _token = obs_data_get_string(obj, "token");
_userID = obs_data_get_string(obj, "userID"); if (obs_data_has_user_value(obj, "userID") &&
*obs_data_get_string(obj, "userID") != '\0') {
_userID = obs_data_get_string(obj, "userID");
} else {
_userID = {};
}
obs_data_set_default_bool(obj, "validateEventSubTimestamps", true); obs_data_set_default_bool(obj, "validateEventSubTimestamps", true);
_validateEventSubTimestamps = _validateEventSubTimestamps =
obs_data_get_bool(obj, "validateEventSubTimestamps"); obs_data_get_bool(obj, "validateEventSubTimestamps");
@@ -255,7 +260,7 @@ void TwitchToken::Save(obs_data_t *obj) const
{ {
Item::Save(obj); Item::Save(obj);
obs_data_set_string(obj, "token", _token.c_str()); obs_data_set_string(obj, "token", _token.c_str());
if (_userID) { if (_userID && !_userID->empty()) {
obs_data_set_string(obj, "userID", _userID->c_str()); obs_data_set_string(obj, "userID", _userID->c_str());
} }
obs_data_set_bool(obj, "validateEventSubTimestamps", obs_data_set_bool(obj, "validateEventSubTimestamps",
@@ -310,7 +315,7 @@ bool TwitchToken::AnyOptionIsEnabled(
return false; return false;
} }
void TwitchToken::SetToken(const std::string &value) bool TwitchToken::SetToken(const std::string &value)
{ {
_token = value; _token = value;
auto res = auto res =
@@ -318,21 +323,34 @@ void TwitchToken::SetToken(const std::string &value)
if (res.status != 200) { if (res.status != 200) {
blog(LOG_WARNING, "failed to get Twitch user id from token!"); blog(LOG_WARNING, "failed to get Twitch user id from token!");
_userID = {}; _userID = {};
return; return false;
} }
bool gotUserID = false;
OBSDataArrayAutoRelease array = obs_data_get_array(res.data, "data"); OBSDataArrayAutoRelease array = obs_data_get_array(res.data, "data");
size_t count = obs_data_array_count(array); size_t count = obs_data_array_count(array);
for (size_t i = 0; i < count; i++) { for (size_t i = 0; i < count; i++) {
OBSDataAutoRelease arrayObj = obs_data_array_item(array, i); OBSDataAutoRelease arrayObj = obs_data_array_item(array, i);
_userID = obs_data_get_string(arrayObj, "id"); std::string id = obs_data_get_string(arrayObj, "id");
if (id.empty()) {
blog(LOG_WARNING,
"Twitch /helix/users response did not contain a user id!");
continue;
}
_userID = id;
_name = obs_data_get_string(arrayObj, "display_name"); _name = obs_data_get_string(arrayObj, "display_name");
gotUserID = true;
}
if (!gotUserID) {
return false;
} }
// Trigger resubscribes with new token // Trigger resubscribes with new token
if (_eventSub) { if (_eventSub) {
_eventSub->ClearActiveSubscriptions(); _eventSub->ClearActiveSubscriptions();
} }
return true;
} }
std::optional<std::string> TwitchToken::GetToken() const std::optional<std::string> TwitchToken::GetToken() const
@@ -388,7 +406,7 @@ bool TwitchToken::IsValid(bool forceUpdate) const
return false; return false;
} }
if (_userID && _userID != id) { if (_userID && !_userID->empty() && _userID != id) {
blog(LOG_INFO, blog(LOG_INFO,
"Twitch token %s does not match expected user (got %s, expected %s)!", "Twitch token %s does not match expected user (got %s, expected %s)!",
_name.c_str(), id, _userID->c_str()); _name.c_str(), id, _userID->c_str());
@@ -396,6 +414,10 @@ bool TwitchToken::IsValid(bool forceUpdate) const
return false; return false;
} }
if (!_userID || _userID->empty()) {
_userID = id;
}
_lastValidityCheckResult = true; _lastValidityCheckResult = true;
return true; return true;
}; };
@@ -819,9 +841,9 @@ void TwitchTokenSettingsDialog::GotToken(const std::optional<QString> &value)
return; return;
} }
_currentToken.SetToken(value.value().toStdString()); bool success = _currentToken.SetToken(value.value().toStdString());
auto name = QString::fromStdString(_currentToken._name); auto name = QString::fromStdString(_currentToken._name);
if (name.isEmpty()) { if (!success || name.isEmpty()) {
_tokenStatus->setText(obs_module_text( _tokenStatus->setText(obs_module_text(
"AdvSceneSwitcher.twitchToken.request.fail")); "AdvSceneSwitcher.twitchToken.request.fail"));
_name->setText(""); _name->setText("");

View File

@@ -48,7 +48,7 @@ public:
bool OptionIsActive(const TokenOption &option) const; bool OptionIsActive(const TokenOption &option) const;
bool OptionIsEnabled(const TokenOption &option) const; bool OptionIsEnabled(const TokenOption &option) const;
bool AnyOptionIsEnabled(const std::vector<TokenOption> &options) const; bool AnyOptionIsEnabled(const std::vector<TokenOption> &options) const;
void SetToken(const std::string &); bool SetToken(const std::string &);
bool IsEmpty() const { return _token.empty(); } bool IsEmpty() const { return _token.empty(); }
std::optional<std::string> GetToken() const; std::optional<std::string> GetToken() const;
std::optional<std::string> GetUserID() const { return _userID; } std::optional<std::string> GetUserID() const { return _userID; }
@@ -65,7 +65,7 @@ private:
mutable std::string _lastValidityCheckValue; mutable std::string _lastValidityCheckValue;
mutable bool _lastValidityCheckResult = false; mutable bool _lastValidityCheckResult = false;
mutable std::chrono::system_clock::time_point _lastValidityCheckTime; mutable std::chrono::system_clock::time_point _lastValidityCheckTime;
std::optional<std::string> _userID; mutable std::optional<std::string> _userID;
std::set<TokenOption> _tokenOptions = TokenOption::GetAllTokenOptions(); std::set<TokenOption> _tokenOptions = TokenOption::GetAllTokenOptions();
std::shared_ptr<EventSub> _eventSub; std::shared_ptr<EventSub> _eventSub;
bool _validateEventSubTimestamps = false; bool _validateEventSubTimestamps = false;

View File

@@ -31,9 +31,14 @@ static bool setup()
static const auto showInvalidWarnings = [](void *) { static const auto showInvalidWarnings = [](void *) {
const auto invalidTokens = getInvalidTokens(); const auto invalidTokens = getInvalidTokens();
for (const auto &token : invalidTokens) { for (const auto &token : invalidTokens) {
QueueUITask([token]() { QueueUITask(
InvalidTokenDialog::ShowWarning(token); [](void *tokenPtr) {
}); auto tokenName = static_cast<QString *>(
tokenPtr);
InvalidTokenDialog::ShowWarning(
*tokenName);
},
(void *)&token);
} }
}; };

View File

@@ -85,8 +85,11 @@ target_sources(
${PROJECT_NAME} ${PROJECT_NAME}
PRIVATE test-math.cpp ${ADVSS_SOURCE_DIR}/lib/utils/math-helpers.cpp PRIVATE test-math.cpp ${ADVSS_SOURCE_DIR}/lib/utils/math-helpers.cpp
${ADVSS_SOURCE_DIR}/lib/utils/obs-module-helper.cpp) ${ADVSS_SOURCE_DIR}/lib/utils/obs-module-helper.cpp)
target_include_directories(${PROJECT_NAME} if(EXISTS "${ADVSS_SOURCE_DIR}/deps/exprtk/exprtk.hpp")
PRIVATE ${ADVSS_SOURCE_DIR}/deps/exprtk) target_include_directories(${PROJECT_NAME}
PRIVATE ${ADVSS_SOURCE_DIR}/deps/exprtk)
target_compile_definitions(${PROJECT_NAME} PRIVATE EXPRTK_SUPPORT=1)
endif()
if(MSVC) if(MSVC)
target_compile_options(${PROJECT_NAME} PUBLIC /MP /d2FH4- /wd4267 /bigobj) target_compile_options(${PROJECT_NAME} PUBLIC /MP /d2FH4- /wd4267 /bigobj)

View File

@@ -40,7 +40,7 @@ std::string GetThemeTypeName()
return "Dark"; return "Dark";
} }
void QueueUITaskRaw(void (*task)(void *param), void *, bool) {} void QueueUITask(void (*task)(void *param), void *) {}
QWidget *GetSettingsWindow() QWidget *GetSettingsWindow()
{ {