window-youtube-actions.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  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 <QDateTime>
  7. #include <QDesktopServices>
  8. const QString SchedulDateAndTimeFormat = "yyyy-MM-dd'T'hh:mm:ss'Z'";
  9. const QString RepresentSchedulDateAndTimeFormat = "dddd, MMMM d, yyyy h:m";
  10. const QString NormalStylesheet = "border: 1px solid black; border-radius: 5px;";
  11. const QString SelectedStylesheet =
  12. "border: 2px solid black; border-radius: 5px;";
  13. const QString IndexOfGamingCategory = "20";
  14. OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth)
  15. : QDialog(parent),
  16. ui(new Ui::OBSYoutubeActions),
  17. apiYouTube(dynamic_cast<YoutubeApiWrappers *>(auth)),
  18. workerThread(new WorkerThread(apiYouTube))
  19. {
  20. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
  21. ui->setupUi(this);
  22. ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Public"),
  23. "public");
  24. ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Unlisted"),
  25. "unlisted");
  26. ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Private"),
  27. "private");
  28. ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Normal"),
  29. "normal");
  30. ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Low"), "low");
  31. ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.UltraLow"),
  32. "ultraLow");
  33. ui->checkAutoStart->setEnabled(false);
  34. ui->checkAutoStop->setEnabled(false);
  35. UpdateOkButtonStatus();
  36. connect(ui->title, &QLineEdit::textChanged, this,
  37. [&](const QString &) { this->UpdateOkButtonStatus(); });
  38. connect(ui->privacyBox, &QComboBox::currentTextChanged, this,
  39. [&](const QString &) { this->UpdateOkButtonStatus(); });
  40. connect(ui->yesMakeForKids, &QRadioButton::toggled, this,
  41. [&](bool) { this->UpdateOkButtonStatus(); });
  42. connect(ui->notMakeForKids, &QRadioButton::toggled, this,
  43. [&](bool) { this->UpdateOkButtonStatus(); });
  44. connect(ui->tabWidget, &QTabWidget::currentChanged, this,
  45. [&](int) { this->UpdateOkButtonStatus(); });
  46. connect(ui->pushButton, &QPushButton::clicked, this,
  47. &OBSYoutubeActions::OpenYouTubeDashboard);
  48. connect(ui->helpAutoStartStop, &QLabel::linkActivated, this,
  49. [](const QString &link) { QDesktopServices::openUrl(link); });
  50. connect(ui->help360Video, &QLabel::linkActivated, this,
  51. [](const QString &link) { QDesktopServices::openUrl(link); });
  52. connect(ui->helpMadeForKids, &QLabel::linkActivated, this,
  53. [](const QString &link) { QDesktopServices::openUrl(link); });
  54. ui->scheduledTime->setVisible(false);
  55. connect(ui->checkScheduledLater, &QCheckBox::stateChanged, this,
  56. [&](int state) {
  57. ui->scheduledTime->setVisible(state);
  58. if (state) {
  59. ui->checkAutoStart->setEnabled(true);
  60. ui->checkAutoStop->setEnabled(true);
  61. ui->checkAutoStart->setChecked(false);
  62. ui->checkAutoStop->setChecked(false);
  63. } else {
  64. ui->checkAutoStart->setEnabled(false);
  65. ui->checkAutoStop->setEnabled(false);
  66. ui->checkAutoStart->setChecked(true);
  67. ui->checkAutoStop->setChecked(true);
  68. }
  69. UpdateOkButtonStatus();
  70. });
  71. ui->scheduledTime->setDateTime(QDateTime::currentDateTime());
  72. if (!apiYouTube) {
  73. blog(LOG_DEBUG, "YouTube API auth NOT found.");
  74. Cancel();
  75. return;
  76. }
  77. ChannelDescription channel;
  78. if (!apiYouTube->GetChannelDescription(channel)) {
  79. blog(LOG_DEBUG, "Could not get channel description.");
  80. ShowErrorDialog(
  81. parent,
  82. apiYouTube->GetLastError().isEmpty()
  83. ? QTStr("YouTube.Actions.Error.General")
  84. : QTStr("YouTube.Actions.Error.Text")
  85. .arg(apiYouTube->GetLastError()));
  86. Cancel();
  87. return;
  88. }
  89. this->setWindowTitle(channel.title);
  90. QVector<CategoryDescription> category_list;
  91. if (!apiYouTube->GetVideoCategoriesList(
  92. channel.country, channel.language, category_list)) {
  93. blog(LOG_DEBUG, "Could not get video category for country; %s.",
  94. channel.country.toStdString().c_str());
  95. ShowErrorDialog(
  96. parent,
  97. apiYouTube->GetLastError().isEmpty()
  98. ? QTStr("YouTube.Actions.Error.General")
  99. : QTStr("YouTube.Actions.Error.Text")
  100. .arg(apiYouTube->GetLastError()));
  101. Cancel();
  102. return;
  103. }
  104. for (auto &category : category_list) {
  105. ui->categoryBox->addItem(category.title, category.id);
  106. if (category.id == IndexOfGamingCategory) {
  107. ui->categoryBox->setCurrentText(category.title);
  108. }
  109. }
  110. connect(ui->okButton, &QPushButton::clicked, this,
  111. &OBSYoutubeActions::InitBroadcast);
  112. connect(ui->cancelButton, &QPushButton::clicked, this, [&]() {
  113. blog(LOG_DEBUG, "YouTube live broadcast creation cancelled.");
  114. // Close the dialog.
  115. Cancel();
  116. });
  117. qDeleteAll(ui->scrollAreaWidgetContents->findChildren<QWidget *>(
  118. QString(), Qt::FindDirectChildrenOnly));
  119. connect(workerThread, &WorkerThread::failed, this, [&]() {
  120. auto last_error = apiYouTube->GetLastError();
  121. if (last_error.isEmpty())
  122. last_error = QTStr("YouTube.Actions.Error.YouTubeApi");
  123. if (!apiYouTube->GetTranslatedError(last_error))
  124. last_error = QTStr("YouTube.Actions.Error.Text")
  125. .arg(last_error);
  126. ShowErrorDialog(this, last_error);
  127. QDialog::reject();
  128. });
  129. connect(workerThread, &WorkerThread::new_item, this,
  130. [&](const QString &title, const QString &dateTimeString,
  131. const QString &broadcast, const QString &status,
  132. bool astart, bool astop) {
  133. ClickableLabel *label = new ClickableLabel();
  134. label->setStyleSheet(NormalStylesheet);
  135. label->setTextFormat(Qt::RichText);
  136. if (status == "live" || status == "testing") {
  137. // Resumable stream
  138. label->setText(
  139. QString("<big>%1</big><br/>%2")
  140. .arg(title,
  141. QTStr("YouTube.Actions.Stream.Resume")));
  142. } else if (dateTimeString.isEmpty()) {
  143. // The broadcast created by YouTube Studio has no start time.
  144. // Yes this does violate the restrictions set in YouTube's API
  145. // But why would YouTube care about consistency?
  146. label->setText(
  147. QString("<big>%1</big><br/>%2")
  148. .arg(title,
  149. QTStr("YouTube.Actions.Stream.YTStudio")));
  150. } else {
  151. label->setText(
  152. QString("<big>%1</big><br/>%2")
  153. .arg(title,
  154. QTStr("YouTube.Actions.Stream.ScheduledFor")
  155. .arg(dateTimeString)));
  156. }
  157. label->setAlignment(Qt::AlignHCenter);
  158. label->setMargin(4);
  159. connect(label, &ClickableLabel::clicked, this,
  160. [&, label, broadcast, astart, astop]() {
  161. for (QWidget *i :
  162. ui->scrollAreaWidgetContents->findChildren<
  163. QWidget *>(
  164. QString(),
  165. Qt::FindDirectChildrenOnly))
  166. i->setStyleSheet(
  167. NormalStylesheet);
  168. label->setStyleSheet(
  169. SelectedStylesheet);
  170. this->selectedBroadcast = broadcast;
  171. this->autostart = astart;
  172. this->autostop = astop;
  173. UpdateOkButtonStatus();
  174. });
  175. ui->scrollAreaWidgetContents->layout()->addWidget(
  176. label);
  177. });
  178. workerThread->start();
  179. #ifdef __APPLE__
  180. // MacOS theming issues
  181. this->resize(this->width() + 200, this->height() + 120);
  182. #endif
  183. valid = true;
  184. }
  185. OBSYoutubeActions::~OBSYoutubeActions()
  186. {
  187. workerThread->stop();
  188. workerThread->wait();
  189. delete workerThread;
  190. }
  191. void WorkerThread::run()
  192. {
  193. if (!pending)
  194. return;
  195. json11::Json broadcasts;
  196. for (QString broacastStatus : {"active", "upcoming"}) {
  197. if (!apiYouTube->GetBroadcastsList(broadcasts, "",
  198. broacastStatus)) {
  199. emit failed();
  200. return;
  201. }
  202. while (pending) {
  203. auto items = broadcasts["items"].array_items();
  204. for (auto item : items) {
  205. QString status = QString::fromStdString(
  206. item["status"]["lifeCycleStatus"]
  207. .string_value());
  208. if (status == "live" || status == "testing") {
  209. // Check that the attached liveStream is offline (reconnectable)
  210. QString stream_id = QString::fromStdString(
  211. item["contentDetails"]
  212. ["boundStreamId"]
  213. .string_value());
  214. json11::Json stream;
  215. if (!apiYouTube->FindStream(stream_id,
  216. stream))
  217. continue;
  218. if (stream["status"]["streamStatus"] ==
  219. "active")
  220. continue;
  221. }
  222. QString title = QString::fromStdString(
  223. item["snippet"]["title"].string_value());
  224. QString scheduledStartTime =
  225. QString::fromStdString(
  226. item["snippet"]
  227. ["scheduledStartTime"]
  228. .string_value());
  229. QString broadcast = QString::fromStdString(
  230. item["id"].string_value());
  231. // Treat already started streams as autostart for UI purposes
  232. bool astart =
  233. status == "live"
  234. ? true
  235. : item["contentDetails"]
  236. ["enableAutoStart"]
  237. .bool_value();
  238. bool astop =
  239. item["contentDetails"]["enableAutoStop"]
  240. .bool_value();
  241. QDateTime utcDTime = QDateTime::fromString(
  242. scheduledStartTime,
  243. SchedulDateAndTimeFormat);
  244. // DateTime parser means that input datetime is a local, so we need to move it
  245. QDateTime dateTime = utcDTime.addSecs(
  246. utcDTime.offsetFromUtc());
  247. QString dateTimeString = QLocale().toString(
  248. dateTime,
  249. QString("%1 %2").arg(
  250. QLocale().dateFormat(
  251. QLocale::LongFormat),
  252. QLocale().timeFormat(
  253. QLocale::ShortFormat)));
  254. emit new_item(title, dateTimeString, broadcast,
  255. status, astart, astop);
  256. }
  257. auto nextPageToken =
  258. broadcasts["nextPageToken"].string_value();
  259. if (nextPageToken.empty() || items.empty())
  260. break;
  261. else {
  262. if (!pending)
  263. return;
  264. if (!apiYouTube->GetBroadcastsList(
  265. broadcasts,
  266. QString::fromStdString(
  267. nextPageToken),
  268. broacastStatus)) {
  269. emit failed();
  270. return;
  271. }
  272. }
  273. }
  274. }
  275. emit ready();
  276. }
  277. void OBSYoutubeActions::UpdateOkButtonStatus()
  278. {
  279. if (ui->tabWidget->currentIndex() == 0) {
  280. ui->okButton->setEnabled(
  281. !ui->title->text().isEmpty() &&
  282. !ui->privacyBox->currentText().isEmpty() &&
  283. (ui->yesMakeForKids->isChecked() ||
  284. ui->notMakeForKids->isChecked()));
  285. if (ui->checkScheduledLater->checkState() == Qt::Checked) {
  286. ui->okButton->setText(
  287. QTStr("YouTube.Actions.Create_Save"));
  288. } else {
  289. ui->okButton->setText(
  290. QTStr("YouTube.Actions.Create_GoLive"));
  291. }
  292. ui->pushButton->setVisible(false);
  293. } else {
  294. ui->okButton->setEnabled(!selectedBroadcast.isEmpty());
  295. ui->okButton->setText(QTStr("YouTube.Actions.Choose_GoLive"));
  296. ui->pushButton->setVisible(true);
  297. }
  298. }
  299. bool OBSYoutubeActions::StreamNowAction(YoutubeApiWrappers *api,
  300. StreamDescription &stream)
  301. {
  302. YoutubeApiWrappers *apiYouTube = api;
  303. BroadcastDescription broadcast = {};
  304. UiToBroadcast(broadcast);
  305. // stream now is always autostart/autostop
  306. broadcast.auto_start = true;
  307. broadcast.auto_stop = true;
  308. blog(LOG_DEBUG, "Scheduled date and time: %s",
  309. broadcast.schedul_date_time.toStdString().c_str());
  310. if (!apiYouTube->InsertBroadcast(broadcast)) {
  311. blog(LOG_DEBUG, "No broadcast created.");
  312. return false;
  313. }
  314. stream = {"", "", "OBS Studio Video Stream", ""};
  315. if (!apiYouTube->InsertStream(stream)) {
  316. blog(LOG_DEBUG, "No stream created.");
  317. return false;
  318. }
  319. if (!apiYouTube->BindStream(broadcast.id, stream.id)) {
  320. blog(LOG_DEBUG, "No stream binded.");
  321. return false;
  322. }
  323. if (!apiYouTube->SetVideoCategory(broadcast.id, broadcast.title,
  324. broadcast.description,
  325. broadcast.category.id)) {
  326. blog(LOG_DEBUG, "No category set.");
  327. return false;
  328. }
  329. return true;
  330. }
  331. bool OBSYoutubeActions::StreamLaterAction(YoutubeApiWrappers *api)
  332. {
  333. YoutubeApiWrappers *apiYouTube = api;
  334. BroadcastDescription broadcast = {};
  335. UiToBroadcast(broadcast);
  336. // DateTime parser means that input datetime is a local, so we need to move it
  337. auto dateTime = ui->scheduledTime->dateTime();
  338. auto utcDTime = dateTime.addSecs(-dateTime.offsetFromUtc());
  339. broadcast.schedul_date_time =
  340. utcDTime.toString(SchedulDateAndTimeFormat);
  341. blog(LOG_DEBUG, "Scheduled date and time: %s",
  342. broadcast.schedul_date_time.toStdString().c_str());
  343. if (!apiYouTube->InsertBroadcast(broadcast)) {
  344. blog(LOG_DEBUG, "No broadcast created.");
  345. return false;
  346. }
  347. if (!apiYouTube->SetVideoCategory(broadcast.id, broadcast.title,
  348. broadcast.description,
  349. broadcast.category.id)) {
  350. blog(LOG_DEBUG, "No category set.");
  351. return false;
  352. }
  353. return true;
  354. }
  355. bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api,
  356. StreamDescription &stream)
  357. {
  358. YoutubeApiWrappers *apiYouTube = api;
  359. json11::Json json;
  360. if (!apiYouTube->FindBroadcast(selectedBroadcast, json)) {
  361. blog(LOG_DEBUG, "No broadcast found.");
  362. return false;
  363. }
  364. std::string boundStreamId =
  365. json["items"]
  366. .array_items()[0]["contentDetails"]["boundStreamId"]
  367. .string_value();
  368. stream.id = boundStreamId.c_str();
  369. if (!stream.id.isEmpty() && apiYouTube->FindStream(stream.id, json)) {
  370. auto item = json["items"].array_items()[0];
  371. auto streamName = item["cdn"]["ingestionInfo"]["streamName"]
  372. .string_value();
  373. auto title = item["snippet"]["title"].string_value();
  374. auto description =
  375. item["snippet"]["description"].string_value();
  376. stream.name = streamName.c_str();
  377. stream.title = title.c_str();
  378. stream.description = description.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. return true;
  392. }
  393. void OBSYoutubeActions::ShowErrorDialog(QWidget *parent, QString text)
  394. {
  395. QMessageBox dlg(parent);
  396. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  397. dlg.setWindowTitle(QTStr("YouTube.Actions.Error.Title"));
  398. dlg.setText(text);
  399. dlg.setTextFormat(Qt::RichText);
  400. dlg.setIcon(QMessageBox::Warning);
  401. dlg.setStandardButtons(QMessageBox::StandardButton::Ok);
  402. dlg.exec();
  403. }
  404. void OBSYoutubeActions::InitBroadcast()
  405. {
  406. StreamDescription stream;
  407. QMessageBox msgBox(this);
  408. msgBox.setWindowFlags(msgBox.windowFlags() &
  409. ~Qt::WindowCloseButtonHint);
  410. msgBox.setWindowTitle(QTStr("YouTube.Actions.Notify.Title"));
  411. msgBox.setText(QTStr("YouTube.Actions.Notify.CreatingBroadcast"));
  412. msgBox.setStandardButtons(QMessageBox::StandardButtons());
  413. bool success = false;
  414. auto action = [&]() {
  415. if (ui->tabWidget->currentIndex() == 0) {
  416. if (ui->checkScheduledLater->isChecked()) {
  417. success = this->StreamLaterAction(apiYouTube);
  418. } else {
  419. success = this->StreamNowAction(apiYouTube,
  420. stream);
  421. }
  422. } else {
  423. success = this->ChooseAnEventAction(apiYouTube, stream);
  424. };
  425. QMetaObject::invokeMethod(&msgBox, "accept",
  426. Qt::QueuedConnection);
  427. };
  428. QScopedPointer<QThread> thread(CreateQThread(action));
  429. thread->start();
  430. msgBox.exec();
  431. thread->wait();
  432. if (success) {
  433. if (ui->tabWidget->currentIndex() == 0) {
  434. // Stream later usecase.
  435. if (ui->checkScheduledLater->isChecked()) {
  436. QMessageBox msg(this);
  437. msg.setWindowTitle(QTStr(
  438. "YouTube.Actions.EventCreated.Title"));
  439. msg.setText(QTStr(
  440. "YouTube.Actions.EventCreated.Text"));
  441. msg.setStandardButtons(QMessageBox::Ok);
  442. msg.exec();
  443. // Close dialog without start streaming.
  444. Cancel();
  445. } else {
  446. // Stream now usecase.
  447. blog(LOG_DEBUG, "New valid stream: %s",
  448. QT_TO_UTF8(stream.name));
  449. emit ok(QT_TO_UTF8(stream.id),
  450. QT_TO_UTF8(stream.name), true, true);
  451. Accept();
  452. }
  453. } else {
  454. // Stream to precreated broadcast usecase.
  455. emit ok(QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name),
  456. autostart, autostop);
  457. Accept();
  458. }
  459. } else {
  460. // Fail.
  461. auto last_error = apiYouTube->GetLastError();
  462. if (last_error.isEmpty())
  463. last_error = QTStr("YouTube.Actions.Error.YouTubeApi");
  464. if (!apiYouTube->GetTranslatedError(last_error))
  465. last_error =
  466. QTStr("YouTube.Actions.Error.NoBroadcastCreated")
  467. .arg(last_error);
  468. ShowErrorDialog(this, last_error);
  469. }
  470. }
  471. void OBSYoutubeActions::UiToBroadcast(BroadcastDescription &broadcast)
  472. {
  473. broadcast.title = ui->title->text();
  474. broadcast.description = ui->description->text();
  475. broadcast.privacy = ui->privacyBox->currentData().toString();
  476. broadcast.category.title = ui->categoryBox->currentText();
  477. broadcast.category.id = ui->categoryBox->currentData().toString();
  478. broadcast.made_for_kids = ui->yesMakeForKids->isChecked();
  479. broadcast.latency = ui->latencyBox->currentData().toString();
  480. broadcast.auto_start = ui->checkAutoStart->isChecked();
  481. broadcast.auto_stop = ui->checkAutoStop->isChecked();
  482. broadcast.dvr = ui->checkDVR->isChecked();
  483. broadcast.schedul_for_later = ui->checkScheduledLater->isChecked();
  484. broadcast.projection = ui->check360Video->isChecked() ? "360"
  485. : "rectangular";
  486. // Current time by default.
  487. broadcast.schedul_date_time = QDateTime::currentDateTimeUtc().toString(
  488. SchedulDateAndTimeFormat);
  489. }
  490. void OBSYoutubeActions::OpenYouTubeDashboard()
  491. {
  492. ChannelDescription channel;
  493. if (!apiYouTube->GetChannelDescription(channel)) {
  494. blog(LOG_DEBUG, "Could not get channel description.");
  495. ShowErrorDialog(
  496. this,
  497. apiYouTube->GetLastError().isEmpty()
  498. ? QTStr("YouTube.Actions.Error.General")
  499. : QTStr("YouTube.Actions.Error.Text")
  500. .arg(apiYouTube->GetLastError()));
  501. return;
  502. }
  503. //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
  504. QString uri =
  505. QString("https://studio.youtube.com/channel/%1/videos/live?filter=[]&sort={\"columnType\"%3A\"date\"%2C\"sortOrder\"%3A\"DESCENDING\"}")
  506. .arg(channel.id);
  507. QDesktopServices::openUrl(uri);
  508. }
  509. void OBSYoutubeActions::Cancel()
  510. {
  511. workerThread->stop();
  512. reject();
  513. }
  514. void OBSYoutubeActions::Accept()
  515. {
  516. workerThread->stop();
  517. accept();
  518. }