window-youtube-actions.cpp 26 KB

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