youtube-api-wrappers.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. #include "youtube-api-wrappers.hpp"
  2. #include <QUrl>
  3. #include <QMimeDatabase>
  4. #include <QFile>
  5. #include <string>
  6. #include <iostream>
  7. #include "auth-youtube.hpp"
  8. #include "obs-app.hpp"
  9. #include "qt-wrappers.hpp"
  10. #include "remote-text.hpp"
  11. #include "ui-config.h"
  12. #include "obf.h"
  13. using namespace json11;
  14. /* ------------------------------------------------------------------------- */
  15. #define YOUTUBE_LIVE_API_URL "https://www.googleapis.com/youtube/v3"
  16. #define YOUTUBE_LIVE_STREAM_URL YOUTUBE_LIVE_API_URL "/liveStreams"
  17. #define YOUTUBE_LIVE_BROADCAST_URL YOUTUBE_LIVE_API_URL "/liveBroadcasts"
  18. #define YOUTUBE_LIVE_BROADCAST_TRANSITION_URL \
  19. YOUTUBE_LIVE_BROADCAST_URL "/transition"
  20. #define YOUTUBE_LIVE_BROADCAST_BIND_URL YOUTUBE_LIVE_BROADCAST_URL "/bind"
  21. #define YOUTUBE_LIVE_CHANNEL_URL YOUTUBE_LIVE_API_URL "/channels"
  22. #define YOUTUBE_LIVE_TOKEN_URL "https://oauth2.googleapis.com/token"
  23. #define YOUTUBE_LIVE_VIDEOCATEGORIES_URL YOUTUBE_LIVE_API_URL "/videoCategories"
  24. #define YOUTUBE_LIVE_VIDEOS_URL YOUTUBE_LIVE_API_URL "/videos"
  25. #define YOUTUBE_LIVE_THUMBNAIL_URL \
  26. "https://www.googleapis.com/upload/youtube/v3/thumbnails/set"
  27. #define DEFAULT_BROADCASTS_PER_QUERY \
  28. "50" // acceptable values are 0 to 50, inclusive
  29. /* ------------------------------------------------------------------------- */
  30. bool IsYouTubeService(const std::string &service)
  31. {
  32. auto it = find_if(youtubeServices.begin(), youtubeServices.end(),
  33. [&service](const Auth::Def &yt) {
  34. return service == yt.service;
  35. });
  36. return it != youtubeServices.end();
  37. }
  38. bool YoutubeApiWrappers::GetTranslatedError(QString &error_message)
  39. {
  40. QString translated =
  41. QTStr("YouTube.Errors." + lastErrorReason.toUtf8());
  42. // No translation found
  43. if (translated.startsWith("YouTube.Errors."))
  44. return false;
  45. error_message = translated;
  46. return true;
  47. }
  48. YoutubeApiWrappers::YoutubeApiWrappers(const Def &d) : YoutubeAuth(d) {}
  49. bool YoutubeApiWrappers::TryInsertCommand(const char *url,
  50. const char *content_type,
  51. std::string request_type,
  52. const char *data, Json &json_out,
  53. long *error_code, int data_size)
  54. {
  55. long httpStatusCode = 0;
  56. #ifdef _DEBUG
  57. blog(LOG_DEBUG, "YouTube API command URL: %s", url);
  58. if (data && data[0] == '{') // only log JSON data
  59. blog(LOG_DEBUG, "YouTube API command data: %s", data);
  60. #endif
  61. if (token.empty())
  62. return false;
  63. std::string output;
  64. std::string error;
  65. // Increase timeout by the time it takes to transfer `data_size` at 1 Mbps
  66. int timeout = 5 + data_size / 125000;
  67. bool success = GetRemoteFile(url, output, error, &httpStatusCode,
  68. content_type, request_type, data,
  69. {"Authorization: Bearer " + token},
  70. nullptr, timeout, false, data_size);
  71. if (error_code)
  72. *error_code = httpStatusCode;
  73. if (!success || output.empty())
  74. return false;
  75. json_out = Json::parse(output, error);
  76. #ifdef _DEBUG
  77. blog(LOG_DEBUG, "YouTube API command answer: %s",
  78. json_out.dump().c_str());
  79. #endif
  80. if (!error.empty()) {
  81. return false;
  82. }
  83. return httpStatusCode < 400;
  84. }
  85. bool YoutubeApiWrappers::UpdateAccessToken()
  86. {
  87. if (refresh_token.empty()) {
  88. return false;
  89. }
  90. std::string clientid = YOUTUBE_CLIENTID;
  91. std::string secret = YOUTUBE_SECRET;
  92. deobfuscate_str(&clientid[0], YOUTUBE_CLIENTID_HASH);
  93. deobfuscate_str(&secret[0], YOUTUBE_SECRET_HASH);
  94. std::string r_token =
  95. QUrl::toPercentEncoding(refresh_token.c_str()).toStdString();
  96. const QString url = YOUTUBE_LIVE_TOKEN_URL;
  97. const QString data_template = "client_id=%1"
  98. "&client_secret=%2"
  99. "&refresh_token=%3"
  100. "&grant_type=refresh_token";
  101. const QString data = data_template.arg(QString(clientid.c_str()),
  102. QString(secret.c_str()),
  103. QString(r_token.c_str()));
  104. Json json_out;
  105. bool success = TryInsertCommand(QT_TO_UTF8(url),
  106. "application/x-www-form-urlencoded", "",
  107. QT_TO_UTF8(data), json_out);
  108. if (!success || json_out.object_items().find("error") !=
  109. json_out.object_items().end())
  110. return false;
  111. token = json_out["access_token"].string_value();
  112. return token.empty() ? false : true;
  113. }
  114. bool YoutubeApiWrappers::InsertCommand(const char *url,
  115. const char *content_type,
  116. std::string request_type,
  117. const char *data, Json &json_out,
  118. int data_size)
  119. {
  120. long error_code;
  121. bool success = TryInsertCommand(url, content_type, request_type, data,
  122. json_out, &error_code, data_size);
  123. if (error_code == 401) {
  124. // Attempt to update access token and try again
  125. if (!UpdateAccessToken())
  126. return false;
  127. success = TryInsertCommand(url, content_type, request_type,
  128. data, json_out, &error_code,
  129. data_size);
  130. }
  131. if (json_out.object_items().find("error") !=
  132. json_out.object_items().end()) {
  133. blog(LOG_ERROR,
  134. "YouTube API error:\n\tHTTP status: %ld\n\tURL: %s\n\tJSON: %s",
  135. error_code, url, json_out.dump().c_str());
  136. lastError = json_out["error"]["code"].int_value();
  137. lastErrorReason =
  138. QString(json_out["error"]["errors"][0]["reason"]
  139. .string_value()
  140. .c_str());
  141. lastErrorMessage = QString(
  142. json_out["error"]["message"].string_value().c_str());
  143. // The existence of an error implies non-success even if the HTTP status code disagrees.
  144. success = false;
  145. }
  146. return success;
  147. }
  148. bool YoutubeApiWrappers::GetChannelDescription(
  149. ChannelDescription &channel_description)
  150. {
  151. lastErrorMessage.clear();
  152. lastErrorReason.clear();
  153. const QByteArray url = YOUTUBE_LIVE_CHANNEL_URL
  154. "?part=snippet,contentDetails,statistics"
  155. "&mine=true";
  156. Json json_out;
  157. if (!InsertCommand(url, "application/json", "", nullptr, json_out)) {
  158. return false;
  159. }
  160. if (json_out["pageInfo"]["totalResults"].int_value() == 0) {
  161. lastErrorMessage = QTStr("YouTube.Auth.NoChannels");
  162. return false;
  163. }
  164. channel_description.id =
  165. QString(json_out["items"][0]["id"].string_value().c_str());
  166. channel_description.title = QString(
  167. json_out["items"][0]["snippet"]["title"].string_value().c_str());
  168. return channel_description.id.isEmpty() ? false : true;
  169. }
  170. bool YoutubeApiWrappers::InsertBroadcast(BroadcastDescription &broadcast)
  171. {
  172. lastErrorMessage.clear();
  173. lastErrorReason.clear();
  174. const QByteArray url = YOUTUBE_LIVE_BROADCAST_URL
  175. "?part=snippet,status,contentDetails";
  176. const Json data = Json::object{
  177. {"snippet",
  178. Json::object{
  179. {"title", QT_TO_UTF8(broadcast.title)},
  180. {"description", QT_TO_UTF8(broadcast.description)},
  181. {"scheduledStartTime",
  182. QT_TO_UTF8(broadcast.schedul_date_time)},
  183. }},
  184. {"status",
  185. Json::object{
  186. {"privacyStatus", QT_TO_UTF8(broadcast.privacy)},
  187. {"selfDeclaredMadeForKids", broadcast.made_for_kids},
  188. }},
  189. {"contentDetails",
  190. Json::object{
  191. {"latencyPreference", QT_TO_UTF8(broadcast.latency)},
  192. {"enableAutoStart", broadcast.auto_start},
  193. {"enableAutoStop", broadcast.auto_stop},
  194. {"enableDvr", broadcast.dvr},
  195. {"projection", QT_TO_UTF8(broadcast.projection)},
  196. {
  197. "monitorStream",
  198. Json::object{
  199. {"enableMonitorStream", false},
  200. },
  201. },
  202. }},
  203. };
  204. Json json_out;
  205. if (!InsertCommand(url, "application/json", "", data.dump().c_str(),
  206. json_out)) {
  207. return false;
  208. }
  209. broadcast.id = QString(json_out["id"].string_value().c_str());
  210. return broadcast.id.isEmpty() ? false : true;
  211. }
  212. bool YoutubeApiWrappers::InsertStream(StreamDescription &stream)
  213. {
  214. lastErrorMessage.clear();
  215. lastErrorReason.clear();
  216. const QByteArray url = YOUTUBE_LIVE_STREAM_URL
  217. "?part=snippet,cdn,status,contentDetails";
  218. const Json data = Json::object{
  219. {"snippet",
  220. Json::object{
  221. {"title", QT_TO_UTF8(stream.title)},
  222. }},
  223. {"cdn",
  224. Json::object{
  225. {"frameRate", "variable"},
  226. {"ingestionType", "rtmp"},
  227. {"resolution", "variable"},
  228. }},
  229. {"contentDetails", Json::object{{"isReusable", false}}},
  230. };
  231. Json json_out;
  232. if (!InsertCommand(url, "application/json", "", data.dump().c_str(),
  233. json_out)) {
  234. return false;
  235. }
  236. stream.id = QString(json_out["id"].string_value().c_str());
  237. stream.name = QString(json_out["cdn"]["ingestionInfo"]["streamName"]
  238. .string_value()
  239. .c_str());
  240. return stream.id.isEmpty() ? false : true;
  241. }
  242. bool YoutubeApiWrappers::BindStream(const QString broadcast_id,
  243. const QString stream_id)
  244. {
  245. lastErrorMessage.clear();
  246. lastErrorReason.clear();
  247. const QString url_template = YOUTUBE_LIVE_BROADCAST_BIND_URL
  248. "?id=%1"
  249. "&streamId=%2"
  250. "&part=id,snippet,contentDetails,status";
  251. const QString url = url_template.arg(broadcast_id, stream_id);
  252. const Json data = Json::object{};
  253. this->broadcast_id = broadcast_id;
  254. Json json_out;
  255. return InsertCommand(QT_TO_UTF8(url), "application/json", "",
  256. data.dump().c_str(), json_out);
  257. }
  258. bool YoutubeApiWrappers::GetBroadcastsList(Json &json_out, const QString &page,
  259. const QString &status)
  260. {
  261. lastErrorMessage.clear();
  262. lastErrorReason.clear();
  263. QByteArray url = YOUTUBE_LIVE_BROADCAST_URL
  264. "?part=snippet,contentDetails,status"
  265. "&broadcastType=all&maxResults=" DEFAULT_BROADCASTS_PER_QUERY;
  266. if (status.isEmpty())
  267. url += "&mine=true";
  268. else
  269. url += "&broadcastStatus=" + status.toUtf8();
  270. if (!page.isEmpty())
  271. url += "&pageToken=" + page.toUtf8();
  272. return InsertCommand(url, "application/json", "", nullptr, json_out);
  273. }
  274. bool YoutubeApiWrappers::GetVideoCategoriesList(
  275. QVector<CategoryDescription> &category_list_out)
  276. {
  277. lastErrorMessage.clear();
  278. lastErrorReason.clear();
  279. const QString url_template = YOUTUBE_LIVE_VIDEOCATEGORIES_URL
  280. "?part=snippet"
  281. "&regionCode=%1"
  282. "&hl=%2";
  283. /*
  284. * All OBS locale regions aside from "US" are missing category id 29
  285. * ("Nonprofits & Activism"), but it is still available to channels
  286. * set to those regions via the YouTube Studio website.
  287. * To work around this inconsistency with the API all locales will
  288. * use the "US" region and only set the language part for localisation.
  289. * It is worth noting that none of the regions available on YouTube
  290. * feature any category not also available to the "US" region.
  291. */
  292. QString url = url_template.arg("US", QLocale().name());
  293. Json json_out;
  294. if (!InsertCommand(QT_TO_UTF8(url), "application/json", "", nullptr,
  295. json_out)) {
  296. if (lastErrorReason != "unsupportedLanguageCode" &&
  297. lastErrorReason != "invalidLanguage")
  298. return false;
  299. // Try again with en-US if YouTube error indicates an unsupported locale
  300. url = url_template.arg("US", "en_US");
  301. if (!InsertCommand(QT_TO_UTF8(url), "application/json", "",
  302. nullptr, json_out))
  303. return false;
  304. }
  305. category_list_out = {};
  306. for (auto &j : json_out["items"].array_items()) {
  307. // Assignable only.
  308. if (j["snippet"]["assignable"].bool_value()) {
  309. category_list_out.push_back(
  310. {j["id"].string_value().c_str(),
  311. j["snippet"]["title"].string_value().c_str()});
  312. }
  313. }
  314. return category_list_out.isEmpty() ? false : true;
  315. }
  316. bool YoutubeApiWrappers::SetVideoCategory(const QString &video_id,
  317. const QString &video_title,
  318. const QString &video_description,
  319. const QString &categorie_id)
  320. {
  321. lastErrorMessage.clear();
  322. lastErrorReason.clear();
  323. const QByteArray url = YOUTUBE_LIVE_VIDEOS_URL "?part=snippet";
  324. const Json data = Json::object{
  325. {"id", QT_TO_UTF8(video_id)},
  326. {"snippet",
  327. Json::object{
  328. {"title", QT_TO_UTF8(video_title)},
  329. {"description", QT_TO_UTF8(video_description)},
  330. {"categoryId", QT_TO_UTF8(categorie_id)},
  331. }},
  332. };
  333. Json json_out;
  334. return InsertCommand(url, "application/json", "PUT",
  335. data.dump().c_str(), json_out);
  336. }
  337. bool YoutubeApiWrappers::SetVideoThumbnail(const QString &video_id,
  338. const QString &thumbnail_file)
  339. {
  340. lastErrorMessage.clear();
  341. lastErrorReason.clear();
  342. // Make sure the file hasn't been deleted since originally selecting it
  343. if (!QFile::exists(thumbnail_file)) {
  344. lastErrorMessage = QTStr("YouTube.Actions.Error.FileMissing");
  345. return false;
  346. }
  347. QFile thumbFile(thumbnail_file);
  348. if (!thumbFile.open(QFile::ReadOnly)) {
  349. lastErrorMessage =
  350. QTStr("YouTube.Actions.Error.FileOpeningFailed");
  351. return false;
  352. }
  353. const QByteArray fileContents = thumbFile.readAll();
  354. const QString mime =
  355. QMimeDatabase().mimeTypeForData(fileContents).name();
  356. const QString url = YOUTUBE_LIVE_THUMBNAIL_URL "?videoId=" + video_id;
  357. Json json_out;
  358. return InsertCommand(QT_TO_UTF8(url), QT_TO_UTF8(mime), "POST",
  359. fileContents.constData(), json_out,
  360. fileContents.size());
  361. }
  362. bool YoutubeApiWrappers::StartBroadcast(const QString &broadcast_id)
  363. {
  364. lastErrorMessage.clear();
  365. lastErrorReason.clear();
  366. Json json_out;
  367. if (!FindBroadcast(broadcast_id, json_out))
  368. return false;
  369. auto lifeCycleStatus =
  370. json_out["items"][0]["status"]["lifeCycleStatus"].string_value();
  371. if (lifeCycleStatus == "live" || lifeCycleStatus == "liveStarting")
  372. // Broadcast is already (going to be) live
  373. return true;
  374. else if (lifeCycleStatus == "testStarting") {
  375. // User will need to wait a few seconds before attempting to start broadcast
  376. lastErrorMessage =
  377. QTStr("YouTube.Actions.Error.BroadcastTestStarting");
  378. lastErrorReason.clear();
  379. return false;
  380. }
  381. // Only reset if broadcast has monitoring enabled and is not already in "testing" mode
  382. auto monitorStreamEnabled =
  383. json_out["items"][0]["contentDetails"]["monitorStream"]
  384. ["enableMonitorStream"]
  385. .bool_value();
  386. if (lifeCycleStatus != "testing" && monitorStreamEnabled &&
  387. !ResetBroadcast(broadcast_id, json_out))
  388. return false;
  389. const QString url_template = YOUTUBE_LIVE_BROADCAST_TRANSITION_URL
  390. "?id=%1"
  391. "&broadcastStatus=%2"
  392. "&part=status";
  393. const QString live = url_template.arg(broadcast_id, "live");
  394. bool success = InsertCommand(QT_TO_UTF8(live), "application/json",
  395. "POST", "{}", json_out);
  396. // Return a success if the command failed, but was redundant (broadcast already live)
  397. return success || lastErrorReason == "redundantTransition";
  398. }
  399. bool YoutubeApiWrappers::StartLatestBroadcast()
  400. {
  401. return StartBroadcast(this->broadcast_id);
  402. }
  403. bool YoutubeApiWrappers::StopBroadcast(const QString &broadcast_id)
  404. {
  405. lastErrorMessage.clear();
  406. lastErrorReason.clear();
  407. const QString url_template = YOUTUBE_LIVE_BROADCAST_TRANSITION_URL
  408. "?id=%1"
  409. "&broadcastStatus=complete"
  410. "&part=status";
  411. const QString url = url_template.arg(broadcast_id);
  412. Json json_out;
  413. bool success = InsertCommand(QT_TO_UTF8(url), "application/json",
  414. "POST", "{}", json_out);
  415. // Return a success if the command failed, but was redundant (broadcast already stopped)
  416. return success || lastErrorReason == "redundantTransition";
  417. }
  418. bool YoutubeApiWrappers::StopLatestBroadcast()
  419. {
  420. return StopBroadcast(this->broadcast_id);
  421. }
  422. void YoutubeApiWrappers::SetBroadcastId(QString &broadcast_id)
  423. {
  424. this->broadcast_id = broadcast_id;
  425. }
  426. QString YoutubeApiWrappers::GetBroadcastId()
  427. {
  428. return this->broadcast_id;
  429. }
  430. bool YoutubeApiWrappers::ResetBroadcast(const QString &broadcast_id,
  431. json11::Json &json_out)
  432. {
  433. lastErrorMessage.clear();
  434. lastErrorReason.clear();
  435. auto snippet = json_out["items"][0]["snippet"];
  436. auto status = json_out["items"][0]["status"];
  437. auto contentDetails = json_out["items"][0]["contentDetails"];
  438. auto monitorStream = contentDetails["monitorStream"];
  439. const Json data = Json::object{
  440. {"id", QT_TO_UTF8(broadcast_id)},
  441. {"snippet",
  442. Json::object{
  443. {"title", snippet["title"]},
  444. {"description", snippet["description"]},
  445. {"scheduledStartTime", snippet["scheduledStartTime"]},
  446. {"scheduledEndTime", snippet["scheduledEndTime"]},
  447. }},
  448. {"status",
  449. Json::object{
  450. {"privacyStatus", status["privacyStatus"]},
  451. {"madeForKids", status["madeForKids"]},
  452. {"selfDeclaredMadeForKids",
  453. status["selfDeclaredMadeForKids"]},
  454. }},
  455. {"contentDetails",
  456. Json::object{
  457. {
  458. "monitorStream",
  459. Json::object{
  460. {"enableMonitorStream", false},
  461. {"broadcastStreamDelayMs",
  462. monitorStream["broadcastStreamDelayMs"]},
  463. },
  464. },
  465. {"enableAutoStart", contentDetails["enableAutoStart"]},
  466. {"enableAutoStop", contentDetails["enableAutoStop"]},
  467. {"enableClosedCaptions",
  468. contentDetails["enableClosedCaptions"]},
  469. {"enableDvr", contentDetails["enableDvr"]},
  470. {"enableContentEncryption",
  471. contentDetails["enableContentEncryption"]},
  472. {"enableEmbed", contentDetails["enableEmbed"]},
  473. {"recordFromStart", contentDetails["recordFromStart"]},
  474. {"startWithSlate", contentDetails["startWithSlate"]},
  475. }},
  476. };
  477. const QString put = YOUTUBE_LIVE_BROADCAST_URL
  478. "?part=id,snippet,contentDetails,status";
  479. return InsertCommand(QT_TO_UTF8(put), "application/json", "PUT",
  480. data.dump().c_str(), json_out);
  481. }
  482. bool YoutubeApiWrappers::FindBroadcast(const QString &id,
  483. json11::Json &json_out)
  484. {
  485. lastErrorMessage.clear();
  486. lastErrorReason.clear();
  487. QByteArray url = YOUTUBE_LIVE_BROADCAST_URL
  488. "?part=id,snippet,contentDetails,status"
  489. "&broadcastType=all&maxResults=1";
  490. url += "&id=" + id.toUtf8();
  491. if (!InsertCommand(url, "application/json", "", nullptr, json_out))
  492. return false;
  493. auto items = json_out["items"].array_items();
  494. if (items.size() != 1) {
  495. lastErrorMessage =
  496. QTStr("YouTube.Actions.Error.BroadcastNotFound");
  497. return false;
  498. }
  499. return true;
  500. }
  501. bool YoutubeApiWrappers::FindStream(const QString &id, json11::Json &json_out)
  502. {
  503. lastErrorMessage.clear();
  504. lastErrorReason.clear();
  505. QByteArray url = YOUTUBE_LIVE_STREAM_URL "?part=id,snippet,cdn,status"
  506. "&maxResults=1";
  507. url += "&id=" + id.toUtf8();
  508. if (!InsertCommand(url, "application/json", "", nullptr, json_out))
  509. return false;
  510. auto items = json_out["items"].array_items();
  511. if (items.size() != 1) {
  512. lastErrorMessage = "No active broadcast found.";
  513. return false;
  514. }
  515. return true;
  516. }