window-youtube-actions.cpp 16 KB

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