1
0

OBSYoutubeActions.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. #include "OBSYoutubeActions.hpp"
  2. #include <docks/YouTubeAppDock.hpp>
  3. #include <widgets/OBSBasic.hpp>
  4. #include <qt-wrappers.hpp>
  5. #include <QDesktopServices>
  6. #include <QFileInfo>
  7. #include <QImageReader>
  8. #include <QStandardPaths>
  9. #include <QToolTip>
  10. #include "moc_OBSYoutubeActions.cpp"
  11. const QString SchedulDateAndTimeFormat = "yyyy-MM-dd'T'hh:mm:ss'Z'";
  12. const QString RepresentSchedulDateAndTimeFormat = "dddd, MMMM d, yyyy h:m";
  13. const QString IndexOfGamingCategory = "20";
  14. OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, bool broadcastReady)
  15. : QDialog(parent),
  16. ui(new Ui::OBSYoutubeActions),
  17. apiYouTube(dynamic_cast<YoutubeApiWrappers *>(auth)),
  18. workerThread(new WorkerThread(apiYouTube)),
  19. broadcastReady(broadcastReady)
  20. {
  21. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  22. ui->setupUi(this);
  23. ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Public"), "public");
  24. ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Unlisted"), "unlisted");
  25. ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Private"), "private");
  26. ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Normal"), "normal");
  27. ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Low"), "low");
  28. ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.UltraLow"), "ultraLow");
  29. UpdateOkButtonStatus();
  30. connect(ui->title, &QLineEdit::textChanged, this, [&](const QString &) { this->UpdateOkButtonStatus(); });
  31. connect(ui->privacyBox, &QComboBox::currentTextChanged, this,
  32. [&](const QString &) { this->UpdateOkButtonStatus(); });
  33. connect(ui->yesMakeForKids, &QRadioButton::toggled, this, [&](bool) { this->UpdateOkButtonStatus(); });
  34. connect(ui->notMakeForKids, &QRadioButton::toggled, this, [&](bool) { this->UpdateOkButtonStatus(); });
  35. connect(ui->tabWidget, &QTabWidget::currentChanged, this, [&](int) { this->UpdateOkButtonStatus(); });
  36. connect(ui->pushButton, &QPushButton::clicked, this, &OBSYoutubeActions::OpenYouTubeDashboard);
  37. connect(ui->helpAutoStartStop, &QLabel::linkActivated, this,
  38. [](const QString &) { QToolTip::showText(QCursor::pos(), QTStr("YouTube.Actions.AutoStartStop.TT")); });
  39. connect(ui->help360Video, &QLabel::linkActivated, this,
  40. [](const QString &link) { QDesktopServices::openUrl(link); });
  41. connect(ui->helpMadeForKids, &QLabel::linkActivated, this,
  42. [](const QString &link) { QDesktopServices::openUrl(link); });
  43. ui->scheduledTime->setVisible(false);
  44. #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
  45. connect(ui->checkScheduledLater, &QCheckBox::checkStateChanged, this,
  46. [&](Qt::CheckState state)
  47. #else
  48. connect(ui->checkScheduledLater, &QCheckBox::stateChanged, this,
  49. [&](int state)
  50. #endif
  51. {
  52. const bool checked = (state == Qt::Checked);
  53. ui->scheduledTime->setVisible(checked);
  54. if (checked) {
  55. ui->checkAutoStart->setVisible(true);
  56. ui->checkAutoStop->setVisible(true);
  57. ui->helpAutoStartStop->setVisible(true);
  58. ui->checkAutoStart->setChecked(false);
  59. ui->checkAutoStop->setChecked(false);
  60. } else {
  61. ui->checkAutoStart->setVisible(false);
  62. ui->checkAutoStop->setVisible(false);
  63. ui->helpAutoStartStop->setVisible(false);
  64. ui->checkAutoStart->setChecked(true);
  65. ui->checkAutoStop->setChecked(true);
  66. }
  67. UpdateOkButtonStatus();
  68. });
  69. ui->checkAutoStart->setVisible(false);
  70. ui->checkAutoStop->setVisible(false);
  71. ui->helpAutoStartStop->setVisible(false);
  72. ui->scheduledTime->setDateTime(QDateTime::currentDateTime());
  73. auto thumbSelectionHandler = [&]() {
  74. if (thumbnailFile.isEmpty()) {
  75. QString filePath = OpenFile(this, QTStr("YouTube.Actions.Thumbnail.SelectFile"),
  76. QStandardPaths::writableLocation(QStandardPaths::PicturesLocation),
  77. QString("Images (*.png *.jpg *.jpeg *.gif)"));
  78. if (!filePath.isEmpty()) {
  79. QFileInfo tFile(filePath);
  80. if (!tFile.exists()) {
  81. return ShowErrorDialog(this, QTStr("YouTube.Actions.Error.FileMissing"));
  82. } else if (tFile.size() > 2 * 1024 * 1024) {
  83. return ShowErrorDialog(this, QTStr("YouTube.Actions.Error.FileTooLarge"));
  84. }
  85. thumbnailFile = filePath;
  86. ui->selectedFileName->setText(thumbnailFile);
  87. ui->selectFileButton->setText(QTStr("YouTube.Actions.Thumbnail.ClearFile"));
  88. QImageReader imgReader(filePath);
  89. imgReader.setAutoTransform(true);
  90. const QImage newImage = imgReader.read();
  91. ui->thumbnailPreview->setPixmap(QPixmap::fromImage(newImage).scaled(
  92. 160, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  93. }
  94. } else {
  95. thumbnailFile.clear();
  96. ui->selectedFileName->setText(QTStr("YouTube.Actions.Thumbnail.NoFileSelected"));
  97. ui->selectFileButton->setText(QTStr("YouTube.Actions.Thumbnail.SelectFile"));
  98. ui->thumbnailPreview->setPixmap(GetPlaceholder().pixmap(QSize(16, 16)));
  99. }
  100. };
  101. connect(ui->selectFileButton, &QPushButton::clicked, this, thumbSelectionHandler);
  102. connect(ui->thumbnailPreview, &ClickableLabel::clicked, this, thumbSelectionHandler);
  103. if (!apiYouTube) {
  104. blog(LOG_DEBUG, "YouTube API auth NOT found.");
  105. Cancel();
  106. return;
  107. }
  108. const char *name = config_get_string(OBSBasic::Get()->Config(), "YouTube", "ChannelName");
  109. this->setWindowTitle(QTStr("YouTube.Actions.WindowTitle").arg(name));
  110. QVector<CategoryDescription> category_list;
  111. if (!apiYouTube->GetVideoCategoriesList(category_list)) {
  112. ShowErrorDialog(parent, apiYouTube->GetLastError().isEmpty()
  113. ? QTStr("YouTube.Actions.Error.General")
  114. : QTStr("YouTube.Actions.Error.Text").arg(apiYouTube->GetLastError()));
  115. Cancel();
  116. return;
  117. }
  118. for (auto &category : category_list) {
  119. ui->categoryBox->addItem(category.title, category.id);
  120. if (category.id == IndexOfGamingCategory) {
  121. ui->categoryBox->setCurrentText(category.title);
  122. }
  123. }
  124. connect(ui->okButton, &QPushButton::clicked, this, &OBSYoutubeActions::InitBroadcast);
  125. connect(ui->saveButton, &QPushButton::clicked, this, &OBSYoutubeActions::ReadyBroadcast);
  126. connect(ui->cancelButton, &QPushButton::clicked, this, [&]() {
  127. blog(LOG_DEBUG, "YouTube live broadcast creation cancelled.");
  128. // Close the dialog.
  129. Cancel();
  130. });
  131. qDeleteAll(ui->scrollAreaWidgetContents->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly));
  132. // Add label indicating loading state
  133. QLabel *loadingLabel = new QLabel();
  134. loadingLabel->setTextFormat(Qt::RichText);
  135. loadingLabel->setAlignment(Qt::AlignHCenter);
  136. loadingLabel->setText(QString("<big>%1</big>").arg(QTStr("YouTube.Actions.EventsLoading")));
  137. ui->scrollAreaWidgetContents->layout()->addWidget(loadingLabel);
  138. // Delete "loading..." label on completion
  139. connect(workerThread, &WorkerThread::finished, this, [&] {
  140. QLayoutItem *item = ui->scrollAreaWidgetContents->layout()->takeAt(0);
  141. item->widget()->deleteLater();
  142. });
  143. connect(workerThread, &WorkerThread::failed, this, [&]() {
  144. auto last_error = apiYouTube->GetLastError();
  145. if (last_error.isEmpty())
  146. last_error = QTStr("YouTube.Actions.Error.YouTubeApi");
  147. if (!apiYouTube->GetTranslatedError(last_error))
  148. last_error = QTStr("YouTube.Actions.Error.Text").arg(last_error);
  149. ShowErrorDialog(this, last_error);
  150. QDialog::reject();
  151. });
  152. connect(workerThread, &WorkerThread::new_item, this,
  153. [&](const QString &title, const QString &dateTimeString, const QString &broadcast,
  154. const QString &status, bool astart, bool astop) {
  155. ClickableLabel *label = new ClickableLabel();
  156. label->setTextFormat(Qt::RichText);
  157. if (status == "live" || status == "testing") {
  158. // Resumable stream
  159. label->setText(QString("<big>%1</big><br/>%2")
  160. .arg(title, QTStr("YouTube.Actions.Stream.Resume")));
  161. } else if (dateTimeString.isEmpty()) {
  162. // The broadcast created by YouTube Studio has no start time.
  163. // Yes this does violate the restrictions set in YouTube's API
  164. // But why would YouTube care about consistency?
  165. label->setText(QString("<big>%1</big><br/>%2")
  166. .arg(title, QTStr("YouTube.Actions.Stream.YTStudio")));
  167. } else {
  168. label->setText(
  169. QString("<big>%1</big><br/>%2")
  170. .arg(title,
  171. QTStr("YouTube.Actions.Stream.ScheduledFor").arg(dateTimeString)));
  172. }
  173. label->setAlignment(Qt::AlignHCenter);
  174. label->setMargin(4);
  175. connect(label, &ClickableLabel::clicked, this, [&, label, broadcast, astart, astop]() {
  176. for (QWidget *i : ui->scrollAreaWidgetContents->findChildren<QWidget *>(
  177. QString(), Qt::FindDirectChildrenOnly)) {
  178. i->setProperty("class", "");
  179. i->style()->unpolish(i);
  180. i->style()->polish(i);
  181. }
  182. label->setProperty("class", "row-selected");
  183. label->style()->unpolish(label);
  184. label->style()->polish(label);
  185. this->selectedBroadcast = broadcast;
  186. this->autostart = astart;
  187. this->autostop = astop;
  188. UpdateOkButtonStatus();
  189. });
  190. ui->scrollAreaWidgetContents->layout()->addWidget(label);
  191. if (selectedBroadcast == broadcast)
  192. label->clicked();
  193. });
  194. workerThread->start();
  195. OBSBasic *main = OBSBasic::Get();
  196. bool rememberSettings = config_get_bool(main->activeConfiguration, "YouTube", "RememberSettings");
  197. if (rememberSettings)
  198. LoadSettings();
  199. // Switch to events page and select readied broadcast once loaded
  200. if (broadcastReady) {
  201. ui->tabWidget->setCurrentIndex(1);
  202. selectedBroadcast = apiYouTube->GetBroadcastId();
  203. }
  204. #ifdef __APPLE__
  205. // MacOS theming issues
  206. this->resize(this->width() + 200, this->height() + 120);
  207. #endif
  208. valid = true;
  209. }
  210. void OBSYoutubeActions::showEvent(QShowEvent *event)
  211. {
  212. QDialog::showEvent(event);
  213. if (thumbnailFile.isEmpty())
  214. ui->thumbnailPreview->setPixmap(GetPlaceholder().pixmap(QSize(16, 16)));
  215. }
  216. OBSYoutubeActions::~OBSYoutubeActions()
  217. {
  218. workerThread->stop();
  219. workerThread->wait();
  220. delete workerThread;
  221. }
  222. void WorkerThread::run()
  223. {
  224. if (!pending)
  225. return;
  226. json11::Json broadcasts;
  227. for (QString broadcastStatus : {"active", "upcoming"}) {
  228. if (!apiYouTube->GetBroadcastsList(broadcasts, "", broadcastStatus)) {
  229. emit failed();
  230. return;
  231. }
  232. while (pending) {
  233. auto items = broadcasts["items"].array_items();
  234. for (auto item : items) {
  235. QString status =
  236. QString::fromStdString(item["status"]["lifeCycleStatus"].string_value());
  237. if (status == "live" || status == "testing") {
  238. // Check that the attached liveStream is offline (reconnectable)
  239. QString stream_id = QString::fromStdString(
  240. item["contentDetails"]["boundStreamId"].string_value());
  241. json11::Json stream;
  242. if (!apiYouTube->FindStream(stream_id, stream))
  243. continue;
  244. if (stream["status"]["streamStatus"] == "active")
  245. continue;
  246. }
  247. QString title = QString::fromStdString(item["snippet"]["title"].string_value());
  248. QString scheduledStartTime =
  249. QString::fromStdString(item["snippet"]["scheduledStartTime"].string_value());
  250. QString broadcast = QString::fromStdString(item["id"].string_value());
  251. // Treat already started streams as autostart for UI purposes
  252. bool astart = status == "live" ||
  253. item["contentDetails"]["enableAutoStart"].bool_value();
  254. bool astop = item["contentDetails"]["enableAutoStop"].bool_value();
  255. QDateTime utcDTime =
  256. QDateTime::fromString(scheduledStartTime, SchedulDateAndTimeFormat);
  257. // DateTime parser means that input datetime is a local, so we need to move it
  258. QDateTime dateTime = utcDTime.addSecs(utcDTime.offsetFromUtc());
  259. QString dateTimeString = QLocale().toString(
  260. dateTime, QString("%1 %2").arg(QLocale().dateFormat(QLocale::LongFormat),
  261. QLocale().timeFormat(QLocale::ShortFormat)));
  262. emit new_item(title, dateTimeString, broadcast, status, astart, astop);
  263. }
  264. auto nextPageToken = broadcasts["nextPageToken"].string_value();
  265. if (nextPageToken.empty() || items.empty())
  266. break;
  267. else {
  268. if (!pending)
  269. return;
  270. if (!apiYouTube->GetBroadcastsList(broadcasts, QString::fromStdString(nextPageToken),
  271. broadcastStatus)) {
  272. emit failed();
  273. return;
  274. }
  275. }
  276. }
  277. }
  278. emit ready();
  279. }
  280. void OBSYoutubeActions::UpdateOkButtonStatus()
  281. {
  282. bool enable = false;
  283. if (ui->tabWidget->currentIndex() == 0) {
  284. enable = !ui->title->text().isEmpty() && !ui->privacyBox->currentText().isEmpty() &&
  285. (ui->yesMakeForKids->isChecked() || ui->notMakeForKids->isChecked());
  286. ui->okButton->setEnabled(enable);
  287. ui->saveButton->setEnabled(enable);
  288. if (ui->checkScheduledLater->checkState() == Qt::Checked) {
  289. ui->okButton->setText(QTStr("YouTube.Actions.Create_Schedule"));
  290. ui->saveButton->setText(QTStr("YouTube.Actions.Create_Schedule_Ready"));
  291. } else {
  292. ui->okButton->setText(QTStr("YouTube.Actions.Create_GoLive"));
  293. ui->saveButton->setText(QTStr("YouTube.Actions.Create_Ready"));
  294. }
  295. ui->pushButton->setVisible(false);
  296. } else {
  297. enable = !selectedBroadcast.isEmpty();
  298. ui->okButton->setEnabled(enable);
  299. ui->saveButton->setEnabled(enable);
  300. ui->okButton->setText(QTStr("YouTube.Actions.Choose_GoLive"));
  301. ui->saveButton->setText(QTStr("YouTube.Actions.Choose_Ready"));
  302. ui->pushButton->setVisible(true);
  303. }
  304. }
  305. bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, BroadcastDescription &broadcast,
  306. StreamDescription &stream, bool stream_later, bool ready_broadcast)
  307. {
  308. YoutubeApiWrappers *apiYouTube = api;
  309. UiToBroadcast(broadcast);
  310. if (stream_later) {
  311. // DateTime parser means that input datetime is a local, so we need to move it
  312. auto dateTime = ui->scheduledTime->dateTime();
  313. auto utcDTime = dateTime.addSecs(-dateTime.offsetFromUtc());
  314. broadcast.schedul_date_time = utcDTime.toString(SchedulDateAndTimeFormat);
  315. } else {
  316. // stream now is always autostart/autostop
  317. broadcast.auto_start = true;
  318. broadcast.auto_stop = true;
  319. broadcast.schedul_date_time = QDateTime::currentDateTimeUtc().toString(SchedulDateAndTimeFormat);
  320. }
  321. autostart = broadcast.auto_start;
  322. autostop = broadcast.auto_stop;
  323. blog(LOG_DEBUG, "Scheduled date and time: %s", broadcast.schedul_date_time.toStdString().c_str());
  324. if (!apiYouTube->InsertBroadcast(broadcast)) {
  325. blog(LOG_DEBUG, "No broadcast created.");
  326. return false;
  327. }
  328. if (!apiYouTube->SetVideoCategory(broadcast.id, broadcast.title, broadcast.description,
  329. broadcast.category.id)) {
  330. blog(LOG_DEBUG, "No category set.");
  331. return false;
  332. }
  333. if (!thumbnailFile.isEmpty()) {
  334. blog(LOG_INFO, "Uploading thumbnail file \"%s\"...", thumbnailFile.toStdString().c_str());
  335. if (!apiYouTube->SetVideoThumbnail(broadcast.id, thumbnailFile)) {
  336. blog(LOG_DEBUG, "No thumbnail set.");
  337. return false;
  338. }
  339. }
  340. if (!stream_later || ready_broadcast) {
  341. stream = {"", "", "OBS Studio Video Stream"};
  342. if (!apiYouTube->InsertStream(stream)) {
  343. blog(LOG_DEBUG, "No stream created.");
  344. return false;
  345. }
  346. if (!apiYouTube->BindStream(broadcast.id, stream.id)) {
  347. blog(LOG_DEBUG, "No stream binded.");
  348. return false;
  349. }
  350. if (broadcast.privacy != "private") {
  351. apiYouTube->SetChatId(broadcast.id);
  352. } else {
  353. apiYouTube->ResetChat();
  354. }
  355. }
  356. #ifdef YOUTUBE_ENABLED
  357. if (OBSBasic::Get()->GetYouTubeAppDock())
  358. OBSBasic::Get()->GetYouTubeAppDock()->BroadcastCreated(broadcast.id.toStdString().c_str());
  359. #endif
  360. return true;
  361. }
  362. bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, StreamDescription &stream)
  363. {
  364. YoutubeApiWrappers *apiYouTube = api;
  365. json11::Json json;
  366. if (!apiYouTube->FindBroadcast(selectedBroadcast, json)) {
  367. blog(LOG_DEBUG, "No broadcast found.");
  368. return false;
  369. }
  370. std::string boundStreamId = json["items"].array_items()[0]["contentDetails"]["boundStreamId"].string_value();
  371. std::string broadcastPrivacy = json["items"].array_items()[0]["status"]["privacyStatus"].string_value();
  372. stream.id = boundStreamId.c_str();
  373. if (!stream.id.isEmpty() && apiYouTube->FindStream(stream.id, json)) {
  374. auto item = json["items"].array_items()[0];
  375. auto streamName = item["cdn"]["ingestionInfo"]["streamName"].string_value();
  376. auto title = item["snippet"]["title"].string_value();
  377. stream.name = streamName.c_str();
  378. stream.title = title.c_str();
  379. api->SetBroadcastId(selectedBroadcast);
  380. } else {
  381. stream = {"", "", "OBS Studio Video Stream"};
  382. if (!apiYouTube->InsertStream(stream)) {
  383. blog(LOG_DEBUG, "No stream created.");
  384. return false;
  385. }
  386. if (!apiYouTube->BindStream(selectedBroadcast, stream.id)) {
  387. blog(LOG_DEBUG, "No stream binded.");
  388. return false;
  389. }
  390. }
  391. if (broadcastPrivacy != "private")
  392. apiYouTube->SetChatId(selectedBroadcast);
  393. else
  394. apiYouTube->ResetChat();
  395. #ifdef YOUTUBE_ENABLED
  396. if (OBSBasic::Get()->GetYouTubeAppDock())
  397. OBSBasic::Get()->GetYouTubeAppDock()->BroadcastSelected(selectedBroadcast.toStdString().c_str());
  398. #endif
  399. return true;
  400. }
  401. void OBSYoutubeActions::ShowErrorDialog(QWidget *parent, QString text)
  402. {
  403. QMessageBox dlg(parent);
  404. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  405. dlg.setWindowTitle(QTStr("YouTube.Actions.Error.Title"));
  406. dlg.setText(text);
  407. dlg.setTextFormat(Qt::RichText);
  408. dlg.setIcon(QMessageBox::Warning);
  409. dlg.setStandardButtons(QMessageBox::StandardButton::Ok);
  410. dlg.exec();
  411. }
  412. void OBSYoutubeActions::InitBroadcast()
  413. {
  414. BroadcastDescription broadcast;
  415. StreamDescription stream;
  416. QMessageBox msgBox(this);
  417. msgBox.setWindowFlags(msgBox.windowFlags() & ~Qt::WindowCloseButtonHint);
  418. msgBox.setWindowTitle(QTStr("YouTube.Actions.Notify.Title"));
  419. msgBox.setText(QTStr("YouTube.Actions.Notify.CreatingBroadcast"));
  420. msgBox.setStandardButtons(QMessageBox::StandardButtons());
  421. bool success = false;
  422. auto action = [&]() {
  423. if (ui->tabWidget->currentIndex() == 0) {
  424. success = this->CreateEventAction(apiYouTube, broadcast, stream,
  425. ui->checkScheduledLater->isChecked());
  426. } else {
  427. success = this->ChooseAnEventAction(apiYouTube, stream);
  428. if (success)
  429. broadcast.id = this->selectedBroadcast;
  430. };
  431. QMetaObject::invokeMethod(&msgBox, "accept", Qt::QueuedConnection);
  432. };
  433. QScopedPointer<QThread> thread(CreateQThread(action));
  434. thread->start();
  435. msgBox.exec();
  436. thread->wait();
  437. if (success) {
  438. if (ui->tabWidget->currentIndex() == 0) {
  439. // Stream later usecase.
  440. if (ui->checkScheduledLater->isChecked()) {
  441. QMessageBox msg(this);
  442. msg.setWindowTitle(QTStr("YouTube.Actions.EventCreated.Title"));
  443. msg.setText(QTStr("YouTube.Actions.EventCreated.Text"));
  444. msg.setStandardButtons(QMessageBox::Ok);
  445. msg.exec();
  446. // Close dialog without start streaming.
  447. Cancel();
  448. } else {
  449. // Stream now usecase.
  450. blog(LOG_DEBUG, "New valid stream: %s", QT_TO_UTF8(stream.name));
  451. emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name), true,
  452. true, true);
  453. Accept();
  454. }
  455. } else {
  456. // Stream to precreated broadcast usecase.
  457. emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name), autostart,
  458. autostop, true);
  459. Accept();
  460. }
  461. } else {
  462. // Fail.
  463. auto last_error = apiYouTube->GetLastError();
  464. if (last_error.isEmpty())
  465. last_error = QTStr("YouTube.Actions.Error.YouTubeApi");
  466. if (!apiYouTube->GetTranslatedError(last_error))
  467. last_error = QTStr("YouTube.Actions.Error.NoBroadcastCreated").arg(last_error);
  468. ShowErrorDialog(this, last_error);
  469. }
  470. }
  471. void OBSYoutubeActions::ReadyBroadcast()
  472. {
  473. BroadcastDescription broadcast;
  474. StreamDescription stream;
  475. QMessageBox msgBox(this);
  476. msgBox.setWindowFlags(msgBox.windowFlags() & ~Qt::WindowCloseButtonHint);
  477. msgBox.setWindowTitle(QTStr("YouTube.Actions.Notify.Title"));
  478. msgBox.setText(QTStr("YouTube.Actions.Notify.CreatingBroadcast"));
  479. msgBox.setStandardButtons(QMessageBox::StandardButtons());
  480. bool success = false;
  481. auto action = [&]() {
  482. if (ui->tabWidget->currentIndex() == 0) {
  483. success = this->CreateEventAction(apiYouTube, broadcast, stream,
  484. ui->checkScheduledLater->isChecked(), true);
  485. } else {
  486. success = this->ChooseAnEventAction(apiYouTube, stream);
  487. if (success)
  488. broadcast.id = this->selectedBroadcast;
  489. };
  490. QMetaObject::invokeMethod(&msgBox, "accept", Qt::QueuedConnection);
  491. };
  492. QScopedPointer<QThread> thread(CreateQThread(action));
  493. thread->start();
  494. msgBox.exec();
  495. thread->wait();
  496. if (success) {
  497. emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name), autostart, autostop,
  498. false);
  499. Accept();
  500. } else {
  501. // Fail.
  502. auto last_error = apiYouTube->GetLastError();
  503. if (last_error.isEmpty())
  504. last_error = QTStr("YouTube.Actions.Error.YouTubeApi");
  505. if (!apiYouTube->GetTranslatedError(last_error))
  506. last_error = QTStr("YouTube.Actions.Error.NoBroadcastCreated").arg(last_error);
  507. ShowErrorDialog(this, last_error);
  508. }
  509. }
  510. void OBSYoutubeActions::UiToBroadcast(BroadcastDescription &broadcast)
  511. {
  512. broadcast.title = ui->title->text();
  513. // ToDo: UI warning rather than silent truncation
  514. broadcast.description = ui->description->toPlainText().left(5000);
  515. broadcast.privacy = ui->privacyBox->currentData().toString();
  516. broadcast.category.title = ui->categoryBox->currentText();
  517. broadcast.category.id = ui->categoryBox->currentData().toString();
  518. broadcast.made_for_kids = ui->yesMakeForKids->isChecked();
  519. broadcast.latency = ui->latencyBox->currentData().toString();
  520. broadcast.auto_start = ui->checkAutoStart->isChecked();
  521. broadcast.auto_stop = ui->checkAutoStop->isChecked();
  522. broadcast.dvr = ui->checkDVR->isChecked();
  523. broadcast.schedul_for_later = ui->checkScheduledLater->isChecked();
  524. broadcast.projection = ui->check360Video->isChecked() ? "360" : "rectangular";
  525. if (ui->checkRememberSettings->isChecked())
  526. SaveSettings(broadcast);
  527. }
  528. void OBSYoutubeActions::SaveSettings(BroadcastDescription &broadcast)
  529. {
  530. OBSBasic *main = OBSBasic::Get();
  531. config_set_string(main->activeConfiguration, "YouTube", "Title", QT_TO_UTF8(broadcast.title));
  532. config_set_string(main->activeConfiguration, "YouTube", "Description", QT_TO_UTF8(broadcast.description));
  533. config_set_string(main->activeConfiguration, "YouTube", "Privacy", QT_TO_UTF8(broadcast.privacy));
  534. config_set_string(main->activeConfiguration, "YouTube", "CategoryID", QT_TO_UTF8(broadcast.category.id));
  535. config_set_string(main->activeConfiguration, "YouTube", "Latency", QT_TO_UTF8(broadcast.latency));
  536. config_set_bool(main->activeConfiguration, "YouTube", "MadeForKids", broadcast.made_for_kids);
  537. config_set_bool(main->activeConfiguration, "YouTube", "AutoStart", broadcast.auto_start);
  538. config_set_bool(main->activeConfiguration, "YouTube", "AutoStop", broadcast.auto_start);
  539. config_set_bool(main->activeConfiguration, "YouTube", "DVR", broadcast.dvr);
  540. config_set_bool(main->activeConfiguration, "YouTube", "ScheduleForLater", broadcast.schedul_for_later);
  541. config_set_string(main->activeConfiguration, "YouTube", "Projection", QT_TO_UTF8(broadcast.projection));
  542. config_set_string(main->activeConfiguration, "YouTube", "ThumbnailFile", QT_TO_UTF8(thumbnailFile));
  543. config_set_bool(main->activeConfiguration, "YouTube", "RememberSettings", true);
  544. }
  545. void OBSYoutubeActions::LoadSettings()
  546. {
  547. OBSBasic *main = OBSBasic::Get();
  548. const char *title = config_get_string(main->activeConfiguration, "YouTube", "Title");
  549. ui->title->setText(QT_UTF8(title));
  550. const char *desc = config_get_string(main->activeConfiguration, "YouTube", "Description");
  551. ui->description->setPlainText(QT_UTF8(desc));
  552. const char *priv = config_get_string(main->activeConfiguration, "YouTube", "Privacy");
  553. int index = ui->privacyBox->findData(priv);
  554. ui->privacyBox->setCurrentIndex(index);
  555. const char *catID = config_get_string(main->activeConfiguration, "YouTube", "CategoryID");
  556. index = ui->categoryBox->findData(catID);
  557. ui->categoryBox->setCurrentIndex(index);
  558. const char *latency = config_get_string(main->activeConfiguration, "YouTube", "Latency");
  559. index = ui->latencyBox->findData(latency);
  560. ui->latencyBox->setCurrentIndex(index);
  561. bool dvr = config_get_bool(main->activeConfiguration, "YouTube", "DVR");
  562. ui->checkDVR->setChecked(dvr);
  563. bool forKids = config_get_bool(main->activeConfiguration, "YouTube", "MadeForKids");
  564. if (forKids)
  565. ui->yesMakeForKids->setChecked(true);
  566. else
  567. ui->notMakeForKids->setChecked(true);
  568. bool schedLater = config_get_bool(main->activeConfiguration, "YouTube", "ScheduleForLater");
  569. ui->checkScheduledLater->setChecked(schedLater);
  570. bool autoStart = config_get_bool(main->activeConfiguration, "YouTube", "AutoStart");
  571. ui->checkAutoStart->setChecked(autoStart);
  572. bool autoStop = config_get_bool(main->activeConfiguration, "YouTube", "AutoStop");
  573. ui->checkAutoStop->setChecked(autoStop);
  574. const char *projection = config_get_string(main->activeConfiguration, "YouTube", "Projection");
  575. if (projection && *projection) {
  576. if (strcmp(projection, "360") == 0)
  577. ui->check360Video->setChecked(true);
  578. else
  579. ui->check360Video->setChecked(false);
  580. }
  581. const char *thumbFile = config_get_string(main->activeConfiguration, "YouTube", "ThumbnailFile");
  582. if (thumbFile && *thumbFile) {
  583. QFileInfo tFile(thumbFile);
  584. // Re-check validity before setting path again
  585. if (tFile.exists() && tFile.size() <= 2 * 1024 * 1024) {
  586. thumbnailFile = tFile.absoluteFilePath();
  587. ui->selectedFileName->setText(thumbnailFile);
  588. ui->selectFileButton->setText(QTStr("YouTube.Actions.Thumbnail.ClearFile"));
  589. QImageReader imgReader(thumbnailFile);
  590. imgReader.setAutoTransform(true);
  591. const QImage newImage = imgReader.read();
  592. ui->thumbnailPreview->setPixmap(QPixmap::fromImage(newImage).scaled(
  593. 160, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation));
  594. }
  595. }
  596. }
  597. void OBSYoutubeActions::OpenYouTubeDashboard()
  598. {
  599. ChannelDescription channel;
  600. if (!apiYouTube->GetChannelDescription(channel)) {
  601. blog(LOG_DEBUG, "Could not get channel description.");
  602. ShowErrorDialog(this, apiYouTube->GetLastError().isEmpty()
  603. ? QTStr("YouTube.Actions.Error.General")
  604. : QTStr("YouTube.Actions.Error.Text").arg(apiYouTube->GetLastError()));
  605. return;
  606. }
  607. //https://studio.youtube.com/channel/UCA9bSfH3KL186kyiUsvi3IA/videos/live?filter=%5B%5D&sort=%7B%22columnType%22%3A%22date%22%2C%22sortOrder%22%3A%22DESCENDING%22%7D
  608. QString uri =
  609. QString("https://studio.youtube.com/channel/%1/videos/live?filter=[]&sort={\"columnType\"%3A\"date\"%2C\"sortOrder\"%3A\"DESCENDING\"}")
  610. .arg(channel.id);
  611. QDesktopServices::openUrl(uri);
  612. }
  613. void OBSYoutubeActions::Cancel()
  614. {
  615. workerThread->stop();
  616. reject();
  617. }
  618. void OBSYoutubeActions::Accept()
  619. {
  620. workerThread->stop();
  621. accept();
  622. }