diff --git a/data/locale/en-US.ini b/data/locale/en-US.ini index 01c0b863..2e1f7ce3 100644 --- a/data/locale/en-US.ini +++ b/data/locale/en-US.ini @@ -1667,6 +1667,18 @@ AdvSceneSwitcher.action.youtube.create.autoStart="Go live automatically when vid AdvSceneSwitcher.action.youtube.create.autoStop="End broadcast automatically when video stops" AdvSceneSwitcher.action.youtube.create.madeForKids="Made for kids" AdvSceneSwitcher.action.youtube.create.bindToObsStreamKey="Bind to the OBS stream key" +AdvSceneSwitcher.action.youtube.create.layout.category="Category:{{category}}" +AdvSceneSwitcher.action.youtube.create.category.default="Default" +AdvSceneSwitcher.action.youtube.create.layout.thumbnail="Thumbnail:{{thumbnail}}" +AdvSceneSwitcher.action.youtube.create.thumbnail.tooltip="Optional PNG, JPEG or GIF image of up to 2 MB.\nCustom thumbnails require a verified YouTube channel." +AdvSceneSwitcher.action.youtube.create.layout.latency="Latency:{{latency}}" +AdvSceneSwitcher.action.youtube.create.latency.normal="Normal" +AdvSceneSwitcher.action.youtube.create.latency.low="Low" +AdvSceneSwitcher.action.youtube.create.latency.ultraLow="Ultra low" +AdvSceneSwitcher.action.youtube.create.layout.schedule="{{scheduleForLater}}{{scheduledStartIn}}" +AdvSceneSwitcher.action.youtube.create.scheduleForLater="Schedule to start in" +AdvSceneSwitcher.action.youtube.create.dvr="Enable DVR" +AdvSceneSwitcher.action.youtube.create.projection360="360 video" AdvSceneSwitcher.action.youtube.layout="On{{connection}}{{actions}}{{help}}" AdvSceneSwitcher.action.youtube.start.help="The broadcast must be bound to a stream which is already receiving video, so start streaming first.\nOtherwise YouTube will reject the request and the reason will be written to the OBS log." AdvSceneSwitcher.action.youtube.create.help="OBS does not know about broadcasts created by this action.\nIf a YouTube account is connected in the OBS stream settings, OBS will refuse to start streaming until a broadcast was set up using its \"Manage Broadcast\" dialog.\n\nTo stream to a broadcast created here, use a stream key in the OBS stream settings instead of connecting an account and enable \"Bind to the OBS stream key\"." diff --git a/plugins/youtube/broadcast-selection.cpp b/plugins/youtube/broadcast-selection.cpp index e3466503..89eff1c6 100644 --- a/plugins/youtube/broadcast-selection.cpp +++ b/plugins/youtube/broadcast-selection.cpp @@ -244,13 +244,13 @@ YouTubeBroadcast::GetInfo(YouTubeConnection &connection, bool useCache) const return {}; } -void BroadcastComboBox::showPopup() +void LazyFilterComboBox::showPopup() { - emit BroadcastListNeeded(); + emit ItemsNeeded(); FilterComboBox::showPopup(); } -void BroadcastComboBox::focusInEvent(QFocusEvent *event) +void LazyFilterComboBox::focusInEvent(QFocusEvent *event) { FilterComboBox::focusInEvent(event); @@ -261,7 +261,7 @@ void BroadcastComboBox::focusInEvent(QFocusEvent *event) reason == Qt::ActiveWindowFocusReason) { return; } - emit BroadcastListNeeded(); + emit ItemsNeeded(); } static const int selectionWidthInCharacters = 40; @@ -304,7 +304,7 @@ static QString getDisplayText(const YouTubeBroadcastInfo &broadcast) YouTubeBroadcastSelection::YouTubeBroadcastSelection(QWidget *parent) : QWidget(parent), - _selection(new BroadcastComboBox( + _selection(new LazyFilterComboBox( this, obs_module_text( "AdvSceneSwitcher.youtube.broadcast.select"))), _boundToObsStreamKey(new QLabel( @@ -344,7 +344,7 @@ YouTubeBroadcastSelection::YouTubeBroadcastSelection(QWidget *parent) QWidget::connect(_selection, SIGNAL(currentIndexChanged(int)), this, SLOT(SelectionChanged(int))); - QWidget::connect(_selection, SIGNAL(BroadcastListNeeded()), this, + QWidget::connect(_selection, SIGNAL(ItemsNeeded()), this, SLOT(UpdateBroadcastList())); QWidget::connect(_id, SIGNAL(editingFinished()), this, SLOT(IdChanged())); diff --git a/plugins/youtube/broadcast-selection.hpp b/plugins/youtube/broadcast-selection.hpp index 40453340..75c9cf97 100644 --- a/plugins/youtube/broadcast-selection.hpp +++ b/plugins/youtube/broadcast-selection.hpp @@ -49,7 +49,7 @@ private: std::string GetObsStreamId(YouTubeConnection &connection); -class BroadcastComboBox : public FilterComboBox { +class LazyFilterComboBox : public FilterComboBox { Q_OBJECT public: @@ -60,7 +60,7 @@ protected: void focusInEvent(QFocusEvent *event) override; signals: - void BroadcastListNeeded(); + void ItemsNeeded(); }; class YouTubeBroadcastSelection : public QWidget { @@ -88,7 +88,7 @@ private: YouTubeBroadcast::Type type); void SetWidgetVisibility(); - BroadcastComboBox *_selection; + LazyFilterComboBox *_selection; QLabel *_boundToObsStreamKey; QLabel *_selectedInObs; VariableLineEdit *_id; diff --git a/plugins/youtube/macro-action-youtube.cpp b/plugins/youtube/macro-action-youtube.cpp index 33083774..51f9e57f 100644 --- a/plugins/youtube/macro-action-youtube.cpp +++ b/plugins/youtube/macro-action-youtube.cpp @@ -8,7 +8,10 @@ #include #include +#include #include +#include +#include #include #include @@ -39,6 +42,15 @@ const static std::vector> privacyTypes = { {"public", "AdvSceneSwitcher.action.youtube.create.privacy.public"}, }; +const static std::vector> latencyTypes = { + {"normal", "AdvSceneSwitcher.action.youtube.create.latency.normal"}, + {"low", "AdvSceneSwitcher.action.youtube.create.latency.low"}, + {"ultraLow", "AdvSceneSwitcher.action.youtube.create.latency.ultraLow"}, +}; + +// Limit enforced by YouTube for custom thumbnails +static const qint64 maxThumbnailSize = 2 * 1024 * 1024; + static bool transitionBroadcast(YouTubeConnection &connection, const std::string &id, const std::string &status) @@ -145,29 +157,101 @@ static void bindBroadcastToObsStreamKey(YouTubeConnection &connection, {"streamId", streamId}}); } +static void setVideoCategory(YouTubeConnection &connection, + const std::string &videoId, + const std::string &title, + const std::string &description, + const std::string &categoryId) +{ + // The snippet is replaced as a whole, so title and description have to + // be sent again + const nlohmann::json body = { + {"id", videoId}, + {"snippet", + {{"title", title}, + {"description", description}, + {"categoryId", categoryId}}}, + }; + SendYouTubeRequest(connection, YouTubeRequestMethod::PUT, "/videos", + {{"part", "snippet"}}, + body.dump(-1, ' ', false, + nlohmann::json::error_handler_t::replace)); +} + +static void uploadThumbnail(YouTubeConnection &connection, + const std::string &videoId, const QString &path) +{ + QFile file(path); + if (!file.open(QIODevice::ReadOnly)) { + blog(LOG_WARNING, "could not open YouTube thumbnail \"%s\"", + path.toUtf8().constData()); + return; + } + if (file.size() > maxThumbnailSize) { + blog(LOG_WARNING, + "YouTube thumbnail \"%s\" is larger than 2 MB", + path.toUtf8().constData()); + return; + } + + const auto data = file.readAll(); + const auto mimeType = QMimeDatabase().mimeTypeForData(data).name(); + SendYouTubeUploadRequest(connection, "/thumbnails/set", + {{"videoId", videoId}}, + std::string(data.constData(), data.size()), + mimeType.toStdString()); +} + +static std::string getScheduledStartTime(bool scheduleForLater, + const Duration &startIn) +{ + auto startTime = QDateTime::currentDateTimeUtc(); + if (scheduleForLater) { + startTime = startTime.addMSecs( + static_cast(startIn.Milliseconds())); + } + return startTime.toString(Qt::ISODate).toStdString(); +} + void MacroActionYouTube::CreateBroadcast(YouTubeConnection &connection) { const std::string title = _title; + const std::string description = _description; const nlohmann::json body = { {"snippet", {{"title", title}, - {"description", std::string(_description)}, - {"scheduledStartTime", QDateTime::currentDateTimeUtc() - .toString(Qt::ISODate) - .toStdString()}}}, + {"description", description}, + {"scheduledStartTime", + getScheduledStartTime(_scheduleForLater, + _scheduledStartIn)}}}, {"status", {{"privacyStatus", _privacy}, {"selfDeclaredMadeForKids", _madeForKids}}}, {"contentDetails", - {{"enableAutoStart", _autoStart}, - {"enableAutoStop", _autoStop}}}, + {{"latencyPreference", _latency}, + {"enableAutoStart", _autoStart}, + {"enableAutoStop", _autoStop}, + {"enableDvr", _dvr}, + {"projection", _projection360 ? "360" : "rectangular"}, + // Same as broadcasts created by OBS, which allows going live + // without the testing state first + {"monitorStream", {{"enableMonitorStream", false}}}}}, }; + const auto categoryId = _categoryId; + const auto thumbnail = QString::fromStdString(_thumbnail); const bool bindToObsStreamKey = _bindToObsStreamKey; std::string id; { SuspendLock suspendLock(*this); id = createBroadcast(connection, body); + if (!id.empty() && !categoryId.empty()) { + setVideoCategory(connection, id, title, description, + categoryId); + } + if (!id.empty() && !thumbnail.isEmpty()) { + uploadThumbnail(connection, id, thumbnail); + } if (!id.empty() && bindToObsStreamKey) { bindBroadcastToObsStreamKey(connection, id); } @@ -240,6 +324,14 @@ bool MacroActionYouTube::Save(obs_data_t *obj) const obs_data_set_bool(obj, "autoStop", _autoStop); obs_data_set_bool(obj, "madeForKids", _madeForKids); obs_data_set_bool(obj, "bindToObsStreamKey", _bindToObsStreamKey); + obs_data_set_string(obj, "categoryId", _categoryId.c_str()); + obs_data_set_string(obj, "categoryTitle", _categoryTitle.c_str()); + _thumbnail.Save(obj, "thumbnail"); + obs_data_set_string(obj, "latency", _latency.c_str()); + obs_data_set_bool(obj, "dvr", _dvr); + obs_data_set_bool(obj, "projection360", _projection360); + obs_data_set_bool(obj, "scheduleForLater", _scheduleForLater); + _scheduledStartIn.Save(obj, "scheduledStartIn"); return true; } @@ -261,6 +353,16 @@ bool MacroActionYouTube::Load(obs_data_t *obj) _autoStop = obs_data_get_bool(obj, "autoStop"); _madeForKids = obs_data_get_bool(obj, "madeForKids"); _bindToObsStreamKey = obs_data_get_bool(obj, "bindToObsStreamKey"); + _categoryId = obs_data_get_string(obj, "categoryId"); + _categoryTitle = obs_data_get_string(obj, "categoryTitle"); + _thumbnail.Load(obj, "thumbnail"); + obs_data_set_default_string(obj, "latency", "normal"); + obs_data_set_default_bool(obj, "dvr", true); + _latency = obs_data_get_string(obj, "latency"); + _dvr = obs_data_get_bool(obj, "dvr"); + _projection360 = obs_data_get_bool(obj, "projection360"); + _scheduleForLater = obs_data_get_bool(obj, "scheduleForLater"); + _scheduledStartIn.Load(obj, "scheduledStartIn"); return true; } @@ -302,6 +404,49 @@ void MacroActionYouTube::ResolveVariablesToFixedValues() _broadcast.ResolveVariables(); _title.ResolveVariables(); _description.ResolveVariables(); + _thumbnail.ResolveVariables(); + _scheduledStartIn.ResolveVariables(); +} + +static YouTubeRequestResult +requestVideoCategories(YouTubeConnection &connection, + const std::string &language) +{ + // Other regions lack categories which are still available to channels + // in those regions, so only the language is localized like OBS does + return SendYouTubeRequest( + connection, YouTubeRequestMethod::GET, "/videoCategories", + {{"part", "snippet"}, {"regionCode", "US"}, {"hl", language}}, + "", true); +} + +static std::vector +getVideoCategories(YouTubeConnection &connection) +{ + auto result = requestVideoCategories(connection, + QLocale().name().toStdString()); + if (result.errorReason == "unsupportedLanguageCode" || + result.errorReason == "invalidLanguage") { + result = requestVideoCategories(connection, "en_US"); + } + if (result.status != 200) { + return {}; + } + + std::vector categories; + OBSDataArrayAutoRelease items = + obs_data_get_array(result.data, "items"); + const size_t count = obs_data_array_count(items); + for (size_t i = 0; i < count; i++) { + OBSDataAutoRelease item = obs_data_array_item(items, i); + OBSDataAutoRelease snippet = obs_data_get_obj(item, "snippet"); + if (!obs_data_get_bool(snippet, "assignable")) { + continue; + } + categories.push_back({obs_data_get_string(item, "id"), + obs_data_get_string(snippet, "title")}); + } + return categories; } static void populateActionSelection(QComboBox *list) @@ -312,6 +457,16 @@ static void populateActionSelection(QComboBox *list) } } +static void populateValueSelection( + QComboBox *list, + const std::vector> &values) +{ + for (const auto &[value, name] : values) { + list->addItem(obs_module_text(name.c_str()), + QString::fromStdString(value)); + } +} + MacroActionYouTubeEdit::MacroActionYouTubeEdit( QWidget *parent, std::shared_ptr entryData) : QWidget(parent), @@ -323,10 +478,20 @@ MacroActionYouTubeEdit::MacroActionYouTubeEdit( _title(new VariableLineEdit(this)), _description(new VariableTextEdit(this, 5, 1, 1)), _privacy(new QComboBox(this)), + _category(new LazyFilterComboBox(this)), + _thumbnail(new FileSelection(FileSelection::Type::READ, this)), + _latency(new QComboBox(this)), + _scheduleForLater(new QCheckBox(obs_module_text( + "AdvSceneSwitcher.action.youtube.create.scheduleForLater"))), + _scheduledStartIn(new DurationSelection(this)), _autoStart(new QCheckBox(obs_module_text( "AdvSceneSwitcher.action.youtube.create.autoStart"))), _autoStop(new QCheckBox(obs_module_text( "AdvSceneSwitcher.action.youtube.create.autoStop"))), + _dvr(new QCheckBox(obs_module_text( + "AdvSceneSwitcher.action.youtube.create.dvr"))), + _projection360(new QCheckBox(obs_module_text( + "AdvSceneSwitcher.action.youtube.create.projection360"))), _madeForKids(new QCheckBox(obs_module_text( "AdvSceneSwitcher.action.youtube.create.madeForKids"))), _bindToObsStreamKey(new QCheckBox(obs_module_text( @@ -334,10 +499,10 @@ MacroActionYouTubeEdit::MacroActionYouTubeEdit( _connectionWarning(new QLabel(this)) { populateActionSelection(_actions); - for (const auto &[value, name] : privacyTypes) { - _privacy->addItem(obs_module_text(name.c_str()), - QString::fromStdString(value)); - } + populateValueSelection(_privacy, privacyTypes); + populateValueSelection(_latency, latencyTypes); + _thumbnail->setToolTip(obs_module_text( + "AdvSceneSwitcher.action.youtube.create.thumbnail.tooltip")); QWidget::connect(_connections, SIGNAL(SelectionChanged(const QString &)), this, @@ -354,8 +519,20 @@ MacroActionYouTubeEdit::MacroActionYouTubeEdit( SLOT(DescriptionChanged())); QWidget::connect(_privacy, SIGNAL(currentIndexChanged(int)), this, SLOT(PrivacyChanged(int))); + QWidget::connect(_category, SIGNAL(currentIndexChanged(int)), this, + SLOT(CategoryChanged(int))); + QWidget::connect(_category, SIGNAL(ItemsNeeded()), this, + SLOT(UpdateCategoryList())); + QWidget::connect(_thumbnail, SIGNAL(PathChanged(const QString &)), this, + SLOT(ThumbnailChanged(const QString &))); + QWidget::connect(_latency, SIGNAL(currentIndexChanged(int)), this, + SLOT(LatencyChanged(int))); + QWidget::connect(_scheduledStartIn, + SIGNAL(DurationChanged(const Duration &)), this, + SLOT(ScheduledStartInChanged(const Duration &))); for (const auto checkBox : - {_autoStart, _autoStop, _madeForKids, _bindToObsStreamKey}) { + {_scheduleForLater, _autoStart, _autoStop, _dvr, _projection360, + _madeForKids, _bindToObsStreamKey}) { QWidget::connect(checkBox, SIGNAL(stateChanged(int)), this, SLOT(CreateOptionsChanged())); } @@ -384,14 +561,42 @@ MacroActionYouTubeEdit::MacroActionYouTubeEdit( obs_module_text( "AdvSceneSwitcher.action.youtube.create.layout.privacy"), privacyLayout, {{"{{privacy}}", _privacy}}); + auto categoryLayout = new QHBoxLayout(); + PlaceWidgets( + obs_module_text( + "AdvSceneSwitcher.action.youtube.create.layout.category"), + categoryLayout, {{"{{category}}", _category}}); + auto thumbnailLayout = new QHBoxLayout(); + PlaceWidgets( + obs_module_text( + "AdvSceneSwitcher.action.youtube.create.layout.thumbnail"), + thumbnailLayout, {{"{{thumbnail}}", _thumbnail}}, false); + auto latencyLayout = new QHBoxLayout(); + PlaceWidgets( + obs_module_text( + "AdvSceneSwitcher.action.youtube.create.layout.latency"), + latencyLayout, {{"{{latency}}", _latency}}); + auto scheduleLayout = new QHBoxLayout(); + PlaceWidgets( + obs_module_text( + "AdvSceneSwitcher.action.youtube.create.layout.schedule"), + scheduleLayout, + {{"{{scheduleForLater}}", _scheduleForLater}, + {"{{scheduledStartIn}}", _scheduledStartIn}}); auto createLayout = new QVBoxLayout(); createLayout->setContentsMargins(0, 0, 0, 0); createLayout->addLayout(titleLayout); createLayout->addLayout(descriptionLayout); createLayout->addLayout(privacyLayout); + createLayout->addLayout(categoryLayout); + createLayout->addLayout(thumbnailLayout); + createLayout->addLayout(latencyLayout); + createLayout->addLayout(scheduleLayout); createLayout->addWidget(_autoStart); createLayout->addWidget(_autoStop); + createLayout->addWidget(_dvr); + createLayout->addWidget(_projection360); createLayout->addWidget(_madeForKids); createLayout->addWidget(_bindToObsStreamKey); _createSettings->setLayout(createLayout); @@ -424,8 +629,16 @@ void MacroActionYouTubeEdit::UpdateEntryData() _description->setPlainText(_entryData->_description); _privacy->setCurrentIndex(_privacy->findData( QString::fromStdString(_entryData->_privacy))); + PopulateCategories({}); + _thumbnail->SetPath(_entryData->_thumbnail); + _latency->setCurrentIndex(_latency->findData( + QString::fromStdString(_entryData->_latency))); + _scheduleForLater->setChecked(_entryData->_scheduleForLater); + _scheduledStartIn->SetDuration(_entryData->_scheduledStartIn); _autoStart->setChecked(_entryData->_autoStart); _autoStop->setChecked(_entryData->_autoStop); + _dvr->setChecked(_entryData->_dvr); + _projection360->setChecked(_entryData->_projection360); _madeForKids->setChecked(_entryData->_madeForKids); _bindToObsStreamKey->setChecked(_entryData->_bindToObsStreamKey); SetWidgetVisibility(); @@ -471,13 +684,91 @@ void MacroActionYouTubeEdit::PrivacyChanged(int index) _privacy->itemData(index).toString().toStdString(); } +void MacroActionYouTubeEdit::PopulateCategories( + const std::vector &categories) +{ + if (!_entryData) { + return; + } + + const QSignalBlocker blocker(_category); + _category->clear(); + _category->addItem( + obs_module_text( + "AdvSceneSwitcher.action.youtube.create.category.default"), + QString()); + + const auto &selectedId = _entryData->_categoryId; + bool selectedCategoryListed = false; + for (const auto &category : categories) { + _category->addItem(QString::fromStdString(category.title), + QString::fromStdString(category.id)); + selectedCategoryListed |= category.id == selectedId; + } + + // Keep showing the selection if the list was not fetched yet + if (!selectedId.empty() && !selectedCategoryListed) { + _category->addItem( + QString::fromStdString(_entryData->_categoryTitle), + QString::fromStdString(selectedId)); + } + + _category->setCurrentIndex( + _category->findData(QString::fromStdString(selectedId))); +} + +void MacroActionYouTubeEdit::UpdateCategoryList() +{ + if (!_entryData) { + return; + } + + auto connection = _entryData->_connection.lock(); + PopulateCategories(connection ? getVideoCategories(*connection) + : std::vector()); +} + +void MacroActionYouTubeEdit::CategoryChanged(int index) +{ + GUARD_LOADING_AND_LOCK(); + _entryData->_categoryId = + _category->itemData(index).toString().toStdString(); + _entryData->_categoryTitle = + _entryData->_categoryId.empty() + ? "" + : _category->itemText(index).toStdString(); +} + +void MacroActionYouTubeEdit::ThumbnailChanged(const QString &path) +{ + GUARD_LOADING_AND_LOCK(); + _entryData->_thumbnail = path.toStdString(); +} + +void MacroActionYouTubeEdit::LatencyChanged(int index) +{ + GUARD_LOADING_AND_LOCK(); + _entryData->_latency = + _latency->itemData(index).toString().toStdString(); +} + +void MacroActionYouTubeEdit::ScheduledStartInChanged(const Duration &duration) +{ + GUARD_LOADING_AND_LOCK(); + _entryData->_scheduledStartIn = duration; +} + void MacroActionYouTubeEdit::CreateOptionsChanged() { GUARD_LOADING_AND_LOCK(); + _entryData->_scheduleForLater = _scheduleForLater->isChecked(); _entryData->_autoStart = _autoStart->isChecked(); _entryData->_autoStop = _autoStop->isChecked(); + _entryData->_dvr = _dvr->isChecked(); + _entryData->_projection360 = _projection360->isChecked(); _entryData->_madeForKids = _madeForKids->isChecked(); _entryData->_bindToObsStreamKey = _bindToObsStreamKey->isChecked(); + _scheduledStartIn->setEnabled(_entryData->_scheduleForLater); } void MacroActionYouTubeEdit::SetWidgetVisibility() @@ -493,6 +784,7 @@ void MacroActionYouTubeEdit::SetWidgetVisibility() MacroActionYouTube::Action::START_BROADCAST; _broadcast->setVisible(!isCreate); _createSettings->setVisible(isCreate); + _scheduledStartIn->setEnabled(_entryData->_scheduleForLater); _help->setVisible(isCreate || isStart); _help->setToolTip(obs_module_text( isCreate ? "AdvSceneSwitcher.action.youtube.create.help" diff --git a/plugins/youtube/macro-action-youtube.hpp b/plugins/youtube/macro-action-youtube.hpp index aacdefbb..ed55bcb3 100644 --- a/plugins/youtube/macro-action-youtube.hpp +++ b/plugins/youtube/macro-action-youtube.hpp @@ -2,6 +2,9 @@ #include "broadcast-selection.hpp" #include "youtube-connection.hpp" +#include +#include +#include #include #include #include @@ -13,6 +16,11 @@ namespace advss { +struct YouTubeVideoCategory { + std::string id; + std::string title; +}; + class MacroActionYouTube : public MacroAction { public: MacroActionYouTube(Macro *m) : MacroAction(m) {} @@ -45,6 +53,14 @@ public: bool _autoStop = true; bool _madeForKids = false; bool _bindToObsStreamKey = true; + std::string _categoryId; + std::string _categoryTitle; + StringVariable _thumbnail = ""; + std::string _latency = "normal"; + bool _dvr = true; + bool _projection360 = false; + bool _scheduleForLater = false; + Duration _scheduledStartIn = 3600.0; private: void CreateBroadcast(YouTubeConnection &connection); @@ -79,6 +95,11 @@ private slots: void TitleChanged(); void DescriptionChanged(); void PrivacyChanged(int); + void CategoryChanged(int); + void UpdateCategoryList(); + void ThumbnailChanged(const QString &); + void LatencyChanged(int); + void ScheduledStartInChanged(const Duration &); void CreateOptionsChanged(); void CheckConnection(); @@ -86,6 +107,7 @@ signals: void HeaderInfoChanged(const QString &); private: + void PopulateCategories(const std::vector &); void SetWidgetVisibility(); YouTubeConnectionSelection *_connections; @@ -96,8 +118,15 @@ private: VariableLineEdit *_title; VariableTextEdit *_description; QComboBox *_privacy; + LazyFilterComboBox *_category; + FileSelection *_thumbnail; + QComboBox *_latency; + QCheckBox *_scheduleForLater; + DurationSelection *_scheduledStartIn; QCheckBox *_autoStart; QCheckBox *_autoStop; + QCheckBox *_dvr; + QCheckBox *_projection360; QCheckBox *_madeForKids; QCheckBox *_bindToObsStreamKey; QLabel *_connectionWarning; diff --git a/plugins/youtube/youtube-helpers.cpp b/plugins/youtube/youtube-helpers.cpp index 6bd6788c..c30c7fe2 100644 --- a/plugins/youtube/youtube-helpers.cpp +++ b/plugins/youtube/youtube-helpers.cpp @@ -12,6 +12,7 @@ namespace advss { static const char *tokenHost = "https://oauth2.googleapis.com"; static const char *apiHost = "https://www.googleapis.com"; static const char *apiBasePath = "/youtube/v3"; +static const char *uploadBasePath = "/upload/youtube/v3"; // Conditions are checked frequently, so cache responses to stay within the // daily API quota static const int cacheTimeoutSeconds = 30; @@ -94,17 +95,21 @@ static std::string getErrorReason(obs_data_t *data) return obs_data_get_string(firstError, "reason"); } -static httplib::Result sendRequest(YouTubeRequestMethod method, - const std::string &path, - const httplib::Params ¶ms, - const std::string &body, - const std::string &accessToken) +struct RequestBody { + const std::string &data; + const char *contentType = "application/json"; +}; + +static httplib::Result +sendRequest(YouTubeRequestMethod method, const std::string &basePath, + const std::string &path, const httplib::Params ¶ms, + const RequestBody &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); + httplib::append_query_params(basePath + path, params); switch (method) { case YouTubeRequestMethod::GET: @@ -112,16 +117,18 @@ static httplib::Result sendRequest(YouTubeRequestMethod method, 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 cli.Post(fullPath, headers, body.data, body.contentType); + case YouTubeRequestMethod::PUT: + vblog(LOG_INFO, "YouTube PUT request to %s", fullPath.c_str()); + return cli.Put(fullPath, headers, body.data, body.contentType); } return httplib::Result(); } -static YouTubeRequestResult sendYouTubeRequest(YouTubeConnection &connection, - YouTubeRequestMethod method, - const std::string &path, - const httplib::Params ¶ms, - const std::string &body) +static YouTubeRequestResult +sendYouTubeRequest(YouTubeConnection &connection, YouTubeRequestMethod method, + const std::string &basePath, const std::string &path, + const httplib::Params ¶ms, const RequestBody &body) { if (connection.RequestsArePaused()) { vblog(LOG_INFO, "skipping YouTube request to %s due to quota", @@ -134,14 +141,15 @@ static YouTubeRequestResult sendYouTubeRequest(YouTubeConnection &connection, return {}; } - auto response = sendRequest(method, path, params, body, *accessToken); + auto response = + sendRequest(method, basePath, path, params, body, *accessToken); if (response && response->status == 401) { accessToken = connection.GetAccessToken(true); if (!accessToken) { return {}; } - response = - sendRequest(method, path, params, body, *accessToken); + response = sendRequest(method, basePath, path, params, body, + *accessToken); } if (!response) { @@ -200,8 +208,8 @@ YouTubeRequestResult SendYouTubeRequest(YouTubeConnection &connection, const std::string &body, bool useCache) { if (!useCache || method != YouTubeRequestMethod::GET) { - return sendYouTubeRequest(connection, method, path, params, - body); + return sendYouTubeRequest(connection, method, apiBasePath, path, + params, {body}); } static std::mutex mutex; @@ -227,11 +235,22 @@ YouTubeRequestResult SendYouTubeRequest(YouTubeConnection &connection, } // Failed requests are cached as well, as they also cost API quota - auto result = - sendYouTubeRequest(connection, method, path, params, body); + auto result = sendYouTubeRequest(connection, method, apiBasePath, path, + params, {body}); std::lock_guard lock(mutex); cache[key] = {result, now}; return result; } +YouTubeRequestResult SendYouTubeUploadRequest(YouTubeConnection &connection, + const std::string &path, + const httplib::Params ¶ms, + const std::string &data, + const std::string &contentType) +{ + return sendYouTubeRequest(connection, YouTubeRequestMethod::POST, + uploadBasePath, path, params, + {data, contentType.c_str()}); +} + } // namespace advss diff --git a/plugins/youtube/youtube-helpers.hpp b/plugins/youtube/youtube-helpers.hpp index 93b10b13..a3cdf135 100644 --- a/plugins/youtube/youtube-helpers.hpp +++ b/plugins/youtube/youtube-helpers.hpp @@ -17,6 +17,7 @@ struct YouTubeRequestResult { enum class YouTubeRequestMethod { GET, POST, + PUT, }; TokenResponse ExchangeAuthCode(const OAuthClientConfig &config, @@ -31,5 +32,10 @@ YouTubeRequestResult SendYouTubeRequest(YouTubeConnection &connection, YouTubeRequestMethod method, const std::string &path, const httplib::Params ¶ms = {}, const std::string &body = "", bool useCache = false); +YouTubeRequestResult SendYouTubeUploadRequest(YouTubeConnection &connection, + const std::string &path, + const httplib::Params ¶ms, + const std::string &data, + const std::string &contentType); } // namespace advss