youtube.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. /* eslint-disable */
  2. import async from "async";
  3. import config from "config";
  4. import * as rax from "retry-axios";
  5. import axios from "axios";
  6. import CoreClass from "../core";
  7. class RateLimitter {
  8. /**
  9. * Constructor
  10. *
  11. * @param {number} timeBetween - The time between each allowed YouTube request
  12. */
  13. constructor(timeBetween) {
  14. this.dateStarted = Date.now();
  15. this.timeBetween = timeBetween;
  16. }
  17. /**
  18. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  19. *
  20. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  21. */
  22. continue() {
  23. return new Promise(resolve => {
  24. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  25. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  26. });
  27. }
  28. /**
  29. * Restart the rate limit timer
  30. */
  31. restart() {
  32. this.dateStarted = Date.now();
  33. }
  34. }
  35. let YouTubeModule;
  36. const quotas = [
  37. {
  38. type: "QUERIES_PER_DAY",
  39. limit: 10000
  40. },
  41. {
  42. type: "QUERIES_PER_MINUTE",
  43. limit: 1800000
  44. },
  45. {
  46. type: "QUERIES_PER_100_SECONDS",
  47. limit: 3000000
  48. }
  49. ];
  50. // const dummyApiCalls = [
  51. // {
  52. // quotaCost: 100,
  53. // date: new Date(new Date() - (1000 * 120))
  54. // },
  55. // {
  56. // quotaCost: 2,
  57. // date: new Date(new Date() - (1000 * 120))
  58. // },
  59. // {
  60. // quotaCost: 1,
  61. // date: new Date()
  62. // },
  63. // {
  64. // quotaCost: 100,
  65. // date: new Date()
  66. // }
  67. // ];
  68. const isQuotaExceeded = apiCalls => {
  69. const reversedApiCalls = apiCalls.slice().reverse();
  70. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  71. let quotaExceeded = false;
  72. for (const quota of sortedQuotas) {
  73. let quotaUsed = 0;
  74. let dateCutoff = null;
  75. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  76. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  77. else if (quota.type === "QUERIES_PER_DAY") {
  78. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  79. dateCutoff = new Date();
  80. dateCutoff.setUTCMilliseconds(0);
  81. dateCutoff.setUTCSeconds(0);
  82. dateCutoff.setUTCMinutes(0);
  83. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  84. dateCutoff.setUTCHours(0);
  85. }
  86. for (const apiCall of reversedApiCalls) {
  87. if (apiCall.date >= dateCutoff) quotaUsed += apiCall.quotaCost;
  88. else break;
  89. }
  90. if (quotaUsed >= quota.limit) {
  91. quotaExceeded = true;
  92. break;
  93. }
  94. }
  95. return quotaExceeded;
  96. };
  97. const getQuotaStatus = apiCalls => {
  98. const reversedApiCalls = apiCalls.slice().reverse();
  99. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  100. const status = {};
  101. for (const quota of sortedQuotas) {
  102. status[quota.type] = {
  103. quotaUsed: 0,
  104. limit: quota.limit,
  105. quotaExceeded: false
  106. };
  107. let dateCutoff = null;
  108. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  109. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  110. else if (quota.type === "QUERIES_PER_DAY") {
  111. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  112. dateCutoff = new Date();
  113. dateCutoff.setUTCMilliseconds(0);
  114. dateCutoff.setUTCSeconds(0);
  115. dateCutoff.setUTCMinutes(0);
  116. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  117. dateCutoff.setUTCHours(0);
  118. }
  119. for (const apiCall of reversedApiCalls) {
  120. if (apiCall.date >= dateCutoff) status[quota.type].quotaUsed += apiCall.quotaCost;
  121. else break;
  122. }
  123. if (status[quota.type].quotaUsed >= quota.limit && !status[quota.type].quotaExceeded)
  124. status[quota.type].quotaExceeded = true;
  125. }
  126. return status;
  127. };
  128. class _YouTubeModule extends CoreClass {
  129. // eslint-disable-next-line require-jsdoc
  130. constructor() {
  131. super("youtube", {
  132. concurrency: 1,
  133. priorities: {
  134. GET_PLAYLIST: 11
  135. }
  136. });
  137. YouTubeModule = this;
  138. }
  139. /**
  140. * Initialises the activities module
  141. *
  142. * @returns {Promise} - returns promise (reject, resolve)
  143. */
  144. initialize() {
  145. return new Promise(resolve => {
  146. this.rateLimiter = new RateLimitter(config.get("apis.youtube.rateLimit"));
  147. this.requestTimeout = config.get("apis.youtube.requestTimeout");
  148. this.axios = axios.create();
  149. this.axios.defaults.raxConfig = {
  150. instance: this.axios,
  151. retry: config.get("apis.youtube.retryAmount"),
  152. noResponseRetries: config.get("apis.youtube.retryAmount")
  153. };
  154. rax.attach(this.axios);
  155. this.apiCalls = [];
  156. resolve();
  157. });
  158. }
  159. /**
  160. * Fetches a list of songs from Youtube's API
  161. *
  162. * @param {object} payload - object that contains the payload
  163. * @param {string} payload.query - the query we'll pass to youtubes api
  164. * @param {string} payload.pageToken - (optional) if this exists, will search search youtube for a specific page reference
  165. * @returns {Promise} - returns promise (reject, resolve)
  166. */
  167. SEARCH(payload) {
  168. const params = {
  169. part: "snippet",
  170. q: payload.query,
  171. type: "video",
  172. maxResults: 10
  173. };
  174. if (payload.pageToken) params.pageToken = payload.pageToken;
  175. return new Promise((resolve, reject) => {
  176. YouTubeModule.runJob(
  177. "API_SEARCH",
  178. {
  179. params
  180. },
  181. this
  182. )
  183. .then(({ response }) => {
  184. const { data } = response;
  185. return resolve(data);
  186. })
  187. .catch(err => {
  188. YouTubeModule.log("ERROR", "SEARCH", `${err.message}`);
  189. return reject(new Error("An error has occured. Please try again later."));
  190. });
  191. });
  192. }
  193. /**
  194. * Gets the details of a song using the YouTube API
  195. *
  196. * @param {object} payload - object that contains the payload
  197. * @param {string} payload.youtubeId - the YouTube API id of the song
  198. * @returns {Promise} - returns promise (reject, resolve)
  199. */
  200. GET_SONG(payload) {
  201. return new Promise((resolve, reject) => {
  202. const params = {
  203. part: "snippet,contentDetails,statistics,status",
  204. id: payload.youtubeId
  205. };
  206. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  207. .then(({ response }) => {
  208. const { data } = response;
  209. if (data.items[0] === undefined)
  210. return reject(new Error("The specified video does not exist or cannot be publicly accessed."));
  211. // TODO Clean up duration converter
  212. let dur = data.items[0].contentDetails.duration;
  213. dur = dur.replace("PT", "");
  214. let duration = 0;
  215. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  216. v2 = Number(v2);
  217. duration = v2 * 60 * 60;
  218. return "";
  219. });
  220. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  221. v2 = Number(v2);
  222. duration += v2 * 60;
  223. return "";
  224. });
  225. // eslint-disable-next-line no-unused-vars
  226. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  227. v2 = Number(v2);
  228. duration += v2;
  229. return "";
  230. });
  231. const song = {
  232. youtubeId: data.items[0].id,
  233. title: data.items[0].snippet.title,
  234. thumbnail: data.items[0].snippet.thumbnails.default.url,
  235. duration
  236. };
  237. return resolve({ song });
  238. })
  239. .catch(err => {
  240. YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
  241. return reject(new Error("An error has occured. Please try again later."));
  242. });
  243. });
  244. }
  245. /**
  246. * Gets the id of the channel upload playlist
  247. *
  248. * @param {object} payload - object that contains the payload
  249. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  250. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  251. * @returns {Promise} - returns promise (reject, resolve)
  252. */
  253. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  254. return new Promise((resolve, reject) => {
  255. const params = {
  256. part: "id,contentDetails"
  257. };
  258. if (payload.id) params.id = payload.id;
  259. else params.forUsername = payload.username;
  260. YouTubeModule.runJob(
  261. "API_GET_CHANNELS",
  262. {
  263. params
  264. },
  265. this
  266. )
  267. .then(({ response }) => {
  268. const { data } = response;
  269. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  270. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  271. return resolve({ playlistId });
  272. })
  273. .catch(err => {
  274. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  275. if (err.message === "Request failed with status code 404") {
  276. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  277. }
  278. return reject(new Error("An error has occured. Please try again later."));
  279. });
  280. });
  281. }
  282. /**
  283. * Gets the id of the channel from the custom URL
  284. *
  285. * @param {object} payload - object that contains the payload
  286. * @param {string} payload.customUrl - the customUrl of the YouTube channel
  287. * @returns {Promise} - returns promise (reject, resolve)
  288. */
  289. GET_CHANNEL_ID_FROM_CUSTOM_URL(payload) {
  290. return new Promise((resolve, reject) => {
  291. async.waterfall(
  292. [
  293. next => {
  294. const params = {
  295. part: "snippet",
  296. type: "channel",
  297. maxResults: 50
  298. };
  299. params.q = payload.customUrl;
  300. YouTubeModule.runJob(
  301. "API_SEARCH",
  302. {
  303. params
  304. },
  305. this
  306. )
  307. .then(({ response }) => {
  308. const { data } = response;
  309. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  310. const channelIds = data.items.map(item => item.id.channelId);
  311. return next(null, channelIds);
  312. })
  313. .catch(err => {
  314. next(err);
  315. });
  316. },
  317. (channelIds, next) => {
  318. const params = {
  319. part: "snippet",
  320. id: channelIds.join(","),
  321. maxResults: 50
  322. };
  323. YouTubeModule.runJob(
  324. "API_GET_CHANNELS",
  325. {
  326. params
  327. },
  328. this
  329. )
  330. .then(({ response }) => {
  331. const { data } = response;
  332. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  333. let channelId = null;
  334. for (const item of data.items) {
  335. if (item.snippet.customUrl && item.snippet.customUrl.toLowerCase() === payload.customUrl.toLowerCase()) {
  336. channelId = item.id;
  337. break;
  338. }
  339. }
  340. if (!channelId) return next("Channel not found.");
  341. return next(null, channelId);
  342. })
  343. .catch(err => {
  344. next(err);
  345. });
  346. }
  347. ],
  348. (channelId, err) => {
  349. if (err) {
  350. YouTubeModule.log("ERROR", "GET_CHANNEL_ID_FROM_CUSTOM_URL", `${err.message}`);
  351. if (err.message === "Request failed with status code 404") {
  352. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  353. }
  354. return reject(new Error("An error has occured. Please try again later."));
  355. }
  356. return resolve({ channelId });
  357. }
  358. );
  359. });
  360. }
  361. /**
  362. * Returns an array of songs taken from a YouTube playlist
  363. *
  364. * @param {object} payload - object that contains the payload
  365. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  366. * @param {string} payload.url - the url of the YouTube playlist
  367. * @returns {Promise} - returns promise (reject, resolve)
  368. */
  369. GET_PLAYLIST(payload) {
  370. return new Promise((resolve, reject) => {
  371. const regex = /[\\?&]list=([^&#]*)/;
  372. const splitQuery = regex.exec(payload.url);
  373. if (!splitQuery) {
  374. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  375. reject(new Error("Invalid playlist URL."));
  376. return;
  377. }
  378. const playlistId = splitQuery[1];
  379. async.waterfall(
  380. [
  381. next => {
  382. let songs = [];
  383. let nextPageToken = "";
  384. async.whilst(
  385. next => {
  386. YouTubeModule.log(
  387. "INFO",
  388. `Getting playlist progress for job (${this.toString()}): ${
  389. songs.length
  390. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  391. );
  392. next(null, nextPageToken !== undefined);
  393. },
  394. next => {
  395. // Add 250ms delay between each job request
  396. setTimeout(() => {
  397. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  398. .then(response => {
  399. songs = songs.concat(response.songs);
  400. nextPageToken = response.nextPageToken;
  401. next();
  402. })
  403. .catch(err => next(err));
  404. }, 250);
  405. },
  406. err => next(err, songs)
  407. );
  408. },
  409. (songs, next) =>
  410. next(
  411. null,
  412. songs.map(song => song.contentDetails.videoId)
  413. ),
  414. (songs, next) => {
  415. if (!payload.musicOnly) return next(true, { songs });
  416. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  417. .then(filteredSongs => next(null, { filteredSongs, songs }))
  418. .catch(next);
  419. }
  420. ],
  421. (err, response) => {
  422. if (err && err !== true) {
  423. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  424. reject(new Error(err.message));
  425. } else {
  426. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  427. }
  428. }
  429. );
  430. });
  431. }
  432. /**
  433. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL.
  434. *
  435. * @param {object} payload - object that contains the payload
  436. * @param {boolean} payload.playlistId - the playlist id to get videos from
  437. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  438. * @param {string} payload.url - the url of the YouTube playlist
  439. * @returns {Promise} - returns promise (reject, resolve)
  440. */
  441. GET_PLAYLIST_PAGE(payload) {
  442. return new Promise((resolve, reject) => {
  443. const params = {
  444. part: "contentDetails",
  445. playlistId: payload.playlistId,
  446. maxResults: 50
  447. };
  448. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  449. YouTubeModule.runJob(
  450. "GET_PLAYLIST_ITEMS",
  451. {
  452. params
  453. },
  454. this
  455. )
  456. .then(({ response }) => {
  457. const { data } = response;
  458. const songs = data.items;
  459. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  460. return resolve({ songs });
  461. })
  462. .catch(err => {
  463. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  464. if (err.message === "Request failed with status code 404") {
  465. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  466. }
  467. return reject(new Error("An error has occured. Please try again later."));
  468. });
  469. });
  470. }
  471. /**
  472. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  473. *
  474. * @param {object} payload - object that contains the payload
  475. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  476. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  477. * @returns {Promise} - returns promise (reject, resolve)
  478. */
  479. FILTER_MUSIC_VIDEOS(payload) {
  480. return new Promise((resolve, reject) => {
  481. const page = payload.page ? payload.page : 0;
  482. const videosPerPage = 50;
  483. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  484. if (localVideoIds.length === 0) {
  485. resolve({ videoIds: [] });
  486. return;
  487. }
  488. const params = {
  489. part: "topicDetails",
  490. id: localVideoIds.join(","),
  491. maxResults: videosPerPage
  492. };
  493. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  494. .then(({ response }) => {
  495. const { data } = response;
  496. const videoIds = [];
  497. data.items.forEach(item => {
  498. const videoId = item.id;
  499. if (!item.topicDetails) return;
  500. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  501. videoIds.push(videoId);
  502. });
  503. return YouTubeModule.runJob(
  504. "FILTER_MUSIC_VIDEOS",
  505. { videoIds: payload.videoIds, page: page + 1 },
  506. this
  507. )
  508. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  509. .catch(err => reject(err));
  510. })
  511. .catch(err => {
  512. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  513. return reject(new Error("Failed to find playlist from YouTube"));
  514. });
  515. });
  516. }
  517. /**
  518. * Returns an array of songs taken from a YouTube channel
  519. *
  520. * @param {object} payload - object that contains the payload
  521. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  522. * @param {string} payload.url - the url of the YouTube channel
  523. * @returns {Promise} - returns promise (reject, resolve)
  524. */
  525. GET_CHANNEL(payload) {
  526. return new Promise((resolve, reject) => {
  527. const regex = /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  528. const splitQuery = regex.exec(payload.url);
  529. if (!splitQuery) {
  530. YouTubeModule.log("ERROR", "GET_CHANNEL", "Invalid YouTube channel URL query.");
  531. reject(new Error("Invalid playlist URL."));
  532. return;
  533. }
  534. const channelId = splitQuery[1];
  535. const channelUsername = splitQuery[2];
  536. const channelCustomUrl = splitQuery[3]; // NOTE: not supported yet
  537. const channelUsernameOrCustomUrl = splitQuery[4]; // NOTE: customUrl not supported yet
  538. console.log(`Channel id: ${channelId}`);
  539. console.log(`Channel username: ${channelUsername}`);
  540. console.log(`Channel custom URL: ${channelCustomUrl}`);
  541. console.log(`Channel username or custom URL: ${channelUsernameOrCustomUrl}`);
  542. async.waterfall(
  543. [
  544. next => {
  545. const payload = {};
  546. if (channelId) payload.id = channelId;
  547. else if (channelUsername || channelUsernameOrCustomUrl) payload.username = channelUsername;
  548. else return next("No id/username given.");
  549. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  550. .then(({ playlistId }) => {
  551. next(null, playlistId);
  552. })
  553. .catch(err => next(err));
  554. },
  555. next => {
  556. let songs = [];
  557. let nextPageToken = "";
  558. async.whilst(
  559. next => {
  560. YouTubeModule.log(
  561. "INFO",
  562. `Getting channel progress for job (${this.toString()}): ${
  563. songs.length
  564. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  565. );
  566. next(null, nextPageToken !== undefined);
  567. },
  568. next => {
  569. // Add 250ms delay between each job request
  570. setTimeout(() => {
  571. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  572. .then(response => {
  573. songs = songs.concat(response.songs);
  574. nextPageToken = response.nextPageToken;
  575. next();
  576. })
  577. .catch(err => next(err));
  578. }, 250);
  579. },
  580. err => next(err, songs)
  581. );
  582. },
  583. (songs, next) =>
  584. next(
  585. null,
  586. songs.map(song => song.contentDetails.videoId)
  587. ),
  588. (songs, next) => {
  589. if (!payload.musicOnly) return next(true, { songs });
  590. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  591. .then(filteredSongs => next(null, { filteredSongs, songs }))
  592. .catch(next);
  593. }
  594. ],
  595. (err, response) => {
  596. if (err && err !== true) {
  597. YouTubeModule.log("ERROR", "GET_CHANNEL", "Some error has occurred.", err.message);
  598. reject(new Error(err.message));
  599. } else {
  600. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  601. }
  602. }
  603. );
  604. });
  605. }
  606. API_GET_VIDEOS(payload) {
  607. return new Promise((resolve, reject) => {
  608. const { params } = payload;
  609. YouTubeModule.runJob(
  610. "API_CALL",
  611. {
  612. url: "https://www.googleapis.com/youtube/v3/videos",
  613. params: {
  614. key: config.get("apis.youtube.key"),
  615. ...params
  616. },
  617. quotaCost: 1
  618. },
  619. this
  620. )
  621. .then(response => {
  622. resolve(response);
  623. })
  624. .catch(err => {
  625. reject(err);
  626. });
  627. });
  628. }
  629. API_GET_PLAYLIST_ITEMS(payload) {
  630. return new Promise((resolve, reject) => {
  631. const { params } = payload;
  632. YouTubeModule.runJob(
  633. "API_CALL",
  634. {
  635. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  636. params: {
  637. key: config.get("apis.youtube.key"),
  638. ...params
  639. },
  640. quotaCost: 1
  641. },
  642. this
  643. )
  644. .then(response => {
  645. resolve(response);
  646. })
  647. .catch(err => {
  648. reject(err);
  649. });
  650. });
  651. }
  652. API_GET_CHANNELS(payload) {
  653. return new Promise((resolve, reject) => {
  654. const { params } = payload;
  655. YouTubeModule.runJob(
  656. "API_CALL",
  657. {
  658. url: "https://www.googleapis.com/youtube/v3/channels",
  659. params: {
  660. key: config.get("apis.youtube.key"),
  661. ...params
  662. },
  663. quotaCost: 1
  664. },
  665. this
  666. )
  667. .then(response => {
  668. resolve(response);
  669. })
  670. .catch(err => {
  671. reject(err);
  672. });
  673. });
  674. }
  675. API_SEARCH(payload) {
  676. return new Promise((resolve, reject) => {
  677. const { params } = payload;
  678. YouTubeModule.runJob(
  679. "API_CALL",
  680. {
  681. url: "https://www.googleapis.com/youtube/v3/search",
  682. params: {
  683. key: config.get("apis.youtube.key"),
  684. ...params
  685. },
  686. quotaCost: 100
  687. },
  688. this
  689. )
  690. .then(response => {
  691. resolve(response);
  692. })
  693. .catch(err => {
  694. reject(err);
  695. });
  696. });
  697. }
  698. API_CALL(payload) {
  699. return new Promise((resolve, reject) => {
  700. const { url, params, quotaCost } = payload;
  701. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  702. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  703. else {
  704. YouTubeModule.apiCalls.push({
  705. quotaCost,
  706. date: new Date()
  707. });
  708. YouTubeModule.axios
  709. .get(url, {
  710. params,
  711. timeout: YouTubeModule.requestTimeout
  712. })
  713. .then(response => {
  714. if (response.data.error) {
  715. reject(new Error(response.data.error));
  716. } else {
  717. resolve({ response });
  718. }
  719. })
  720. .catch(err => {
  721. reject(err);
  722. });
  723. }
  724. });
  725. }
  726. }
  727. export default new _YouTubeModule();