window-youtube-actions.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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, bool astart, bool astop) {
  132. ClickableLabel *label = new ClickableLabel();
  133. label->setStyleSheet(NormalStylesheet);
  134. label->setTextFormat(Qt::RichText);
  135. label->setText(
  136. QString("<big>%1 %2</big><br/>%3 %4")
  137. .arg(title,
  138. QTStr("YouTube.Actions.Stream"),
  139. QTStr("YouTube.Actions.Stream.ScheduledFor")
  140. .arg(dateTimeString)));
  141. label->setAlignment(Qt::AlignHCenter);
  142. label->setMargin(4);
  143. connect(label, &ClickableLabel::clicked, this,
  144. [&, label, broadcast, astart, astop]() {
  145. for (QWidget *i :
  146. ui->scrollAreaWidgetContents->findChildren<
  147. QWidget *>(
  148. QString(),
  149. Qt::FindDirectChildrenOnly))
  150. i->setStyleSheet(
  151. NormalStylesheet);
  152. label->setStyleSheet(
  153. SelectedStylesheet);
  154. this->selectedBroadcast = broadcast;
  155. this->autostart = astart;
  156. this->autostop = astop;
  157. UpdateOkButtonStatus();
  158. });
  159. ui->scrollAreaWidgetContents->layout()->addWidget(
  160. label);
  161. });
  162. workerThread->start();
  163. #ifdef __APPLE__
  164. // MacOS theming issues
  165. this->resize(this->width() + 200, this->height() + 120);
  166. #endif
  167. valid = true;
  168. }
  169. OBSYoutubeActions::~OBSYoutubeActions()
  170. {
  171. workerThread->stop();
  172. workerThread->wait();
  173. delete workerThread;
  174. }
  175. void WorkerThread::run()
  176. {
  177. if (!pending)
  178. return;
  179. json11::Json broadcasts;
  180. if (!apiYouTube->GetBroadcastsList(broadcasts, "")) {
  181. emit failed();
  182. return;
  183. }
  184. while (pending) {
  185. auto items = broadcasts["items"].array_items();
  186. for (auto item = items.begin(); item != items.end(); item++) {
  187. auto status = (*item)["status"]["lifeCycleStatus"]
  188. .string_value();
  189. if (status == "created" || status == "ready") {
  190. auto title = QString::fromStdString(
  191. (*item)["snippet"]["title"]
  192. .string_value());
  193. auto scheduledStartTime = QString::fromStdString(
  194. (*item)["snippet"]["scheduledStartTime"]
  195. .string_value());
  196. auto broadcast = QString::fromStdString(
  197. (*item)["id"].string_value());
  198. auto astart = (*item)["contentDetails"]
  199. ["enableAutoStart"]
  200. .bool_value();
  201. auto astop = (*item)["contentDetails"]
  202. ["enableAutoStop"]
  203. .bool_value();
  204. auto utcDTime = QDateTime::fromString(
  205. scheduledStartTime,
  206. SchedulDateAndTimeFormat);
  207. // DateTime parser means that input datetime is a local, so we need to move it
  208. auto dateTime = utcDTime.addSecs(
  209. utcDTime.offsetFromUtc());
  210. auto dateTimeString = QLocale().toString(
  211. dateTime,
  212. QString("%1 %2").arg(
  213. QLocale().dateFormat(
  214. QLocale::LongFormat),
  215. QLocale().timeFormat(
  216. QLocale::ShortFormat)));
  217. emit new_item(title, dateTimeString, broadcast,
  218. astart, astop);
  219. }
  220. }
  221. auto nextPageToken = broadcasts["nextPageToken"].string_value();
  222. if (nextPageToken.empty() || items.empty())
  223. break;
  224. else {
  225. if (!pending)
  226. return;
  227. if (!apiYouTube->GetBroadcastsList(
  228. broadcasts,
  229. QString::fromStdString(nextPageToken))) {
  230. emit failed();
  231. return;
  232. }
  233. }
  234. }
  235. emit ready();
  236. }
  237. void OBSYoutubeActions::UpdateOkButtonStatus()
  238. {
  239. if (ui->tabWidget->currentIndex() == 0) {
  240. ui->okButton->setEnabled(
  241. !ui->title->text().isEmpty() &&
  242. !ui->privacyBox->currentText().isEmpty() &&
  243. (ui->yesMakeForKids->isChecked() ||
  244. ui->notMakeForKids->isChecked()));
  245. if (ui->checkScheduledLater->checkState() == Qt::Checked) {
  246. ui->okButton->setText(
  247. QTStr("YouTube.Actions.Create_Save"));
  248. } else {
  249. ui->okButton->setText(
  250. QTStr("YouTube.Actions.Create_GoLive"));
  251. }
  252. ui->pushButton->setVisible(false);
  253. } else {
  254. ui->okButton->setEnabled(!selectedBroadcast.isEmpty());
  255. ui->okButton->setText(QTStr("YouTube.Actions.Choose_GoLive"));
  256. ui->pushButton->setVisible(true);
  257. }
  258. }
  259. bool OBSYoutubeActions::StreamNowAction(YoutubeApiWrappers *api,
  260. StreamDescription &stream)
  261. {
  262. YoutubeApiWrappers *apiYouTube = api;
  263. BroadcastDescription broadcast = {};
  264. UiToBroadcast(broadcast);
  265. // stream now is always autostart/autostop
  266. broadcast.auto_start = true;
  267. broadcast.auto_stop = true;
  268. blog(LOG_DEBUG, "Scheduled date and time: %s",
  269. broadcast.schedul_date_time.toStdString().c_str());
  270. if (!apiYouTube->InsertBroadcast(broadcast)) {
  271. blog(LOG_DEBUG, "No broadcast created.");
  272. return false;
  273. }
  274. stream = {"", "", "OBS Studio Video Stream", ""};
  275. if (!apiYouTube->InsertStream(stream)) {
  276. blog(LOG_DEBUG, "No stream created.");
  277. return false;
  278. }
  279. if (!apiYouTube->BindStream(broadcast.id, stream.id)) {
  280. blog(LOG_DEBUG, "No stream binded.");
  281. return false;
  282. }
  283. if (!apiYouTube->SetVideoCategory(broadcast.id, broadcast.title,
  284. broadcast.description,
  285. broadcast.category.id)) {
  286. blog(LOG_DEBUG, "No category set.");
  287. return false;
  288. }
  289. return true;
  290. }
  291. bool OBSYoutubeActions::StreamLaterAction(YoutubeApiWrappers *api)
  292. {
  293. YoutubeApiWrappers *apiYouTube = api;
  294. BroadcastDescription broadcast = {};
  295. UiToBroadcast(broadcast);
  296. // DateTime parser means that input datetime is a local, so we need to move it
  297. auto dateTime = ui->scheduledTime->dateTime();
  298. auto utcDTime = dateTime.addSecs(-dateTime.offsetFromUtc());
  299. broadcast.schedul_date_time =
  300. utcDTime.toString(SchedulDateAndTimeFormat);
  301. blog(LOG_DEBUG, "Scheduled date and time: %s",
  302. broadcast.schedul_date_time.toStdString().c_str());
  303. if (!apiYouTube->InsertBroadcast(broadcast)) {
  304. blog(LOG_DEBUG, "No broadcast created.");
  305. return false;
  306. }
  307. return true;
  308. }
  309. bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api,
  310. StreamDescription &stream,
  311. bool start)
  312. {
  313. YoutubeApiWrappers *apiYouTube = api;
  314. std::string boundStreamId;
  315. {
  316. json11::Json json;
  317. if (!apiYouTube->FindBroadcast(selectedBroadcast, json)) {
  318. blog(LOG_DEBUG, "No broadcast found.");
  319. return false;
  320. }
  321. auto item = json["items"].array_items()[0];
  322. auto boundStreamId =
  323. item["contentDetails"]["boundStreamId"].string_value();
  324. }
  325. stream.id = boundStreamId.c_str();
  326. json11::Json json;
  327. if (!stream.id.isEmpty() && apiYouTube->FindStream(stream.id, json)) {
  328. auto item = json["items"].array_items()[0];
  329. auto streamName = item["cdn"]["streamName"].string_value();
  330. auto title = item["snippet"]["title"].string_value();
  331. auto description =
  332. item["snippet"]["description"].string_value();
  333. stream.name = streamName.c_str();
  334. stream.title = title.c_str();
  335. stream.description = description.c_str();
  336. } else {
  337. stream = {"", "", "OBS Studio Video Stream", ""};
  338. if (!apiYouTube->InsertStream(stream)) {
  339. blog(LOG_DEBUG, "No stream created.");
  340. return false;
  341. }
  342. if (!apiYouTube->BindStream(selectedBroadcast, stream.id)) {
  343. blog(LOG_DEBUG, "No stream binded.");
  344. return false;
  345. }
  346. }
  347. return true;
  348. }
  349. void OBSYoutubeActions::ShowErrorDialog(QWidget *parent, QString text)
  350. {
  351. QMessageBox dlg(parent);
  352. dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint);
  353. dlg.setWindowTitle(QTStr("YouTube.Actions.Error.Title"));
  354. dlg.setText(text);
  355. dlg.setTextFormat(Qt::RichText);
  356. dlg.setIcon(QMessageBox::Warning);
  357. dlg.setStandardButtons(QMessageBox::StandardButton::Ok);
  358. dlg.exec();
  359. }
  360. void OBSYoutubeActions::InitBroadcast()
  361. {
  362. StreamDescription stream;
  363. QMessageBox msgBox(this);
  364. msgBox.setWindowFlags(msgBox.windowFlags() &
  365. ~Qt::WindowCloseButtonHint);
  366. msgBox.setWindowTitle(QTStr("YouTube.Actions.Notify.Title"));
  367. msgBox.setText(QTStr("YouTube.Actions.Notify.CreatingBroadcast"));
  368. msgBox.setStandardButtons(QMessageBox::StandardButtons());
  369. bool success = false;
  370. auto action = [&]() {
  371. if (ui->tabWidget->currentIndex() == 0) {
  372. if (ui->checkScheduledLater->isChecked()) {
  373. success = this->StreamLaterAction(apiYouTube);
  374. } else {
  375. success = this->StreamNowAction(apiYouTube,
  376. stream);
  377. }
  378. } else {
  379. success = this->ChooseAnEventAction(apiYouTube, stream,
  380. this->autostart);
  381. };
  382. QMetaObject::invokeMethod(&msgBox, "accept",
  383. Qt::QueuedConnection);
  384. };
  385. QScopedPointer<QThread> thread(CreateQThread(action));
  386. thread->start();
  387. msgBox.exec();
  388. thread->wait();
  389. if (success) {
  390. if (ui->tabWidget->currentIndex() == 0) {
  391. // Stream later usecase.
  392. if (ui->checkScheduledLater->isChecked()) {
  393. QMessageBox msg(this);
  394. msg.setWindowTitle(QTStr(
  395. "YouTube.Actions.EventCreated.Title"));
  396. msg.setText(QTStr(
  397. "YouTube.Actions.EventCreated.Text"));
  398. msg.setStandardButtons(QMessageBox::Ok);
  399. msg.exec();
  400. // Close dialog without start streaming.
  401. Cancel();
  402. } else {
  403. // Stream now usecase.
  404. blog(LOG_DEBUG, "New valid stream: %s",
  405. QT_TO_UTF8(stream.name));
  406. emit ok(QT_TO_UTF8(stream.id),
  407. QT_TO_UTF8(stream.name), true, true);
  408. Accept();
  409. }
  410. } else {
  411. // Stream to precreated broadcast usecase.
  412. emit ok(QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name),
  413. autostart, autostop);
  414. Accept();
  415. }
  416. } else {
  417. // Fail.
  418. auto last_error = apiYouTube->GetLastError();
  419. if (last_error.isEmpty())
  420. last_error = QTStr("YouTube.Actions.Error.YouTubeApi");
  421. if (!apiYouTube->GetTranslatedError(last_error))
  422. last_error =
  423. QTStr("YouTube.Actions.Error.NoBroadcastCreated")
  424. .arg(last_error);
  425. ShowErrorDialog(this, last_error);
  426. }
  427. }
  428. void OBSYoutubeActions::UiToBroadcast(BroadcastDescription &broadcast)
  429. {
  430. broadcast.title = ui->title->text();
  431. broadcast.description = ui->description->text();
  432. broadcast.privacy = ui->privacyBox->currentData().toString();
  433. broadcast.category.title = ui->categoryBox->currentText();
  434. broadcast.category.id = ui->categoryBox->currentData().toString();
  435. broadcast.made_for_kids = ui->yesMakeForKids->isChecked();
  436. broadcast.latency = ui->latencyBox->currentData().toString();
  437. broadcast.auto_start = ui->checkAutoStart->isChecked();
  438. broadcast.auto_stop = ui->checkAutoStop->isChecked();
  439. broadcast.dvr = ui->checkDVR->isChecked();
  440. broadcast.schedul_for_later = ui->checkScheduledLater->isChecked();
  441. broadcast.projection = ui->check360Video->isChecked() ? "360"
  442. : "rectangular";
  443. // Current time by default.
  444. broadcast.schedul_date_time = QDateTime::currentDateTimeUtc().toString(
  445. SchedulDateAndTimeFormat);
  446. }
  447. void OBSYoutubeActions::OpenYouTubeDashboard()
  448. {
  449. ChannelDescription channel;
  450. if (!apiYouTube->GetChannelDescription(channel)) {
  451. blog(LOG_DEBUG, "Could not get channel description.");
  452. ShowErrorDialog(
  453. this,
  454. apiYouTube->GetLastError().isEmpty()
  455. ? QTStr("YouTube.Actions.Error.General")
  456. : QTStr("YouTube.Actions.Error.Text")
  457. .arg(apiYouTube->GetLastError()));
  458. return;
  459. }
  460. //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
  461. QString uri =
  462. QString("https://studio.youtube.com/channel/%1/videos/live?filter=[]&sort={\"columnType\"%3A\"date\"%2C\"sortOrder\"%3A\"DESCENDING\"}")
  463. .arg(channel.id);
  464. QDesktopServices::openUrl(uri);
  465. }
  466. void OBSYoutubeActions::Cancel()
  467. {
  468. workerThread->stop();
  469. reject();
  470. }
  471. void OBSYoutubeActions::Accept()
  472. {
  473. workerThread->stop();
  474. accept();
  475. }