Add YouTube plugin with connection support

This commit is contained in:
WarmUpTill
2026-11-09 19:47:59 +01:00
parent 1d5fa1752d
commit d699298fe0
13 changed files with 1772 additions and 0 deletions

View File

@@ -158,6 +158,16 @@ AdvSceneSwitcher.twitchConnectionTab.yes="Yes"
AdvSceneSwitcher.twitchConnectionTab.no="No"
AdvSceneSwitcher.twitchConnectionTab.removeSingleConnectionPopup.text="Are you sure you want to remove \"%1\"?"
AdvSceneSwitcher.twitchConnectionTab.removeMultipleConnectionsPopup.text="Are you sure you want to remove %1 Twitch connections?"
AdvSceneSwitcher.youtubeConnectionTab.title="YouTube Connections"
AdvSceneSwitcher.youtubeConnectionTab.help="YouTube connections can be used to perform actions on the linked YouTube channel or to check its state in conditions.\n\nClick on the highlighted plus symbol to add a new connection."
AdvSceneSwitcher.youtubeConnectionTab.addButton.tooltip="Add new YouTube connection"
AdvSceneSwitcher.youtubeConnectionTab.removeButton.tooltip="Remove selected YouTube connections"
AdvSceneSwitcher.youtubeConnectionTab.name.header="Name"
AdvSceneSwitcher.youtubeConnectionTab.isValid.header="Is valid?"
AdvSceneSwitcher.youtubeConnectionTab.yes="Yes"
AdvSceneSwitcher.youtubeConnectionTab.no="No"
AdvSceneSwitcher.youtubeConnectionTab.removeSingleConnectionPopup.text="Are you sure you want to remove \"%1\"?"
AdvSceneSwitcher.youtubeConnectionTab.removeMultipleConnectionsPopup.text="Are you sure you want to remove %1 YouTube connections?"
# MQTT Connections Tab
AdvSceneSwitcher.mqttConnectionTab.title="MQTT Connections"
@@ -240,6 +250,7 @@ AdvSceneSwitcher.macroTab.export.actionQueues="Action Queues"
AdvSceneSwitcher.macroTab.export.httpServers="HTTP Servers"
AdvSceneSwitcher.macroTab.export.macroScheduleEntries="Macro Schedule"
AdvSceneSwitcher.macroTab.export.twitchConnections="Twitch Connections"
AdvSceneSwitcher.macroTab.export.youtubeConnections="YouTube Connections"
AdvSceneSwitcher.macroTab.export.websocketConnections="Websocket Connections"
AdvSceneSwitcher.macroTab.export.importPrompts.edit="Define import prompts..."
AdvSceneSwitcher.macroTab.export.importPrompts.info="Mark values below as \"replaceable\": whoever imports this macro will be prompted to supply their own value for each one you add (e.g. a scene, a source, or a file path that only exists on your setup)."
@@ -1926,6 +1937,35 @@ AdvSceneSwitcher.twitchToken.validateTimestamps.tooltip="Verifies that incoming
AdvSceneSwitcher.twitchToken.warnIfInvalid="Display warning if the token expired or is invalid."
AdvSceneSwitcher.twitchToken.warnIfInvalid.doNotShowAgain="Don't show again for this connection"
AdvSceneSwitcher.twitchToken.warnIfInvalid.message="The Twitch connection \"%1\" is invalid.\nOpen connection settings or ignore?"
AdvSceneSwitcher.youtubeConnection.select="--select YouTube connection--"
AdvSceneSwitcher.youtubeConnection.add="Add new connection"
AdvSceneSwitcher.youtubeConnection.nameNotAvailable="Channel already in use"
AdvSceneSwitcher.youtubeConnection.configure="Configure YouTube connection settings"
AdvSceneSwitcher.youtubeConnection.invalid="Invalid YouTube connection"
AdvSceneSwitcher.youtubeConnection.name="Channel name:"
AdvSceneSwitcher.youtubeConnection.clientId="Client ID:"
AdvSceneSwitcher.youtubeConnection.clientSecret="Client secret:"
AdvSceneSwitcher.youtubeConnection.clientConfig.help="YouTube connections use the OAuth credentials of your own Google Cloud project:\n\n1. Create a project at console.cloud.google.com\n2. Enable the \"YouTube Data API v3\"\n3. Configure the OAuth consent screen with the audience \"External\"\n4. Set the publishing status to \"In production\", otherwise the connection expires after 7 days\n5. Create an OAuth client ID of the type \"Desktop app\"\n6. Enter the client ID and client secret here"
AdvSceneSwitcher.youtubeConnection.connect="Connect Account"
AdvSceneSwitcher.youtubeConnection.connect.waiting="Waiting for approval in the browser ... (%1 s)"
AdvSceneSwitcher.youtubeConnection.connect.success="Account is connected!"
AdvSceneSwitcher.youtubeConnection.connect.notConnected="Account is not connected!"
AdvSceneSwitcher.youtubeConnection.connect.success.browser="Authentication successful! You can close this window now."
AdvSceneSwitcher.youtubeConnection.connect.fail.browser="Authentication failed! (%1)\nYou can close this window now."
AdvSceneSwitcher.youtubeConnection.connect.fail.stateMismatch="State mismatch"
AdvSceneSwitcher.youtubeConnection.error.missingClientConfig="Client ID and client secret are required!"
AdvSceneSwitcher.youtubeConnection.error.accessDenied="Access was denied!\nIf the publishing status of your Google Cloud project is \"Testing\", make sure your Google account is added as a test user."
AdvSceneSwitcher.youtubeConnection.error.invalidClient="Client ID or client secret is invalid!"
AdvSceneSwitcher.youtubeConnection.error.invalidGrant="The authorization expired or was revoked!\nPlease connect the account again."
AdvSceneSwitcher.youtubeConnection.error.apiNotEnabled="The \"YouTube Data API v3\" is not enabled for your Google Cloud project!"
AdvSceneSwitcher.youtubeConnection.error.noChannel="The connected Google account does not have a YouTube channel!"
AdvSceneSwitcher.youtubeConnection.error.timeout="Timed out waiting for approval in the browser!"
AdvSceneSwitcher.youtubeConnection.error.network="Failed to reach the Google servers!"
AdvSceneSwitcher.youtubeConnection.error.server="Failed to start the local server receiving the authorization!"
AdvSceneSwitcher.youtubeConnection.error.unknown="Failed to connect the account! (%1)"
AdvSceneSwitcher.youtubeConnection.warnIfInvalid="Display warning if the connection expired or is invalid."
AdvSceneSwitcher.youtubeConnection.warnIfInvalid.doNotShowAgain="Don't show again for this connection"
AdvSceneSwitcher.youtubeConnection.warnIfInvalid.message="The YouTube connection \"%1\" is invalid.\nOpen connection settings or ignore?"
AdvSceneSwitcher.twitch.selection.channel.open="Open channel"
AdvSceneSwitcher.twitch.selection.channel.open.tooltip.details="Open channel in external application handling the HTTPS protocol."

View File

@@ -43,6 +43,7 @@ add_plugin(usb)
add_plugin(video)
add_plugin(speech)
add_plugin(now-playing)
add_plugin(youtube)
# ---------------------------------------------------------------------------- #

View File

@@ -0,0 +1,78 @@
cmake_minimum_required(VERSION 3.14)
project(advanced-scene-switcher-youtube)
# --- Check requirements ---
get_target_property(ADVSS_SOURCE_DIR advanced-scene-switcher-lib SOURCE_DIR)
set(CPP_HTTPLIB_DIR "${ADVSS_SOURCE_DIR}/deps/cpp-httplib")
if(NOT EXISTS "${CPP_HTTPLIB_DIR}/CMakeLists.txt")
message(WARNING "cpp-httplib directory \"${CPP_HTTPLIB_DIR}\" not found!\n"
"YouTube support will be disabled!")
return()
endif()
if(NOT TARGET httplib)
add_subdirectory("${CPP_HTTPLIB_DIR}" "${CPP_HTTPLIB_DIR}/build"
EXCLUDE_FROM_ALL)
endif()
if(OS_MACOS OR OS_WINDOWS)
set(OPENSSL_USE_STATIC_LIBS
ON
CACHE BOOL "Use static OpenSSL" FORCE)
endif()
find_package(OpenSSL)
if(NOT OPENSSL_FOUND)
message(WARNING "OpenSSL not found!\n"
"YouTube support will be disabled!\n\n")
return()
endif()
if(OS_WINDOWS AND NOT OPENSSL_CRYPTO_LIBRARY MATCHES "_static\\.lib$")
message(
WARNING
"Static OpenSSL libraries (libcrypto_static.lib / libssl_static.lib) not found!\n"
"YouTube support will be disabled to avoid DLL name collisions with other plugins.\n\n"
)
return()
endif()
find_package(ZLIB)
if(NOT ZLIB_FOUND)
message(WARNING "zlib not found!\n" "YouTube support will be disabled!\n\n")
return()
endif()
# --- End of section ---
add_library(${PROJECT_NAME} MODULE)
target_compile_definitions(${PROJECT_NAME} PRIVATE CPPHTTPLIB_OPENSSL_SUPPORT=1)
if(OS_MACOS)
target_compile_definitions(
${PROJECT_NAME} PRIVATE CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN=1)
target_link_libraries(${PROJECT_NAME} PRIVATE "-framework CoreFoundation")
target_link_libraries(${PROJECT_NAME} PRIVATE "-framework Security")
endif()
if(MSVC)
target_compile_options(${PROJECT_NAME} PRIVATE /wd4834)
endif()
target_sources(
${PROJECT_NAME}
PRIVATE youtube-connection.cpp
youtube-connection.hpp
youtube-helpers.cpp
youtube-helpers.hpp
youtube-oauth.cpp
youtube-oauth.hpp
youtube-tab.cpp
youtube-tab.hpp)
setup_advss_plugin(${PROJECT_NAME})
set_target_properties(${PROJECT_NAME} PROPERTIES PREFIX "")
target_include_directories(${PROJECT_NAME} PRIVATE "${CPP_HTTPLIB_DIR}/"
"${OPENSSL_INCLUDE_DIR}")
target_link_libraries(${PROJECT_NAME} PRIVATE ${OPENSSL_LIBRARIES} ZLIB::ZLIB)
if(OS_WINDOWS)
target_link_libraries(${PROJECT_NAME} PRIVATE ws2_32 crypt32 bcrypt)
endif()
install_advss_plugin(${PROJECT_NAME})

View File

@@ -0,0 +1,680 @@
#include "youtube-connection.hpp"
#include "youtube-helpers.hpp"
#include "youtube-tab.hpp"
#include <help-icon.hpp>
#include <log-helper.hpp>
#include <macro-export-extensions.hpp>
#include <obs-module-helper.hpp>
#include <plugin-state-helpers.hpp>
#include <ui-helpers.hpp>
#include <QDesktopServices>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QUrl>
#include <QVBoxLayout>
#include <algorithm>
#include <thread>
#include <unordered_map>
namespace advss {
static const int authTimeoutSeconds = 120;
static const int refreshRetryDelaySeconds = 30;
static std::deque<std::shared_ptr<Item>> youtubeConnections;
static void saveConnections(obs_data_t *obj);
static void loadConnections(obs_data_t *obj);
static void exportConnections(obs_data_t *data, const QStringList &selectedIds)
{
OBSDataArrayAutoRelease array = obs_data_array_create();
for (const auto &item : youtubeConnections) {
if (!selectedIds.isEmpty() &&
!selectedIds.contains(
QString::fromStdString(item->Name()))) {
continue;
}
auto connection =
std::dynamic_pointer_cast<YouTubeConnection>(item);
OBSDataAutoRelease obj = obs_data_create();
connection->SaveForExport(obj);
obs_data_array_push_back(array, obj);
}
obs_data_set_array(data, "youtubeConnections", array);
}
static void importConnections(obs_data_t *data, const QStringList &)
{
OBSDataArrayAutoRelease array =
obs_data_get_array(data, "youtubeConnections");
const size_t count = obs_data_array_count(array);
for (size_t i = 0; i < count; ++i) {
OBSDataAutoRelease obj = obs_data_array_item(array, i);
auto connection = YouTubeConnection::Create();
connection->Load(obj);
if (!GetWeakYouTubeConnectionByName(connection->Name())
.expired()) {
continue;
}
youtubeConnections.emplace_back(connection);
YouTubeConnectionSignalManager::Instance()->Add(
QString::fromStdString(connection->Name()));
}
}
static QList<QPair<QString, QString>> getExportItems()
{
QList<QPair<QString, QString>> items;
for (const auto &connection : youtubeConnections) {
const auto name = QString::fromStdString(connection->Name());
items.append({name, name});
}
return items;
}
static bool setup()
{
AddSaveStep(saveConnections);
AddLoadStep(loadConnections);
AddPluginCleanupStep([]() { youtubeConnections.clear(); });
AddMacroExportExtension(
{"AdvSceneSwitcher.macroTab.export.youtubeConnections",
"youtubeConnections", exportConnections, importConnections,
getExportItems});
return true;
}
static bool setupDone = setup();
static void saveConnections(obs_data_t *obj)
{
OBSDataArrayAutoRelease array = obs_data_array_create();
for (const auto &connection : youtubeConnections) {
OBSDataAutoRelease arrayObj = obs_data_create();
connection->Save(arrayObj);
obs_data_array_push_back(array, arrayObj);
}
obs_data_set_array(obj, "youtubeConnections", array);
}
static void loadConnections(obs_data_t *obj)
{
youtubeConnections.clear();
OBSDataArrayAutoRelease array =
obs_data_get_array(obj, "youtubeConnections");
const size_t count = obs_data_array_count(array);
for (size_t i = 0; i < count; i++) {
OBSDataAutoRelease arrayObj = obs_data_array_item(array, i);
auto connection = YouTubeConnection::Create();
connection->Load(arrayObj);
youtubeConnections.emplace_back(connection);
}
}
YouTubeConnection::YouTubeConnection(const YouTubeConnection &other)
: Item(other._name),
_customClientId(other._customClientId),
_customClientSecret(other._customClientSecret),
_refreshToken(other._refreshToken),
_channelId(other._channelId),
_warnIfInvalid(other._warnIfInvalid.load())
{
std::lock_guard<std::mutex> lock(other._mutex);
_accessToken = other._accessToken;
_accessTokenExpiry = other._accessTokenExpiry;
_refreshTokenRevoked = other._refreshTokenRevoked;
}
YouTubeConnection &YouTubeConnection::operator=(const YouTubeConnection &other)
{
if (this == &other) {
return *this;
}
std::scoped_lock lock(_mutex, other._mutex);
_name = other._name;
_customClientId = other._customClientId;
_customClientSecret = other._customClientSecret;
_refreshToken = other._refreshToken;
_channelId = other._channelId;
_warnIfInvalid = other._warnIfInvalid.load();
_accessToken = other._accessToken;
_accessTokenExpiry = other._accessTokenExpiry;
_refreshTokenRevoked = other._refreshTokenRevoked;
return *this;
}
void YouTubeConnection::Load(obs_data_t *obj)
{
std::lock_guard<std::mutex> lock(_mutex);
Item::Load(obj);
_customClientId = obs_data_get_string(obj, "customClientID");
_customClientSecret = obs_data_get_string(obj, "customClientSecret");
_refreshToken = obs_data_get_string(obj, "refreshToken");
_channelId = obs_data_get_string(obj, "channelID");
obs_data_set_default_bool(obj, "warnIfInvalid", true);
_warnIfInvalid = obs_data_get_bool(obj, "warnIfInvalid");
_accessToken.clear();
_refreshTokenRevoked = false;
}
void YouTubeConnection::Save(obs_data_t *obj) const
{
SaveForExport(obj);
std::lock_guard<std::mutex> lock(_mutex);
obs_data_set_string(obj, "customClientSecret",
_customClientSecret.c_str());
obs_data_set_string(obj, "refreshToken", _refreshToken.c_str());
obs_data_set_bool(obj, "warnIfInvalid", _warnIfInvalid);
}
void YouTubeConnection::SaveForExport(obs_data_t *obj) const
{
std::lock_guard<std::mutex> lock(_mutex);
Item::Save(obj);
obs_data_set_string(obj, "customClientID", _customClientId.c_str());
obs_data_set_string(obj, "channelID", _channelId.c_str());
}
std::optional<OAuthClientConfig> YouTubeConnection::GetClientConfig() const
{
if (_customClientId.empty()) {
return GetBuiltInClientConfig();
}
return OAuthClientConfig{_customClientId, _customClientSecret};
}
std::optional<std::string> YouTubeConnection::GetAccessToken(bool forceRefresh)
{
std::lock_guard<std::mutex> lock(_mutex);
const auto timeLeft =
_accessTokenExpiry - std::chrono::system_clock::now();
if (!forceRefresh && !_accessToken.empty() &&
timeLeft > std::chrono::seconds(60)) {
return _accessToken;
}
if (_refreshToken.empty() || _refreshTokenRevoked) {
return {};
}
const auto config = GetClientConfig();
if (!config) {
return {};
}
const auto now = std::chrono::steady_clock::now();
if (now - _lastRefreshFailure <
std::chrono::seconds(refreshRetryDelaySeconds)) {
return {};
}
const auto response = RefreshAccessToken(*config, _refreshToken);
if (response.error == "invalid_grant") {
blog(LOG_WARNING,
"YouTube connection \"%s\" was revoked or expired!",
_name.c_str());
_refreshTokenRevoked = true;
_accessToken.clear();
if (_warnIfInvalid) {
const auto name = QString::fromStdString(_name);
QueueUITask([name]() {
InvalidConnectionDialog::ShowWarning(name);
});
}
return {};
}
if (!response.error.empty()) {
_lastRefreshFailure = now;
return {};
}
vblog(LOG_INFO, "refreshed access token of YouTube connection \"%s\"",
_name.c_str());
_accessToken = response.accessToken;
_accessTokenExpiry = response.expiresAt;
if (!response.refreshToken.empty()) {
_refreshToken = response.refreshToken;
}
return _accessToken;
}
bool YouTubeConnection::SetAuthResult(const TokenResponse &response,
std::string &errorReason)
{
if (!response.error.empty()) {
errorReason = response.error;
return false;
}
if (response.refreshToken.empty()) {
errorReason = "noRefreshToken";
return false;
}
{
std::lock_guard<std::mutex> lock(_mutex);
_accessToken = response.accessToken;
_accessTokenExpiry = response.expiresAt;
_refreshToken = response.refreshToken;
_refreshTokenRevoked = false;
_lastRefreshFailure = {};
}
const auto result = SendYouTubeRequest(
*this, YouTubeRequestMethod::GET, "/channels",
{{"part", "snippet"}, {"mine", "true"}});
if (result.status != 200) {
errorReason = result.errorReason.empty() ? "requestFailed"
: result.errorReason;
return false;
}
OBSDataArrayAutoRelease items =
obs_data_get_array(result.data, "items");
OBSDataAutoRelease channel = obs_data_array_item(items, 0);
if (!channel) {
errorReason = "noChannel";
return false;
}
OBSDataAutoRelease snippet = obs_data_get_obj(channel, "snippet");
std::lock_guard<std::mutex> lock(_mutex);
_channelId = obs_data_get_string(channel, "id");
_name = obs_data_get_string(snippet, "title");
return true;
}
bool YouTubeConnection::IsValid() const
{
std::lock_guard<std::mutex> lock(_mutex);
return !_refreshToken.empty() && !_refreshTokenRevoked &&
GetClientConfig();
}
void YouTubeConnection::PauseRequests(std::chrono::seconds duration)
{
std::lock_guard<std::mutex> lock(_mutex);
_requestsPausedUntil = std::chrono::steady_clock::now() + duration;
}
bool YouTubeConnection::RequestsArePaused() const
{
std::lock_guard<std::mutex> lock(_mutex);
return std::chrono::steady_clock::now() < _requestsPausedUntil;
}
void YouTubeConnection::Revoke()
{
std::lock_guard<std::mutex> lock(_mutex);
if (!_refreshToken.empty()) {
RevokeToken(_refreshToken);
}
_refreshToken.clear();
_accessToken.clear();
}
std::string YouTubeConnection::GetChannelID() const
{
std::lock_guard<std::mutex> lock(_mutex);
return _channelId;
}
std::weak_ptr<YouTubeConnection>
GetWeakYouTubeConnectionByName(const std::string &name)
{
for (const auto &connection : youtubeConnections) {
if (connection->Name() == name) {
return std::dynamic_pointer_cast<YouTubeConnection>(
connection);
}
}
return {};
}
std::string
GetWeakYouTubeConnectionName(const std::weak_ptr<YouTubeConnection> &weak)
{
auto connection = weak.lock();
if (!connection) {
return obs_module_text(
"AdvSceneSwitcher.youtubeConnection.invalid");
}
return connection->Name();
}
std::deque<std::shared_ptr<Item>> &GetYouTubeConnections()
{
return youtubeConnections;
}
static std::string getBrowserFailText(const std::string &reason)
{
return QString(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect.fail.browser"))
.arg(QString::fromStdString(reason))
.toStdString();
}
AuthCodeGrabberThread::~AuthCodeGrabberThread()
{
_stopWaiting = true;
_cv.notify_all();
wait();
}
void AuthCodeGrabberThread::run()
{
_result = {};
_stopWaiting = false;
httplib::Server server;
const int port = server.bind_to_any_port("127.0.0.1");
if (port < 0) {
blog(LOG_WARNING,
"failed to bind YouTube auth server to localhost!");
_result.error = "serverError";
return;
}
const auto redirectUri = "http://127.0.0.1:" + std::to_string(port);
const auto codeVerifier = GenerateCodeVerifier();
const auto state = GenerateState();
std::string code;
server.Get("/", [&](const httplib::Request &req,
httplib::Response &res) {
std::lock_guard<std::mutex> lock(_mutex);
if (req.get_param_value("state") != state) {
res.set_content(
getBrowserFailText(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect.fail.stateMismatch")),
"text/plain");
return;
}
if (req.has_param("error")) {
_result.error = req.get_param_value("error");
res.set_content(getBrowserFailText(_result.error),
"text/plain");
} else {
code = req.get_param_value("code");
res.set_content(
obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect.success.browser"),
"text/plain");
}
_stopWaiting = true;
_cv.notify_all();
});
std::thread serverThread([&server]() { server.listen_after_bind(); });
const auto authUrl = BuildAuthUrl(
_config, redirectUri, GetCodeChallenge(codeVerifier), state);
QDesktopServices::openUrl(QUrl(QString::fromStdString(authUrl)));
{
std::unique_lock<std::mutex> lock(_mutex);
_cv.wait_for(lock, std::chrono::seconds(authTimeoutSeconds),
[this]() { return _stopWaiting.load(); });
}
server.stop();
serverThread.join();
if (!_result.error.empty()) {
return;
}
if (code.empty()) {
_result.error = "timeout";
return;
}
_result = ExchangeAuthCode(_config, code, codeVerifier, redirectUri);
}
YouTubeConnectionSettingsDialog::YouTubeConnectionSettingsDialog(
QWidget *parent, const YouTubeConnection &settings)
: ItemSettingsDialog(
settings, youtubeConnections,
"AdvSceneSwitcher.youtubeConnection.select",
"AdvSceneSwitcher.youtubeConnection.add",
"AdvSceneSwitcher.youtubeConnection.nameNotAvailable", false,
parent),
_clientId(new QLineEdit(
QString::fromStdString(settings._customClientId))),
_clientSecret(new QLineEdit(
QString::fromStdString(settings._customClientSecret))),
_connect(new QPushButton(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect"))),
_status(new QLabel()),
_warnIfInvalid(new QCheckBox(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.warnIfInvalid"))),
_currentConnection(settings)
{
_warnIfInvalid->setChecked(settings.WarnIfInvalid());
_name->setReadOnly(true);
_clientSecret->setEchoMode(QLineEdit::PasswordEchoOnEdit);
_status->setWordWrap(true);
QWidget::connect(_clientId, &QLineEdit::textEdited, this,
&YouTubeConnectionSettingsDialog::ClientConfigChanged);
QWidget::connect(_clientSecret, &QLineEdit::textEdited, this,
&YouTubeConnectionSettingsDialog::ClientConfigChanged);
QWidget::connect(_connect, &QPushButton::clicked, this,
&YouTubeConnectionSettingsDialog::Connect);
QWidget::connect(&_authGrabber, &QThread::finished, this,
&YouTubeConnectionSettingsDialog::AuthFinished);
QWidget::connect(&_countdownTimer, &QTimer::timeout, this,
&YouTubeConnectionSettingsDialog::UpdateWaitingStatus);
auto grid = new QGridLayout();
int row = 0;
grid->addWidget(new QLabel(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.name")),
row, 0);
auto nameLayout = new QHBoxLayout();
nameLayout->addWidget(_name);
nameLayout->addWidget(_nameHint);
grid->addLayout(nameLayout, row, 1);
++row;
auto clientIdLabelLayout = new QHBoxLayout();
clientIdLabelLayout->addWidget(new QLabel(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.clientId")));
clientIdLabelLayout->addWidget(new HelpIcon(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.clientConfig.help")));
clientIdLabelLayout->addStretch();
grid->addLayout(clientIdLabelLayout, row, 0);
grid->addWidget(_clientId, row, 1);
++row;
grid->addWidget(
new QLabel(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.clientSecret")),
row, 0);
grid->addWidget(_clientSecret, row, 1);
++row;
grid->addWidget(_connect, row, 0);
grid->addWidget(_status, row, 1);
auto layout = new QVBoxLayout();
layout->addLayout(grid);
layout->addWidget(_warnIfInvalid);
layout->addWidget(_buttonbox);
setLayout(layout);
_status->setText(obs_module_text(
settings.IsValid()
? "AdvSceneSwitcher.youtubeConnection.connect.success"
: "AdvSceneSwitcher.youtubeConnection.connect.notConnected"));
if (_name->text().isEmpty()) {
HighlightWidget(_connect, Qt::green, QColor(0, 0, 0, 0), true);
}
}
void YouTubeConnectionSettingsDialog::ClientConfigChanged()
{
_currentConnection._customClientId =
_clientId->text().trimmed().toStdString();
_currentConnection._customClientSecret =
_clientSecret->text().trimmed().toStdString();
_currentConnection._refreshToken.clear();
_currentConnection._accessToken.clear();
_name->setText("");
QMetaObject::invokeMethod(this, "NameChanged",
Q_ARG(const QString &, ""));
_status->setText(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect.notConnected"));
}
void YouTubeConnectionSettingsDialog::Connect()
{
const auto config = _currentConnection.GetClientConfig();
if (!config || config->clientId.empty() ||
config->clientSecret.empty()) {
SetErrorStatus("missingClientConfig");
return;
}
// Don't allow parallel auth requests
_connect->setDisabled(true);
_authGrabber.SetClientConfig(*config);
_authGrabber.start();
_authDeadline = std::chrono::steady_clock::now() +
std::chrono::seconds(authTimeoutSeconds);
UpdateWaitingStatus();
_countdownTimer.start(1000);
}
void YouTubeConnectionSettingsDialog::UpdateWaitingStatus()
{
const auto remaining = std::chrono::ceil<std::chrono::seconds>(
_authDeadline - std::chrono::steady_clock::now());
_status->setText(
QString(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect.waiting"))
.arg(std::max<long long>(remaining.count(), 0)));
}
void YouTubeConnectionSettingsDialog::AuthFinished()
{
_countdownTimer.stop();
_connect->setEnabled(true);
std::string errorReason;
if (!_currentConnection.SetAuthResult(_authGrabber.Result(),
errorReason)) {
_name->setText("");
QMetaObject::invokeMethod(this, "NameChanged",
Q_ARG(const QString &, ""));
SetErrorStatus(errorReason);
return;
}
const auto name = QString::fromStdString(_currentConnection.Name());
_name->setText(name);
QMetaObject::invokeMethod(this, "NameChanged",
Q_ARG(const QString &, name));
_status->setText(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.connect.success"));
}
void YouTubeConnectionSettingsDialog::SetErrorStatus(
const std::string &errorReason)
{
static const std::unordered_map<std::string, const char *> errorTexts{
{"missingClientConfig",
"AdvSceneSwitcher.youtubeConnection.error.missingClientConfig"},
{"access_denied",
"AdvSceneSwitcher.youtubeConnection.error.accessDenied"},
{"invalid_client",
"AdvSceneSwitcher.youtubeConnection.error.invalidClient"},
{"invalid_grant",
"AdvSceneSwitcher.youtubeConnection.error.invalidGrant"},
{"accessNotConfigured",
"AdvSceneSwitcher.youtubeConnection.error.apiNotEnabled"},
{"noChannel",
"AdvSceneSwitcher.youtubeConnection.error.noChannel"},
{"timeout", "AdvSceneSwitcher.youtubeConnection.error.timeout"},
{"network_error",
"AdvSceneSwitcher.youtubeConnection.error.network"},
{"serverError",
"AdvSceneSwitcher.youtubeConnection.error.server"},
};
const auto it = errorTexts.find(errorReason);
if (it != errorTexts.end()) {
_status->setText(obs_module_text(it->second));
return;
}
_status->setText(
QString(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.error.unknown"))
.arg(QString::fromStdString(errorReason)));
}
bool YouTubeConnectionSettingsDialog::AskForSettings(
QWidget *parent, YouTubeConnection &settings)
{
YouTubeConnectionSettingsDialog dialog(parent, settings);
dialog.setWindowTitle(obs_module_text("AdvSceneSwitcher.windowTitle"));
if (dialog.exec() != DialogCode::Accepted) {
return false;
}
settings = dialog._currentConnection;
settings.SetWarnIfInvalid(dialog._warnIfInvalid->isChecked());
return true;
}
static bool askForSettingsWrapper(QWidget *parent, Item &settings)
{
auto &connection = dynamic_cast<YouTubeConnection &>(settings);
return YouTubeConnectionSettingsDialog::AskForSettings(parent,
connection);
}
YouTubeConnectionSelection::YouTubeConnectionSelection(QWidget *parent)
: ItemSelection(youtubeConnections, YouTubeConnection::Create,
askForSettingsWrapper,
"AdvSceneSwitcher.youtubeConnection.select",
"AdvSceneSwitcher.youtubeConnection.add",
"AdvSceneSwitcher.youtubeConnection.nameNotAvailable",
"AdvSceneSwitcher.youtubeConnection.configure", parent)
{
ShowRenameContextMenu(false);
QWidget::connect(YouTubeConnectionSignalManager::Instance(),
SIGNAL(Add(const QString &)), this,
SLOT(AddItem(const QString &)));
QWidget::connect(YouTubeConnectionSignalManager::Instance(),
SIGNAL(Remove(const QString &)), this,
SLOT(RemoveItem(const QString &)));
QWidget::connect(this, SIGNAL(ItemAdded(const QString &)),
YouTubeConnectionSignalManager::Instance(),
SIGNAL(Add(const QString &)));
QWidget::connect(this, SIGNAL(ItemRemoved(const QString &)),
YouTubeConnectionSignalManager::Instance(),
SIGNAL(Remove(const QString &)));
}
void YouTubeConnectionSelection::SetConnection(
const std::weak_ptr<YouTubeConnection> &weak)
{
auto connection = weak.lock();
SetItem(connection ? connection->Name() : "");
}
YouTubeConnectionSignalManager *YouTubeConnectionSignalManager::Instance()
{
static YouTubeConnectionSignalManager manager;
return &manager;
}
} // namespace advss

View File

@@ -0,0 +1,139 @@
#pragma once
#include "youtube-oauth.hpp"
#include <item-selection-helpers.hpp>
#include <atomic>
#include <condition_variable>
#include <mutex>
#include <QCheckBox>
#include <QThread>
#include <QTimer>
namespace advss {
class YouTubeConnectionSettingsDialog;
class YouTubeConnection : public Item {
public:
YouTubeConnection() = default;
YouTubeConnection(const YouTubeConnection &);
YouTubeConnection &operator=(const YouTubeConnection &);
static std::shared_ptr<Item> Create()
{
return std::make_shared<YouTubeConnection>();
}
void Load(obs_data_t *obj) override;
void Save(obs_data_t *obj) const override;
void SaveForExport(obs_data_t *obj) const;
std::optional<OAuthClientConfig> GetClientConfig() const;
std::optional<std::string> GetAccessToken(bool forceRefresh = false);
bool SetAuthResult(const TokenResponse &, std::string &errorReason);
bool IsValid() const;
void Revoke();
std::string GetChannelID() const;
bool WarnIfInvalid() const { return _warnIfInvalid; }
void SetWarnIfInvalid(bool value) { _warnIfInvalid = value; }
void PauseRequests(std::chrono::seconds duration);
bool RequestsArePaused() const;
private:
std::string _customClientId;
std::string _customClientSecret;
std::string _refreshToken;
std::string _channelId;
std::atomic_bool _warnIfInvalid = {true};
mutable std::mutex _mutex;
std::string _accessToken;
std::chrono::system_clock::time_point _accessTokenExpiry;
bool _refreshTokenRevoked = false;
std::chrono::steady_clock::time_point _lastRefreshFailure;
std::chrono::steady_clock::time_point _requestsPausedUntil;
friend YouTubeConnectionSettingsDialog;
};
class AuthCodeGrabberThread : public QThread {
Q_OBJECT
public:
~AuthCodeGrabberThread();
void SetClientConfig(const OAuthClientConfig &config)
{
_config = config;
}
const TokenResponse &Result() const { return _result; }
protected:
void run() override;
private:
OAuthClientConfig _config;
TokenResponse _result;
std::mutex _mutex;
std::condition_variable _cv;
std::atomic_bool _stopWaiting = {false};
};
class YouTubeConnectionSettingsDialog : public ItemSettingsDialog {
Q_OBJECT
public:
YouTubeConnectionSettingsDialog(QWidget *parent,
const YouTubeConnection &);
static bool AskForSettings(QWidget *parent,
YouTubeConnection &settings);
private slots:
void ClientConfigChanged();
void Connect();
void AuthFinished();
void UpdateWaitingStatus();
private:
void SetErrorStatus(const std::string &errorReason);
QLineEdit *_clientId;
QLineEdit *_clientSecret;
QPushButton *_connect;
QLabel *_status;
QCheckBox *_warnIfInvalid;
AuthCodeGrabberThread _authGrabber;
QTimer _countdownTimer;
std::chrono::steady_clock::time_point _authDeadline;
YouTubeConnection _currentConnection;
};
class YouTubeConnectionSelection : public ItemSelection {
Q_OBJECT
public:
YouTubeConnectionSelection(QWidget *parent = nullptr);
void SetConnection(const std::weak_ptr<YouTubeConnection> &);
};
class YouTubeConnectionSignalManager : public QObject {
Q_OBJECT
public:
static YouTubeConnectionSignalManager *Instance();
private:
signals:
// Rename signal not required as name is based on the channel name
// and item name cannot be manually changed
void Add(const QString &);
void Remove(const QString &);
};
std::weak_ptr<YouTubeConnection>
GetWeakYouTubeConnectionByName(const std::string &name);
std::string
GetWeakYouTubeConnectionName(const std::weak_ptr<YouTubeConnection> &);
std::deque<std::shared_ptr<Item>> &GetYouTubeConnections();
} // namespace advss

View File

@@ -0,0 +1,237 @@
#include "youtube-helpers.hpp"
#include "youtube-connection.hpp"
#include <log-helper.hpp>
#include <plugin-state-helpers.hpp>
#include <mutex>
#include <unordered_map>
namespace advss {
static const char *tokenHost = "https://oauth2.googleapis.com";
static const char *apiHost = "https://www.googleapis.com";
static const char *apiBasePath = "/youtube/v3";
// Conditions are checked frequently, so cache responses to stay within the
// daily API quota
static const int cacheTimeoutSeconds = 30;
static const int quotaPauseMinutes = 15;
static bool isQuotaError(const std::string &errorReason)
{
return errorReason == "quotaExceeded" ||
errorReason == "rateLimitExceeded" ||
errorReason == "userRateLimitExceeded";
}
static TokenResponse sendTokenRequest(const httplib::Params &params)
{
httplib::Client cli(tokenHost);
const auto response = cli.Post("/token", params);
if (!response) {
blog(LOG_WARNING, "YouTube token request failed: %s",
httplib::to_string(response.error()).c_str());
TokenResponse result;
result.error = "network_error";
return result;
}
auto result = ParseTokenResponse(response->body);
if (!result.error.empty()) {
blog(LOG_WARNING, "YouTube token request failed: %s (%s)",
result.error.c_str(), result.errorDescription.c_str());
}
return result;
}
TokenResponse ExchangeAuthCode(const OAuthClientConfig &config,
const std::string &code,
const std::string &codeVerifier,
const std::string &redirectUri)
{
return sendTokenRequest({
{"grant_type", "authorization_code"},
{"code", code},
{"code_verifier", codeVerifier},
{"redirect_uri", redirectUri},
{"client_id", config.clientId},
{"client_secret", config.clientSecret},
});
}
TokenResponse RefreshAccessToken(const OAuthClientConfig &config,
const std::string &refreshToken)
{
return sendTokenRequest({
{"grant_type", "refresh_token"},
{"refresh_token", refreshToken},
{"client_id", config.clientId},
{"client_secret", config.clientSecret},
});
}
void RevokeToken(const std::string &token)
{
httplib::Client cli(tokenHost);
const auto response =
cli.Post("/revoke", httplib::Params{{"token", token}});
if (!response) {
blog(LOG_WARNING, "failed to revoke YouTube token: %s",
httplib::to_string(response.error()).c_str());
return;
}
if (response->status != 200) {
blog(LOG_WARNING, "failed to revoke YouTube token: %d",
response->status);
}
}
static std::string getErrorReason(obs_data_t *data)
{
OBSDataAutoRelease error = obs_data_get_obj(data, "error");
OBSDataArrayAutoRelease errors = obs_data_get_array(error, "errors");
OBSDataAutoRelease firstError = obs_data_array_item(errors, 0);
return obs_data_get_string(firstError, "reason");
}
static httplib::Result sendRequest(YouTubeRequestMethod method,
const std::string &path,
const httplib::Params &params,
const std::string &body,
const std::string &accessToken)
{
httplib::Client cli(apiHost);
const httplib::Headers headers{
{"Authorization", "Bearer " + accessToken}};
const auto fullPath =
httplib::append_query_params(apiBasePath + path, params);
switch (method) {
case YouTubeRequestMethod::GET:
vblog(LOG_INFO, "YouTube GET request to %s", fullPath.c_str());
return cli.Get(fullPath, headers);
case YouTubeRequestMethod::POST:
vblog(LOG_INFO, "YouTube POST request to %s", fullPath.c_str());
return cli.Post(fullPath, headers, body, "application/json");
}
return httplib::Result();
}
static YouTubeRequestResult sendYouTubeRequest(YouTubeConnection &connection,
YouTubeRequestMethod method,
const std::string &path,
const httplib::Params &params,
const std::string &body)
{
if (connection.RequestsArePaused()) {
vblog(LOG_INFO, "skipping YouTube request to %s due to quota",
path.c_str());
return {};
}
auto accessToken = connection.GetAccessToken();
if (!accessToken) {
return {};
}
auto response = sendRequest(method, path, params, body, *accessToken);
if (response && response->status == 401) {
accessToken = connection.GetAccessToken(true);
if (!accessToken) {
return {};
}
response =
sendRequest(method, path, params, body, *accessToken);
}
if (!response) {
blog(LOG_WARNING, "YouTube request to %s failed: %s",
path.c_str(),
httplib::to_string(response.error()).c_str());
return {};
}
YouTubeRequestResult result;
result.status = response->status;
if (response->body.empty()) {
return result;
}
OBSDataAutoRelease data =
obs_data_create_from_json(response->body.c_str());
result.data = data;
if (response->status < 200 || response->status >= 300) {
result.errorReason = getErrorReason(data);
blog(LOG_WARNING, "YouTube request to %s failed: %d %s",
path.c_str(), response->status,
result.errorReason.c_str());
vblog(LOG_INFO, "YouTube API error response: %s",
response->body.c_str());
}
if (isQuotaError(result.errorReason)) {
blog(LOG_WARNING,
"pausing requests of YouTube connection \"%s\" for %d minutes",
connection.Name().c_str(), quotaPauseMinutes);
connection.PauseRequests(
std::chrono::minutes(quotaPauseMinutes));
}
return result;
}
struct CacheEntry {
YouTubeRequestResult result;
std::chrono::steady_clock::time_point time;
};
static std::string getCacheKey(const YouTubeConnection &connection,
const std::string &path,
const httplib::Params &params)
{
return connection.GetChannelID() +
httplib::append_query_params(path, params);
}
YouTubeRequestResult SendYouTubeRequest(YouTubeConnection &connection,
YouTubeRequestMethod method,
const std::string &path,
const httplib::Params &params,
const std::string &body, bool useCache)
{
if (!useCache || method != YouTubeRequestMethod::GET) {
return sendYouTubeRequest(connection, method, path, params,
body);
}
static std::mutex mutex;
static std::unordered_map<std::string, CacheEntry> cache;
[[maybe_unused]] static bool cleanupRegistered = []() {
AddPluginCleanupStep([]() {
std::lock_guard<std::mutex> lock(mutex);
cache.clear();
});
return true;
}();
const auto key = getCacheKey(connection, path, params);
const auto now = std::chrono::steady_clock::now();
{
std::lock_guard<std::mutex> lock(mutex);
const auto it = cache.find(key);
if (it != cache.end() &&
now - it->second.time <
std::chrono::seconds(cacheTimeoutSeconds)) {
return it->second.result;
}
}
// Failed requests are cached as well, as they also cost API quota
auto result =
sendYouTubeRequest(connection, method, path, params, body);
std::lock_guard<std::mutex> lock(mutex);
cache[key] = {result, now};
return result;
}
} // namespace advss

View File

@@ -0,0 +1,35 @@
#pragma once
#include "youtube-oauth.hpp"
#include <httplib.h>
#include <obs.hpp>
namespace advss {
class YouTubeConnection;
struct YouTubeRequestResult {
int status = 0;
OBSData data = nullptr;
std::string errorReason;
};
enum class YouTubeRequestMethod {
GET,
POST,
};
TokenResponse ExchangeAuthCode(const OAuthClientConfig &config,
const std::string &code,
const std::string &codeVerifier,
const std::string &redirectUri);
TokenResponse RefreshAccessToken(const OAuthClientConfig &config,
const std::string &refreshToken);
void RevokeToken(const std::string &token);
YouTubeRequestResult
SendYouTubeRequest(YouTubeConnection &connection, YouTubeRequestMethod method,
const std::string &path, const httplib::Params &params = {},
const std::string &body = "", bool useCache = false);
} // namespace advss

View File

@@ -0,0 +1,115 @@
#include "youtube-oauth.hpp"
#include <nlohmann/json.hpp>
#include <QByteArray>
#include <QCryptographicHash>
#include <QUrl>
#include <random>
#include <utility>
namespace advss {
static const char *authEndpoint =
"https://accounts.google.com/o/oauth2/v2/auth";
static const char *youtubeScope = "https://www.googleapis.com/auth/youtube";
std::optional<OAuthClientConfig> GetBuiltInClientConfig()
{
return {};
}
static std::string generateRandomString(size_t length)
{
static const std::string chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
static std::random_device rd;
static std::mt19937 gen(rd());
std::uniform_int_distribution<size_t> dis(0, chars.size() - 1);
std::string result;
result.reserve(length);
for (size_t i = 0; i < length; ++i) {
result += chars[dis(gen)];
}
return result;
}
std::string GenerateCodeVerifier()
{
// RFC 7636 requires 43 to 128 characters
return generateRandomString(64);
}
std::string GetCodeChallenge(const std::string &verifier)
{
const auto hash =
QCryptographicHash::hash(QByteArray::fromStdString(verifier),
QCryptographicHash::Sha256);
return hash
.toBase64(QByteArray::Base64UrlEncoding |
QByteArray::OmitTrailingEquals)
.toStdString();
}
std::string GenerateState()
{
return generateRandomString(32);
}
std::string BuildAuthUrl(const OAuthClientConfig &config,
const std::string &redirectUri,
const std::string &codeChallenge,
const std::string &state)
{
const std::pair<const char *, std::string> params[] = {
{"client_id", config.clientId},
{"redirect_uri", redirectUri},
{"response_type", "code"},
{"scope", youtubeScope},
{"access_type", "offline"},
// Without consent Google does not return a new refresh token
// when the user had already granted access before
{"prompt", "consent"},
{"code_challenge", codeChallenge},
{"code_challenge_method", "S256"},
{"state", state},
};
// QUrlQuery is not used as it does not encode '+'
std::string url = authEndpoint;
char separator = '?';
for (const auto &[key, value] : params) {
url += separator;
url += key;
url += '=';
url += QUrl::toPercentEncoding(QString::fromStdString(value))
.toStdString();
separator = '&';
}
return url;
}
TokenResponse ParseTokenResponse(const std::string &body)
{
TokenResponse result;
try {
const auto json = nlohmann::json::parse(body);
result.accessToken = json.value("access_token", "");
result.refreshToken = json.value("refresh_token", "");
result.error = json.value("error", "");
result.errorDescription = json.value("error_description", "");
const auto expiresIn = json.value("expires_in", 0);
result.expiresAt = std::chrono::system_clock::now() +
std::chrono::seconds(expiresIn);
} catch (const nlohmann::json::exception &) {
result.error = "invalid_response";
}
if (result.error.empty() && result.accessToken.empty()) {
result.error = "invalid_response";
}
return result;
}
} // namespace advss

View File

@@ -0,0 +1,32 @@
#pragma once
#include <chrono>
#include <optional>
#include <string>
namespace advss {
struct OAuthClientConfig {
std::string clientId;
std::string clientSecret;
};
struct TokenResponse {
std::string accessToken;
std::string refreshToken;
std::chrono::system_clock::time_point expiresAt;
std::string error;
std::string errorDescription;
};
std::optional<OAuthClientConfig> GetBuiltInClientConfig();
std::string GenerateCodeVerifier();
std::string GetCodeChallenge(const std::string &verifier);
std::string GenerateState();
std::string BuildAuthUrl(const OAuthClientConfig &config,
const std::string &redirectUri,
const std::string &codeChallenge,
const std::string &state);
TokenResponse ParseTokenResponse(const std::string &body);
} // namespace advss

View File

@@ -0,0 +1,284 @@
#include "youtube-tab.hpp"
#include "youtube-connection.hpp"
#include <obs-module-helper.hpp>
#include <sync-helpers.hpp>
#include <tab-helpers.hpp>
#include <ui-helpers.hpp>
#include <QDialogButtonBox>
#include <QTabWidget>
#include <QVBoxLayout>
namespace advss {
static bool setup();
static void setupTab(QTabWidget *);
static bool setupDone = setup();
static YouTubeConnectionsTable *tabWidget = nullptr;
static bool setup()
{
AddSetupTabCallback("youtubeConnectionTab",
YouTubeConnectionsTable::Create, setupTab);
return true;
}
static void setTabVisible(QTabWidget *tab, bool visible)
{
SetTabVisibleByName(
tab, visible,
obs_module_text("AdvSceneSwitcher.youtubeConnectionTab.title"));
}
static bool youtubeTabIsSelected(QTabWidget *tab)
{
return tab->tabText(tab->currentIndex()) ==
obs_module_text("AdvSceneSwitcher.youtubeConnectionTab.title");
}
YouTubeConnectionsTable *YouTubeConnectionsTable::Create()
{
tabWidget = new YouTubeConnectionsTable();
return tabWidget;
}
void YouTubeConnectionsTable::Add()
{
auto connection = std::make_shared<YouTubeConnection>();
const bool accepted = YouTubeConnectionSettingsDialog::AskForSettings(
GetSettingsWindow(), *connection);
if (!accepted) {
return;
}
{
auto lock = LockContext();
GetYouTubeConnections().emplace_back(connection);
}
YouTubeConnectionSignalManager::Instance()->Add(
QString::fromStdString(connection->Name()));
}
void YouTubeConnectionsTable::Remove()
{
const auto selectedRows = Table()->selectionModel()->selectedRows();
if (selectedRows.empty()) {
return;
}
QStringList names;
for (const auto &row : selectedRows) {
auto cell = Table()->item(row.row(), 0);
if (!cell) {
continue;
}
names << cell->text();
}
if (names.size() == 1) {
const QString deleteWarning = obs_module_text(
"AdvSceneSwitcher.youtubeConnectionTab.removeSingleConnectionPopup.text");
if (!DisplayMessage(deleteWarning.arg(names.at(0)), true)) {
return;
}
} else {
const QString deleteWarning = obs_module_text(
"AdvSceneSwitcher.youtubeConnectionTab.removeMultipleConnectionsPopup.text");
if (!DisplayMessage(deleteWarning.arg(names.size()), true)) {
return;
}
}
for (const auto &name : names) {
auto connection =
GetWeakYouTubeConnectionByName(name.toStdString())
.lock();
if (connection) {
connection->Revoke();
}
}
{
auto lock = LockContext();
RemoveItemsByName(GetYouTubeConnections(), names);
}
for (const auto &name : names) {
YouTubeConnectionSignalManager::Instance()->Remove(name);
}
}
static QStringList getCellLabels(const YouTubeConnection &connection,
bool addName = true)
{
QStringList result;
if (addName) {
result << QString::fromStdString(connection.Name());
}
result << obs_module_text(
connection.IsValid()
? "AdvSceneSwitcher.youtubeConnectionTab.yes"
: "AdvSceneSwitcher.youtubeConnectionTab.no");
return result;
}
static void updateConnectionStatus(QTableWidget *table)
{
for (int row = 0; row < table->rowCount(); row++) {
auto item = table->item(row, 0);
if (!item) {
continue;
}
auto connection = GetWeakYouTubeConnectionByName(
item->text().toStdString())
.lock();
if (!connection) {
continue;
}
UpdateItemTableRow(table, row,
getCellLabels(*connection, false));
}
}
static void openSettingsDialog()
{
const auto selectedRows =
tabWidget->Table()->selectionModel()->selectedRows();
if (selectedRows.empty()) {
return;
}
auto cell = tabWidget->Table()->item(selectedRows.last().row(), 0);
if (!cell) {
return;
}
auto connection =
GetWeakYouTubeConnectionByName(cell->text().toStdString())
.lock();
if (!connection) {
return;
}
YouTubeConnectionSettingsDialog::AskForSettings(GetSettingsWindow(),
*connection);
updateConnectionStatus(tabWidget->Table());
}
static const QStringList headers =
QStringList()
<< obs_module_text("AdvSceneSwitcher.youtubeConnectionTab.name.header")
<< obs_module_text(
"AdvSceneSwitcher.youtubeConnectionTab.isValid.header");
YouTubeConnectionsTable::YouTubeConnectionsTable(QTabWidget *parent)
: ResourceTable(
parent,
obs_module_text("AdvSceneSwitcher.youtubeConnectionTab.help"),
obs_module_text(
"AdvSceneSwitcher.youtubeConnectionTab.addButton.tooltip"),
obs_module_text(
"AdvSceneSwitcher.youtubeConnectionTab.removeButton.tooltip"),
headers, openSettingsDialog)
{
for (const auto &item : GetYouTubeConnections()) {
auto connection =
std::static_pointer_cast<YouTubeConnection>(item);
AddItemTableRow(Table(), getCellLabels(*connection));
}
SetHelpVisible(GetYouTubeConnections().empty());
}
static void setupTab(QTabWidget *tab)
{
if (GetYouTubeConnections().empty()) {
setTabVisible(tab, false);
}
QWidget::connect(YouTubeConnectionSignalManager::Instance(),
&YouTubeConnectionSignalManager::Add, tab,
[tab](const QString &name) {
auto connection =
GetWeakYouTubeConnectionByName(
name.toStdString())
.lock();
if (!connection) {
return;
}
AddItemTableRow(tabWidget->Table(),
getCellLabels(*connection));
tabWidget->SetHelpVisible(false);
tabWidget->HighlightAddButton(false);
setTabVisible(tab, true);
});
QWidget::connect(YouTubeConnectionSignalManager::Instance(),
&YouTubeConnectionSignalManager::Remove, tab,
[](const QString &name) {
RemoveItemTableRow(tabWidget->Table(), name);
if (tabWidget->Table()->rowCount() == 0) {
tabWidget->SetHelpVisible(true);
tabWidget->HighlightAddButton(true);
}
});
QWidget::connect(tab, &QTabWidget::currentChanged, [tab]() {
if (youtubeTabIsSelected(tab)) {
updateConnectionStatus(tabWidget->Table());
}
});
}
void InvalidConnectionDialog::ShowWarning(const QString &name)
{
auto connection =
GetWeakYouTubeConnectionByName(name.toStdString()).lock();
if (!connection) {
return;
}
auto dialog = new InvalidConnectionDialog(name);
dialog->setWindowTitle(obs_module_text("AdvSceneSwitcher.windowTitle"));
const bool ignore = dialog->exec() != DialogCode::Accepted;
connection->SetWarnIfInvalid(!dialog->_doNotShowAgain->isChecked());
dialog->deleteLater();
if (ignore) {
return;
}
YouTubeConnectionSettingsDialog::AskForSettings(GetSettingsWindow(),
*connection);
}
InvalidConnectionDialog::InvalidConnectionDialog(const QString &name)
: QDialog(GetSettingsWindow()),
_doNotShowAgain(new QCheckBox(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.warnIfInvalid.doNotShowAgain")))
{
auto buttons = new QDialogButtonBox(QDialogButtonBox::Ignore |
QDialogButtonBox::Open);
connect(buttons->button(QDialogButtonBox::Ignore),
&QPushButton::clicked, this, &QDialog::reject);
connect(buttons->button(QDialogButtonBox::Open), &QPushButton::clicked,
this, &QDialog::accept);
buttons->setCenterButtons(true);
const QString message =
QString(obs_module_text(
"AdvSceneSwitcher.youtubeConnection.warnIfInvalid.message"))
.arg(name);
auto layout = new QVBoxLayout();
layout->addWidget(new QLabel(message));
layout->addWidget(_doNotShowAgain);
layout->addWidget(buttons);
setLayout(layout);
}
} // namespace advss

View File

@@ -0,0 +1,33 @@
#pragma once
#include "resource-table.hpp"
#include <QCheckBox>
#include <QDialog>
namespace advss {
class YouTubeConnectionsTable final : public ResourceTable {
Q_OBJECT
public:
static YouTubeConnectionsTable *Create();
private slots:
void Add();
void Remove();
private:
YouTubeConnectionsTable(QTabWidget *parent = nullptr);
};
class InvalidConnectionDialog : public QDialog {
Q_OBJECT
public:
static void ShowWarning(const QString &name);
private:
InvalidConnectionDialog(const QString &name);
QCheckBox *_doNotShowAgain;
};
} // namespace advss

View File

@@ -233,6 +233,16 @@ target_sources(
${PROJECT_NAME} PRIVATE test-twitch-timestamp.cpp
"${TWITCH_PLUGIN_DIR}/twitch-timestamp.cpp")
# --- youtube oauth --- #
set(YOUTUBE_PLUGIN_DIR
"${ADVSS_SOURCE_DIR}/plugins/youtube"
CACHE INTERNAL "")
target_include_directories(${PROJECT_NAME} PRIVATE "${YOUTUBE_PLUGIN_DIR}")
target_sources(
${PROJECT_NAME} PRIVATE test-youtube-oauth.cpp
"${YOUTUBE_PLUGIN_DIR}/youtube-oauth.cpp")
# --- Testing --- #
enable_testing()

View File

@@ -0,0 +1,88 @@
#include "catch.hpp"
#include <youtube-oauth.hpp>
#include <QUrl>
#include <QUrlQuery>
TEST_CASE("PKCE code challenge", "[youtube-oauth]")
{
// Test vector from RFC 7636 Appendix B
REQUIRE(advss::GetCodeChallenge(
"dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk") ==
"E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM");
}
TEST_CASE("PKCE code verifier", "[youtube-oauth]")
{
const auto verifier = advss::GenerateCodeVerifier();
REQUIRE(verifier.size() >= 43);
REQUIRE(verifier.size() <= 128);
REQUIRE(verifier.find_first_not_of(
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~") ==
std::string::npos);
REQUIRE(verifier != advss::GenerateCodeVerifier());
}
TEST_CASE("Auth URL", "[youtube-oauth]")
{
advss::OAuthClientConfig config{"id+with spaces", "secret"};
const auto url = QUrl(QString::fromStdString(advss::BuildAuthUrl(
config, "http://127.0.0.1:1234", "challenge", "state")));
REQUIRE(url.host() == "accounts.google.com");
REQUIRE(url.path() == "/o/oauth2/v2/auth");
const QUrlQuery query(url);
const auto value = [&query](const char *key) {
return query.queryItemValue(key, QUrl::FullyDecoded)
.toStdString();
};
REQUIRE(value("client_id") == "id+with spaces");
REQUIRE(value("redirect_uri") == "http://127.0.0.1:1234");
REQUIRE(value("response_type") == "code");
REQUIRE(value("scope") == "https://www.googleapis.com/auth/youtube");
REQUIRE(value("access_type") == "offline");
REQUIRE(value("prompt") == "consent");
REQUIRE(value("code_challenge") == "challenge");
REQUIRE(value("code_challenge_method") == "S256");
REQUIRE(value("state") == "state");
REQUIRE_FALSE(query.hasQueryItem("client_secret"));
}
TEST_CASE("Token response parsing", "[youtube-oauth]")
{
SECTION("Success")
{
const auto before = std::chrono::system_clock::now();
const auto result = advss::ParseTokenResponse(
R"({"access_token":"a","refresh_token":"r","expires_in":3599,"token_type":"Bearer"})");
REQUIRE(result.error.empty());
REQUIRE(result.accessToken == "a");
REQUIRE(result.refreshToken == "r");
REQUIRE(result.expiresAt >=
before + std::chrono::seconds(3599));
}
SECTION("Refresh without new refresh token")
{
const auto result = advss::ParseTokenResponse(
R"({"access_token":"a","expires_in":3599})");
REQUIRE(result.error.empty());
REQUIRE(result.refreshToken.empty());
}
SECTION("Error")
{
const auto result = advss::ParseTokenResponse(
R"({"error":"invalid_grant","error_description":"Token has been expired or revoked."})");
REQUIRE(result.error == "invalid_grant");
REQUIRE(result.errorDescription ==
"Token has been expired or revoked.");
}
SECTION("Invalid")
{
REQUIRE(advss::ParseTokenResponse("not json").error ==
"invalid_response");
REQUIRE(advss::ParseTokenResponse("{}").error ==
"invalid_response");
}
}