youtube-api-wrappers.cpp 15 KB

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