youtube.js 23 KB

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