youtube.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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({ date: { $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(payload) {
  160. return new Promise((resolve, reject) => {
  161. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  162. YouTubeModule.youtubeApiRequestModel
  163. .find({ date: { $gte: fromDate - 2 * 24 * 60 * 60 * 1000, $lte: fromDate } }, { date: true, quotaCost: true, _id: false })
  164. .sort({ date: 1 })
  165. .exec((err, youtubeApiRequests) => {
  166. if (err) reject(new Error("Couldn't load YouTube API requests."));
  167. else {
  168. const reversedApiCalls = youtubeApiRequests.slice().reverse();
  169. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  170. const status = {};
  171. for (const quota of sortedQuotas) {
  172. status[quota.type] = {
  173. quotaUsed: 0,
  174. limit: quota.limit,
  175. quotaExceeded: false
  176. };
  177. let dateCutoff = null;
  178. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date(fromDate) - 1000 * 60;
  179. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date(fromDate) - 1000 * 100;
  180. else if (quota.type === "QUERIES_PER_DAY") {
  181. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  182. dateCutoff = new Date(fromDate);
  183. dateCutoff.setUTCMilliseconds(0);
  184. dateCutoff.setUTCSeconds(0);
  185. dateCutoff.setUTCMinutes(0);
  186. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  187. dateCutoff.setUTCHours(0);
  188. }
  189. for (const apiCall of reversedApiCalls) {
  190. if (apiCall.date >= dateCutoff) status[quota.type].quotaUsed += apiCall.quotaCost;
  191. else break;
  192. }
  193. if (status[quota.type].quotaUsed >= quota.limit && !status[quota.type].quotaExceeded)
  194. status[quota.type].quotaExceeded = true;
  195. }
  196. resolve({ status });
  197. }
  198. });
  199. });
  200. }
  201. /**
  202. * Gets the details of a song using the YouTube API
  203. *
  204. * @param {object} payload - object that contains the payload
  205. * @param {string} payload.youtubeId - the YouTube API id of the song
  206. * @returns {Promise} - returns promise (reject, resolve)
  207. */
  208. GET_SONG(payload) {
  209. return new Promise((resolve, reject) => {
  210. const params = {
  211. part: "snippet,contentDetails,statistics,status",
  212. id: payload.youtubeId
  213. };
  214. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  215. .then(({ response }) => {
  216. const { data } = response;
  217. if (data.items[0] === undefined)
  218. return reject(new Error("The specified video does not exist or cannot be publicly accessed."));
  219. // TODO Clean up duration converter
  220. let dur = data.items[0].contentDetails.duration;
  221. dur = dur.replace("PT", "");
  222. let duration = 0;
  223. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  224. v2 = Number(v2);
  225. duration = v2 * 60 * 60;
  226. return "";
  227. });
  228. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  229. v2 = Number(v2);
  230. duration += v2 * 60;
  231. return "";
  232. });
  233. // eslint-disable-next-line no-unused-vars
  234. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  235. v2 = Number(v2);
  236. duration += v2;
  237. return "";
  238. });
  239. const song = {
  240. youtubeId: data.items[0].id,
  241. title: data.items[0].snippet.title,
  242. thumbnail: data.items[0].snippet.thumbnails.default.url,
  243. duration
  244. };
  245. return resolve({ song });
  246. })
  247. .catch(err => {
  248. YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
  249. return reject(new Error("An error has occured. Please try again later."));
  250. });
  251. });
  252. }
  253. /**
  254. * Gets the id of the channel upload playlist
  255. *
  256. * @param {object} payload - object that contains the payload
  257. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  258. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  259. * @returns {Promise} - returns promise (reject, resolve)
  260. */
  261. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  262. return new Promise((resolve, reject) => {
  263. const params = {
  264. part: "id,contentDetails"
  265. };
  266. if (payload.id) params.id = payload.id;
  267. else params.forUsername = payload.username;
  268. YouTubeModule.runJob(
  269. "API_GET_CHANNELS",
  270. {
  271. params
  272. },
  273. this
  274. )
  275. .then(({ response }) => {
  276. const { data } = response;
  277. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  278. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  279. return resolve({ playlistId });
  280. })
  281. .catch(err => {
  282. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  283. if (err.message === "Request failed with status code 404") {
  284. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  285. }
  286. return reject(new Error("An error has occured. Please try again later."));
  287. });
  288. });
  289. }
  290. /**
  291. * Gets the id of the channel from the custom URL
  292. *
  293. * @param {object} payload - object that contains the payload
  294. * @param {string} payload.customUrl - the customUrl of the YouTube channel
  295. * @returns {Promise} - returns promise (reject, resolve)
  296. */
  297. GET_CHANNEL_ID_FROM_CUSTOM_URL(payload) {
  298. return new Promise((resolve, reject) => {
  299. async.waterfall(
  300. [
  301. next => {
  302. const params = {
  303. part: "snippet",
  304. type: "channel",
  305. maxResults: 50
  306. };
  307. params.q = payload.customUrl;
  308. YouTubeModule.runJob(
  309. "API_SEARCH",
  310. {
  311. params
  312. },
  313. this
  314. )
  315. .then(({ response }) => {
  316. const { data } = response;
  317. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  318. const channelIds = data.items.map(item => item.id.channelId);
  319. return next(null, channelIds);
  320. })
  321. .catch(err => {
  322. next(err);
  323. });
  324. },
  325. (channelIds, next) => {
  326. const params = {
  327. part: "snippet",
  328. id: channelIds.join(","),
  329. maxResults: 50
  330. };
  331. YouTubeModule.runJob(
  332. "API_GET_CHANNELS",
  333. {
  334. params
  335. },
  336. this
  337. )
  338. .then(({ response }) => {
  339. const { data } = response;
  340. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  341. let channelId = null;
  342. for (const item of data.items) {
  343. if (
  344. item.snippet.customUrl &&
  345. item.snippet.customUrl.toLowerCase() === payload.customUrl.toLowerCase()
  346. ) {
  347. channelId = item.id;
  348. break;
  349. }
  350. }
  351. if (!channelId) return next("Channel not found.");
  352. return next(null, channelId);
  353. })
  354. .catch(err => {
  355. next(err);
  356. });
  357. }
  358. ],
  359. (err, channelId) => {
  360. if (err) {
  361. YouTubeModule.log("ERROR", "GET_CHANNEL_ID_FROM_CUSTOM_URL", `${err.message}`);
  362. if (err.message === "Request failed with status code 404") {
  363. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  364. }
  365. return reject(new Error("An error has occured. Please try again later."));
  366. }
  367. return resolve({ channelId });
  368. }
  369. );
  370. });
  371. }
  372. /**
  373. * Returns an array of songs taken from a YouTube playlist
  374. *
  375. * @param {object} payload - object that contains the payload
  376. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  377. * @param {string} payload.url - the url of the YouTube playlist
  378. * @returns {Promise} - returns promise (reject, resolve)
  379. */
  380. GET_PLAYLIST(payload) {
  381. return new Promise((resolve, reject) => {
  382. const regex = /[\\?&]list=([^&#]*)/;
  383. const splitQuery = regex.exec(payload.url);
  384. if (!splitQuery) {
  385. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  386. reject(new Error("Invalid playlist URL."));
  387. return;
  388. }
  389. const playlistId = splitQuery[1];
  390. async.waterfall(
  391. [
  392. next => {
  393. let songs = [];
  394. let nextPageToken = "";
  395. async.whilst(
  396. next => {
  397. YouTubeModule.log(
  398. "INFO",
  399. `Getting playlist progress for job (${this.toString()}): ${songs.length
  400. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  401. );
  402. next(null, nextPageToken !== undefined);
  403. },
  404. next => {
  405. // Add 250ms delay between each job request
  406. setTimeout(() => {
  407. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  408. .then(response => {
  409. songs = songs.concat(response.songs);
  410. nextPageToken = response.nextPageToken;
  411. next();
  412. })
  413. .catch(err => next(err));
  414. }, 250);
  415. },
  416. err => next(err, songs)
  417. );
  418. },
  419. (songs, next) =>
  420. next(
  421. null,
  422. songs.map(song => song.contentDetails.videoId)
  423. ),
  424. (songs, next) => {
  425. if (!payload.musicOnly) return next(true, { songs });
  426. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  427. .then(filteredSongs => next(null, { filteredSongs, songs }))
  428. .catch(next);
  429. }
  430. ],
  431. (err, response) => {
  432. if (err && err !== true) {
  433. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  434. reject(new Error(err.message));
  435. } else {
  436. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  437. }
  438. }
  439. );
  440. });
  441. }
  442. /**
  443. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL.
  444. *
  445. * @param {object} payload - object that contains the payload
  446. * @param {boolean} payload.playlistId - the playlist id to get videos from
  447. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  448. * @param {string} payload.url - the url of the YouTube playlist
  449. * @returns {Promise} - returns promise (reject, resolve)
  450. */
  451. GET_PLAYLIST_PAGE(payload) {
  452. return new Promise((resolve, reject) => {
  453. const params = {
  454. part: "contentDetails",
  455. playlistId: payload.playlistId,
  456. maxResults: 50
  457. };
  458. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  459. YouTubeModule.runJob(
  460. "API_GET_PLAYLIST_ITEMS",
  461. {
  462. params
  463. },
  464. this
  465. )
  466. .then(({ response }) => {
  467. const { data } = response;
  468. const songs = data.items;
  469. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  470. return resolve({ songs });
  471. })
  472. .catch(err => {
  473. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  474. if (err.message === "Request failed with status code 404") {
  475. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  476. }
  477. return reject(new Error("An error has occured. Please try again later."));
  478. });
  479. });
  480. }
  481. /**
  482. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  483. *
  484. * @param {object} payload - object that contains the payload
  485. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  486. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  487. * @returns {Promise} - returns promise (reject, resolve)
  488. */
  489. FILTER_MUSIC_VIDEOS(payload) {
  490. return new Promise((resolve, reject) => {
  491. const page = payload.page ? payload.page : 0;
  492. const videosPerPage = 50;
  493. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  494. if (localVideoIds.length === 0) {
  495. resolve({ videoIds: [] });
  496. return;
  497. }
  498. const params = {
  499. part: "topicDetails",
  500. id: localVideoIds.join(","),
  501. maxResults: videosPerPage
  502. };
  503. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  504. .then(({ response }) => {
  505. const { data } = response;
  506. const videoIds = [];
  507. data.items.forEach(item => {
  508. const videoId = item.id;
  509. if (!item.topicDetails) return;
  510. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  511. videoIds.push(videoId);
  512. });
  513. return YouTubeModule.runJob(
  514. "FILTER_MUSIC_VIDEOS",
  515. { videoIds: payload.videoIds, page: page + 1 },
  516. this
  517. )
  518. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  519. .catch(err => reject(err));
  520. })
  521. .catch(err => {
  522. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  523. return reject(new Error("Failed to find playlist from YouTube"));
  524. });
  525. });
  526. }
  527. /**
  528. * Returns an array of songs taken from a YouTube channel
  529. *
  530. * @param {object} payload - object that contains the payload
  531. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  532. * @param {string} payload.url - the url of the YouTube channel
  533. * @returns {Promise} - returns promise (reject, resolve)
  534. */
  535. GET_CHANNEL(payload) {
  536. return new Promise((resolve, reject) => {
  537. const regex =
  538. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  539. const splitQuery = regex.exec(payload.url);
  540. if (!splitQuery) {
  541. YouTubeModule.log("ERROR", "GET_CHANNEL", "Invalid YouTube channel URL query.");
  542. reject(new Error("Invalid playlist URL."));
  543. return;
  544. }
  545. const channelId = splitQuery[1];
  546. const channelUsername = splitQuery[2];
  547. const channelCustomUrl = splitQuery[3];
  548. const channelUsernameOrCustomUrl = splitQuery[4];
  549. console.log(`Channel id: ${channelId}`);
  550. console.log(`Channel username: ${channelUsername}`);
  551. console.log(`Channel custom URL: ${channelCustomUrl}`);
  552. console.log(`Channel username or custom URL: ${channelUsernameOrCustomUrl}`);
  553. async.waterfall(
  554. [
  555. next => {
  556. const payload = {};
  557. if (channelId) payload.id = channelId;
  558. else if (channelUsername) payload.username = channelUsername;
  559. else return next(null, true, null);
  560. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  561. .then(({ playlistId }) => {
  562. next(null, false, playlistId);
  563. })
  564. .catch(err => {
  565. if (err.message === "Channel not found. Is the channel public/unlisted?") next(null, true, null);
  566. else next(err);
  567. });
  568. },
  569. (getUsernameFromCustomUrl, playlistId, next) => {
  570. if (!getUsernameFromCustomUrl) return next(null, playlistId);
  571. const payload = {};
  572. if (channelCustomUrl) payload.customUrl = channelCustomUrl;
  573. else if (channelUsernameOrCustomUrl) payload.customUrl = channelUsernameOrCustomUrl;
  574. else next("No proper URL provided.");
  575. YouTubeModule.runJob("GET_CHANNEL_ID_FROM_CUSTOM_URL", payload, this)
  576. .then(({ channelId }) => {
  577. YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", { id: channelId }, this)
  578. .then(({ playlistId }) => {
  579. next(null, playlistId);
  580. })
  581. .catch(err => next(err));
  582. })
  583. .catch(err => next(err));
  584. },
  585. (playlistId, next) => {
  586. let songs = [];
  587. let nextPageToken = "";
  588. async.whilst(
  589. next => {
  590. YouTubeModule.log(
  591. "INFO",
  592. `Getting channel progress for job (${this.toString()}): ${songs.length
  593. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  594. );
  595. next(null, nextPageToken !== undefined);
  596. },
  597. next => {
  598. // Add 250ms delay between each job request
  599. setTimeout(() => {
  600. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  601. .then(response => {
  602. songs = songs.concat(response.songs);
  603. nextPageToken = response.nextPageToken;
  604. next();
  605. })
  606. .catch(err => next(err));
  607. }, 250);
  608. },
  609. err => next(err, songs)
  610. );
  611. },
  612. (songs, next) =>
  613. next(
  614. null,
  615. songs.map(song => song.contentDetails.videoId)
  616. ),
  617. (songs, next) => {
  618. if (!payload.musicOnly) return next(true, { songs });
  619. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  620. .then(filteredSongs => next(null, { filteredSongs, songs }))
  621. .catch(next);
  622. }
  623. ],
  624. (err, response) => {
  625. if (err && err !== true) {
  626. YouTubeModule.log("ERROR", "GET_CHANNEL", "Some error has occurred.", err.message);
  627. reject(new Error(err.message));
  628. } else {
  629. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  630. }
  631. }
  632. );
  633. });
  634. }
  635. API_GET_VIDEOS(payload) {
  636. return new Promise((resolve, reject) => {
  637. const { params } = payload;
  638. YouTubeModule.runJob(
  639. "API_CALL",
  640. {
  641. url: "https://www.googleapis.com/youtube/v3/videos",
  642. params: {
  643. key: config.get("apis.youtube.key"),
  644. ...params
  645. },
  646. quotaCost: 1
  647. },
  648. this
  649. )
  650. .then(response => {
  651. resolve(response);
  652. })
  653. .catch(err => {
  654. reject(err);
  655. });
  656. });
  657. }
  658. API_GET_PLAYLIST_ITEMS(payload) {
  659. return new Promise((resolve, reject) => {
  660. const { params } = payload;
  661. YouTubeModule.runJob(
  662. "API_CALL",
  663. {
  664. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  665. params: {
  666. key: config.get("apis.youtube.key"),
  667. ...params
  668. },
  669. quotaCost: 1
  670. },
  671. this
  672. )
  673. .then(response => {
  674. resolve(response);
  675. })
  676. .catch(err => {
  677. reject(err);
  678. });
  679. });
  680. }
  681. API_GET_CHANNELS(payload) {
  682. return new Promise((resolve, reject) => {
  683. const { params } = payload;
  684. YouTubeModule.runJob(
  685. "API_CALL",
  686. {
  687. url: "https://www.googleapis.com/youtube/v3/channels",
  688. params: {
  689. key: config.get("apis.youtube.key"),
  690. ...params
  691. },
  692. quotaCost: 1
  693. },
  694. this
  695. )
  696. .then(response => {
  697. resolve(response);
  698. })
  699. .catch(err => {
  700. reject(err);
  701. });
  702. });
  703. }
  704. API_SEARCH(payload) {
  705. return new Promise((resolve, reject) => {
  706. const { params } = payload;
  707. YouTubeModule.runJob(
  708. "API_CALL",
  709. {
  710. url: "https://www.googleapis.com/youtube/v3/search",
  711. params: {
  712. key: config.get("apis.youtube.key"),
  713. ...params
  714. },
  715. quotaCost: 100
  716. },
  717. this
  718. )
  719. .then(response => {
  720. resolve(response);
  721. })
  722. .catch(err => {
  723. reject(err);
  724. });
  725. });
  726. }
  727. API_CALL(payload) {
  728. return new Promise((resolve, reject) => {
  729. const { url, params, quotaCost } = payload;
  730. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  731. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  732. else {
  733. const youtubeApiRequest = new YouTubeModule.YoutubeApiRequestModel({
  734. url,
  735. date: Date.now(),
  736. quotaCost
  737. });
  738. youtubeApiRequest.save();
  739. const { key, ...keylessParams } = payload.params;
  740. CacheModule.runJob(
  741. "HSET",
  742. {
  743. table: "youtubeApiRequestParams",
  744. key: youtubeApiRequest._id.toString(),
  745. value: JSON.stringify(keylessParams)
  746. },
  747. this
  748. ).then();
  749. YouTubeModule.apiCalls.push({ date: youtubeApiRequest.date, quotaCost });
  750. YouTubeModule.axios
  751. .get(url, {
  752. params,
  753. timeout: YouTubeModule.requestTimeout
  754. })
  755. .then(response => {
  756. if (response.data.error) {
  757. reject(new Error(response.data.error));
  758. } else {
  759. CacheModule.runJob(
  760. "HSET",
  761. {
  762. table: "youtubeApiRequestResults",
  763. key: youtubeApiRequest._id.toString(),
  764. value: JSON.stringify(response.data)
  765. },
  766. this
  767. ).then();
  768. resolve({ response });
  769. }
  770. })
  771. .catch(err => {
  772. reject(err);
  773. });
  774. }
  775. });
  776. }
  777. GET_API_REQUESTS(payload) {
  778. return new Promise((resolve, reject) => {
  779. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  780. YouTubeModule.youtubeApiRequestModel
  781. .find({ date: { $lte: fromDate } })
  782. .sort({ date: -1 })
  783. .exec((err, youtubeApiRequests) => {
  784. if (err) reject(new Error("Couldn't load YouTube API requests."));
  785. else {
  786. resolve({ apiRequests: youtubeApiRequests });
  787. }
  788. });
  789. });
  790. }
  791. GET_API_REQUEST(payload) {
  792. return new Promise((resolve, reject) => {
  793. const { apiRequestId } = payload;
  794. async.waterfall(
  795. [
  796. next => {
  797. YouTubeModule.youtubeApiRequestModel
  798. .findOne({ _id: apiRequestId })
  799. .exec(next);
  800. },
  801. (apiRequest, next) => {
  802. CacheModule.runJob(
  803. "HGET",
  804. {
  805. table: "youtubeApiRequestParams",
  806. key: apiRequestId.toString()
  807. },
  808. this
  809. ).then(apiRequestParams => {
  810. next(null, {
  811. ...apiRequest._doc,
  812. params: apiRequestParams
  813. });
  814. }
  815. ).catch(err => next(err));
  816. },
  817. (apiRequest, next) => {
  818. CacheModule.runJob(
  819. "HGET",
  820. {
  821. table: "youtubeApiRequestResults",
  822. key: apiRequestId.toString()
  823. },
  824. this
  825. ).then(apiRequestResults => {
  826. next(null, {
  827. ...apiRequest,
  828. results: apiRequestResults
  829. });
  830. }).catch(err => next(err));
  831. }
  832. ],
  833. (err, apiRequest) => {
  834. if (err) reject(new Error(err));
  835. else resolve({ apiRequest });
  836. }
  837. );
  838. });
  839. }
  840. }
  841. export default new _YouTubeModule();