youtube.js 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030
  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 isQuotaExceeded = apiCalls => {
  39. const reversedApiCalls = apiCalls.slice().reverse();
  40. const quotas = config.get("apis.youtube.quotas");
  41. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  42. let quotaExceeded = false;
  43. for (const quota of sortedQuotas) {
  44. let quotaUsed = 0;
  45. let dateCutoff = null;
  46. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  47. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  48. else if (quota.type === "QUERIES_PER_DAY") {
  49. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  50. dateCutoff = new Date();
  51. dateCutoff.setUTCMilliseconds(0);
  52. dateCutoff.setUTCSeconds(0);
  53. dateCutoff.setUTCMinutes(0);
  54. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  55. dateCutoff.setUTCHours(0);
  56. }
  57. for (const apiCall of reversedApiCalls) {
  58. if (apiCall.date >= dateCutoff) quotaUsed += apiCall.quotaCost;
  59. else break;
  60. }
  61. if (quotaUsed >= quota.limit) {
  62. quotaExceeded = true;
  63. break;
  64. }
  65. }
  66. return quotaExceeded;
  67. };
  68. class _YouTubeModule extends CoreClass {
  69. // eslint-disable-next-line require-jsdoc
  70. constructor() {
  71. super("youtube", {
  72. concurrency: 1,
  73. priorities: {
  74. GET_PLAYLIST: 11
  75. }
  76. });
  77. YouTubeModule = this;
  78. }
  79. /**
  80. * Initialises the activities module
  81. *
  82. * @returns {Promise} - returns promise (reject, resolve)
  83. */
  84. initialize() {
  85. return new Promise(async resolve => {
  86. CacheModule = this.moduleManager.modules.cache;
  87. DBModule = this.moduleManager.modules.db;
  88. this.youtubeApiRequestModel = this.YoutubeApiRequestModel = await DBModule.runJob("GET_MODEL", {
  89. modelName: "youtubeApiRequest"
  90. });
  91. this.rateLimiter = new RateLimitter(config.get("apis.youtube.rateLimit"));
  92. this.requestTimeout = config.get("apis.youtube.requestTimeout");
  93. this.axios = axios.create();
  94. this.axios.defaults.raxConfig = {
  95. instance: this.axios,
  96. retry: config.get("apis.youtube.retryAmount"),
  97. noResponseRetries: config.get("apis.youtube.retryAmount")
  98. };
  99. rax.attach(this.axios);
  100. this.youtubeApiRequestModel
  101. .find({ date: { $gte: new Date() - 2 * 24 * 60 * 60 * 1000 } }, { date: true, quotaCost: true, _id: false })
  102. .sort({ date: 1 })
  103. .exec((err, youtubeApiRequests) => {
  104. if (err) console.log("Couldn't load YouTube API requests.");
  105. else {
  106. this.apiCalls = youtubeApiRequests;
  107. resolve();
  108. }
  109. });
  110. });
  111. }
  112. /**
  113. * Fetches a list of songs from Youtube's API
  114. *
  115. * @param {object} payload - object that contains the payload
  116. * @param {string} payload.query - the query we'll pass to youtubes api
  117. * @param {string} payload.pageToken - (optional) if this exists, will search search youtube for a specific page reference
  118. * @returns {Promise} - returns promise (reject, resolve)
  119. */
  120. SEARCH(payload) {
  121. const params = {
  122. part: "snippet",
  123. q: payload.query,
  124. type: "video",
  125. maxResults: 10
  126. };
  127. if (payload.pageToken) params.pageToken = payload.pageToken;
  128. return new Promise((resolve, reject) => {
  129. YouTubeModule.runJob(
  130. "API_SEARCH",
  131. {
  132. params
  133. },
  134. this
  135. )
  136. .then(({ response }) => {
  137. const { data } = response;
  138. return resolve(data);
  139. })
  140. .catch(err => {
  141. YouTubeModule.log("ERROR", "SEARCH", `${err.message}`);
  142. return reject(new Error("An error has occured. Please try again later."));
  143. });
  144. });
  145. }
  146. GET_QUOTA_STATUS(payload) {
  147. return new Promise((resolve, reject) => {
  148. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  149. YouTubeModule.youtubeApiRequestModel
  150. .find({ date: { $gte: fromDate - 2 * 24 * 60 * 60 * 1000, $lte: fromDate } }, { date: true, quotaCost: true, _id: false })
  151. .sort({ date: 1 })
  152. .exec((err, youtubeApiRequests) => {
  153. if (err) reject(new Error("Couldn't load YouTube API requests."));
  154. else {
  155. const reversedApiCalls = youtubeApiRequests.slice().reverse();
  156. const quotas = config.get("apis.youtube.quotas");
  157. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  158. const status = {};
  159. for (const quota of sortedQuotas) {
  160. status[quota.type] = {
  161. title: quota.title,
  162. quotaUsed: 0,
  163. limit: quota.limit,
  164. quotaExceeded: false
  165. };
  166. let dateCutoff = null;
  167. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date(fromDate) - 1000 * 60;
  168. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date(fromDate) - 1000 * 100;
  169. else if (quota.type === "QUERIES_PER_DAY") {
  170. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  171. dateCutoff = new Date(fromDate);
  172. dateCutoff.setUTCMilliseconds(0);
  173. dateCutoff.setUTCSeconds(0);
  174. dateCutoff.setUTCMinutes(0);
  175. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  176. dateCutoff.setUTCHours(0);
  177. }
  178. for (const apiCall of reversedApiCalls) {
  179. if (apiCall.date >= dateCutoff) status[quota.type].quotaUsed += apiCall.quotaCost;
  180. else break;
  181. }
  182. if (status[quota.type].quotaUsed >= quota.limit && !status[quota.type].quotaExceeded)
  183. status[quota.type].quotaExceeded = true;
  184. }
  185. resolve({ status });
  186. }
  187. });
  188. });
  189. }
  190. /**
  191. * Gets the details of a song using the YouTube API
  192. *
  193. * @param {object} payload - object that contains the payload
  194. * @param {string} payload.youtubeId - the YouTube API id of the song
  195. * @returns {Promise} - returns promise (reject, resolve)
  196. */
  197. GET_SONG(payload) {
  198. return new Promise((resolve, reject) => {
  199. const params = {
  200. part: "snippet,contentDetails,statistics,status",
  201. id: payload.youtubeId
  202. };
  203. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  204. .then(({ response }) => {
  205. const { data } = response;
  206. if (data.items[0] === undefined)
  207. return reject(new Error("The specified video does not exist or cannot be publicly accessed."));
  208. // TODO Clean up duration converter
  209. let dur = data.items[0].contentDetails.duration;
  210. dur = dur.replace("PT", "");
  211. let duration = 0;
  212. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  213. v2 = Number(v2);
  214. duration = v2 * 60 * 60;
  215. return "";
  216. });
  217. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  218. v2 = Number(v2);
  219. duration += v2 * 60;
  220. return "";
  221. });
  222. // eslint-disable-next-line no-unused-vars
  223. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  224. v2 = Number(v2);
  225. duration += v2;
  226. return "";
  227. });
  228. const song = {
  229. youtubeId: data.items[0].id,
  230. title: data.items[0].snippet.title,
  231. thumbnail: data.items[0].snippet.thumbnails.default.url,
  232. duration
  233. };
  234. return resolve({ song });
  235. })
  236. .catch(err => {
  237. YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
  238. return reject(new Error("An error has occured. Please try again later."));
  239. });
  240. });
  241. }
  242. /**
  243. * Gets the id of the channel upload playlist
  244. *
  245. * @param {object} payload - object that contains the payload
  246. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  247. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  248. * @returns {Promise} - returns promise (reject, resolve)
  249. */
  250. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  251. return new Promise((resolve, reject) => {
  252. const params = {
  253. part: "id,contentDetails"
  254. };
  255. if (payload.id) params.id = payload.id;
  256. else params.forUsername = payload.username;
  257. YouTubeModule.runJob(
  258. "API_GET_CHANNELS",
  259. {
  260. params
  261. },
  262. this
  263. )
  264. .then(({ response }) => {
  265. const { data } = response;
  266. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  267. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  268. return resolve({ playlistId });
  269. })
  270. .catch(err => {
  271. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  272. if (err.message === "Request failed with status code 404") {
  273. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  274. }
  275. return reject(new Error("An error has occured. Please try again later."));
  276. });
  277. });
  278. }
  279. /**
  280. * Gets the id of the channel from the custom URL
  281. *
  282. * @param {object} payload - object that contains the payload
  283. * @param {string} payload.customUrl - the customUrl of the YouTube channel
  284. * @returns {Promise} - returns promise (reject, resolve)
  285. */
  286. GET_CHANNEL_ID_FROM_CUSTOM_URL(payload) {
  287. return new Promise((resolve, reject) => {
  288. async.waterfall(
  289. [
  290. next => {
  291. const params = {
  292. part: "snippet",
  293. type: "channel",
  294. maxResults: 50
  295. };
  296. params.q = payload.customUrl;
  297. YouTubeModule.runJob(
  298. "API_SEARCH",
  299. {
  300. params
  301. },
  302. this
  303. )
  304. .then(({ response }) => {
  305. const { data } = response;
  306. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  307. const channelIds = data.items.map(item => item.id.channelId);
  308. return next(null, channelIds);
  309. })
  310. .catch(err => {
  311. next(err);
  312. });
  313. },
  314. (channelIds, next) => {
  315. const params = {
  316. part: "snippet",
  317. id: channelIds.join(","),
  318. maxResults: 50
  319. };
  320. YouTubeModule.runJob(
  321. "API_GET_CHANNELS",
  322. {
  323. params
  324. },
  325. this
  326. )
  327. .then(({ response }) => {
  328. const { data } = response;
  329. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  330. let channelId = null;
  331. for (const item of data.items) {
  332. if (
  333. item.snippet.customUrl &&
  334. item.snippet.customUrl.toLowerCase() === payload.customUrl.toLowerCase()
  335. ) {
  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. (err, channelId) => {
  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()}): ${songs.length
  389. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  390. );
  391. next(null, nextPageToken !== undefined);
  392. },
  393. next => {
  394. // Add 250ms delay between each job request
  395. setTimeout(() => {
  396. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  397. .then(response => {
  398. songs = songs.concat(response.songs);
  399. nextPageToken = response.nextPageToken;
  400. next();
  401. })
  402. .catch(err => next(err));
  403. }, 250);
  404. },
  405. err => next(err, songs)
  406. );
  407. },
  408. (songs, next) =>
  409. next(
  410. null,
  411. songs.map(song => song.contentDetails.videoId)
  412. ),
  413. (songs, next) => {
  414. if (!payload.musicOnly) return next(true, { songs });
  415. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  416. .then(filteredSongs => next(null, { filteredSongs, songs }))
  417. .catch(next);
  418. }
  419. ],
  420. (err, response) => {
  421. if (err && err !== true) {
  422. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  423. reject(new Error(err.message));
  424. } else {
  425. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  426. }
  427. }
  428. );
  429. });
  430. }
  431. /**
  432. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL.
  433. *
  434. * @param {object} payload - object that contains the payload
  435. * @param {boolean} payload.playlistId - the playlist id to get videos from
  436. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  437. * @param {string} payload.url - the url of the YouTube playlist
  438. * @returns {Promise} - returns promise (reject, resolve)
  439. */
  440. GET_PLAYLIST_PAGE(payload) {
  441. return new Promise((resolve, reject) => {
  442. const params = {
  443. part: "contentDetails",
  444. playlistId: payload.playlistId,
  445. maxResults: 50
  446. };
  447. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  448. YouTubeModule.runJob(
  449. "API_GET_PLAYLIST_ITEMS",
  450. {
  451. params
  452. },
  453. this
  454. )
  455. .then(({ response }) => {
  456. const { data } = response;
  457. const songs = data.items;
  458. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  459. return resolve({ songs });
  460. })
  461. .catch(err => {
  462. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  463. if (err.message === "Request failed with status code 404") {
  464. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  465. }
  466. return reject(new Error("An error has occured. Please try again later."));
  467. });
  468. });
  469. }
  470. /**
  471. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  472. *
  473. * @param {object} payload - object that contains the payload
  474. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  475. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  476. * @returns {Promise} - returns promise (reject, resolve)
  477. */
  478. FILTER_MUSIC_VIDEOS(payload) {
  479. return new Promise((resolve, reject) => {
  480. const page = payload.page ? payload.page : 0;
  481. const videosPerPage = 50;
  482. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  483. if (localVideoIds.length === 0) {
  484. resolve({ videoIds: [] });
  485. return;
  486. }
  487. const params = {
  488. part: "topicDetails",
  489. id: localVideoIds.join(","),
  490. maxResults: videosPerPage
  491. };
  492. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  493. .then(({ response }) => {
  494. const { data } = response;
  495. const videoIds = [];
  496. data.items.forEach(item => {
  497. const videoId = item.id;
  498. if (!item.topicDetails) return;
  499. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  500. videoIds.push(videoId);
  501. });
  502. return YouTubeModule.runJob(
  503. "FILTER_MUSIC_VIDEOS",
  504. { videoIds: payload.videoIds, page: page + 1 },
  505. this
  506. )
  507. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  508. .catch(err => reject(err));
  509. })
  510. .catch(err => {
  511. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  512. return reject(new Error("Failed to find playlist from YouTube"));
  513. });
  514. });
  515. }
  516. /**
  517. * Returns an array of songs taken from a YouTube channel
  518. *
  519. * @param {object} payload - object that contains the payload
  520. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  521. * @param {string} payload.url - the url of the YouTube channel
  522. * @returns {Promise} - returns promise (reject, resolve)
  523. */
  524. GET_CHANNEL(payload) {
  525. return new Promise((resolve, reject) => {
  526. const regex =
  527. /\.[\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];
  537. const channelUsernameOrCustomUrl = splitQuery[4];
  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) payload.username = channelUsername;
  548. else return next(null, true, null);
  549. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  550. .then(({ playlistId }) => {
  551. next(null, false, playlistId);
  552. })
  553. .catch(err => {
  554. if (err.message === "Channel not found. Is the channel public/unlisted?") next(null, true, null);
  555. else next(err);
  556. });
  557. },
  558. (getUsernameFromCustomUrl, playlistId, next) => {
  559. if (!getUsernameFromCustomUrl) return next(null, playlistId);
  560. const payload = {};
  561. if (channelCustomUrl) payload.customUrl = channelCustomUrl;
  562. else if (channelUsernameOrCustomUrl) payload.customUrl = channelUsernameOrCustomUrl;
  563. else next("No proper URL provided.");
  564. YouTubeModule.runJob("GET_CHANNEL_ID_FROM_CUSTOM_URL", payload, this)
  565. .then(({ channelId }) => {
  566. YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", { id: channelId }, this)
  567. .then(({ playlistId }) => {
  568. next(null, playlistId);
  569. })
  570. .catch(err => next(err));
  571. })
  572. .catch(err => next(err));
  573. },
  574. (playlistId, next) => {
  575. let songs = [];
  576. let nextPageToken = "";
  577. async.whilst(
  578. next => {
  579. YouTubeModule.log(
  580. "INFO",
  581. `Getting channel progress for job (${this.toString()}): ${songs.length
  582. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  583. );
  584. next(null, nextPageToken !== undefined);
  585. },
  586. next => {
  587. // Add 250ms delay between each job request
  588. setTimeout(() => {
  589. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  590. .then(response => {
  591. songs = songs.concat(response.songs);
  592. nextPageToken = response.nextPageToken;
  593. next();
  594. })
  595. .catch(err => next(err));
  596. }, 250);
  597. },
  598. err => next(err, songs)
  599. );
  600. },
  601. (songs, next) =>
  602. next(
  603. null,
  604. songs.map(song => song.contentDetails.videoId)
  605. ),
  606. (songs, next) => {
  607. if (!payload.musicOnly) return next(true, { songs });
  608. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  609. .then(filteredSongs => next(null, { filteredSongs, songs }))
  610. .catch(next);
  611. }
  612. ],
  613. (err, response) => {
  614. if (err && err !== true) {
  615. YouTubeModule.log("ERROR", "GET_CHANNEL", "Some error has occurred.", err.message);
  616. reject(new Error(err.message));
  617. } else {
  618. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  619. }
  620. }
  621. );
  622. });
  623. }
  624. API_GET_VIDEOS(payload) {
  625. return new Promise((resolve, reject) => {
  626. const { params } = payload;
  627. YouTubeModule.runJob(
  628. "API_CALL",
  629. {
  630. url: "https://www.googleapis.com/youtube/v3/videos",
  631. params: {
  632. key: config.get("apis.youtube.key"),
  633. ...params
  634. },
  635. quotaCost: 1
  636. },
  637. this
  638. )
  639. .then(response => {
  640. resolve(response);
  641. })
  642. .catch(err => {
  643. reject(err);
  644. });
  645. });
  646. }
  647. API_GET_PLAYLIST_ITEMS(payload) {
  648. return new Promise((resolve, reject) => {
  649. const { params } = payload;
  650. YouTubeModule.runJob(
  651. "API_CALL",
  652. {
  653. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  654. params: {
  655. key: config.get("apis.youtube.key"),
  656. ...params
  657. },
  658. quotaCost: 1
  659. },
  660. this
  661. )
  662. .then(response => {
  663. resolve(response);
  664. })
  665. .catch(err => {
  666. reject(err);
  667. });
  668. });
  669. }
  670. API_GET_CHANNELS(payload) {
  671. return new Promise((resolve, reject) => {
  672. const { params } = payload;
  673. YouTubeModule.runJob(
  674. "API_CALL",
  675. {
  676. url: "https://www.googleapis.com/youtube/v3/channels",
  677. params: {
  678. key: config.get("apis.youtube.key"),
  679. ...params
  680. },
  681. quotaCost: 1
  682. },
  683. this
  684. )
  685. .then(response => {
  686. resolve(response);
  687. })
  688. .catch(err => {
  689. reject(err);
  690. });
  691. });
  692. }
  693. API_SEARCH(payload) {
  694. return new Promise((resolve, reject) => {
  695. const { params } = payload;
  696. YouTubeModule.runJob(
  697. "API_CALL",
  698. {
  699. url: "https://www.googleapis.com/youtube/v3/search",
  700. params: {
  701. key: config.get("apis.youtube.key"),
  702. ...params
  703. },
  704. quotaCost: 100
  705. },
  706. this
  707. )
  708. .then(response => {
  709. resolve(response);
  710. })
  711. .catch(err => {
  712. reject(err);
  713. });
  714. });
  715. }
  716. API_CALL(payload) {
  717. return new Promise((resolve, reject) => {
  718. const { url, params, quotaCost } = payload;
  719. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  720. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  721. else {
  722. const youtubeApiRequest = new YouTubeModule.YoutubeApiRequestModel({
  723. url,
  724. date: Date.now(),
  725. quotaCost
  726. });
  727. youtubeApiRequest.save();
  728. const { key, ...keylessParams } = payload.params;
  729. CacheModule.runJob(
  730. "HSET",
  731. {
  732. table: "youtubeApiRequestParams",
  733. key: youtubeApiRequest._id.toString(),
  734. value: JSON.stringify(keylessParams)
  735. },
  736. this
  737. ).then();
  738. YouTubeModule.apiCalls.push({ date: youtubeApiRequest.date, quotaCost });
  739. YouTubeModule.axios
  740. .get(url, {
  741. params,
  742. timeout: YouTubeModule.requestTimeout
  743. })
  744. .then(response => {
  745. if (response.data.error) {
  746. reject(new Error(response.data.error));
  747. } else {
  748. CacheModule.runJob(
  749. "HSET",
  750. {
  751. table: "youtubeApiRequestResults",
  752. key: youtubeApiRequest._id.toString(),
  753. value: JSON.stringify(response.data)
  754. },
  755. this
  756. ).then();
  757. resolve({ response });
  758. }
  759. })
  760. .catch(err => {
  761. reject(err);
  762. });
  763. }
  764. });
  765. }
  766. GET_API_REQUESTS(payload) {
  767. return new Promise((resolve, reject) => {
  768. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  769. YouTubeModule.youtubeApiRequestModel
  770. .find({ date: { $lte: fromDate } })
  771. .sort({ date: -1 })
  772. .exec((err, youtubeApiRequests) => {
  773. if (err) reject(new Error("Couldn't load YouTube API requests."));
  774. else {
  775. resolve({ apiRequests: youtubeApiRequests });
  776. }
  777. });
  778. });
  779. }
  780. GET_API_REQUEST(payload) {
  781. return new Promise((resolve, reject) => {
  782. const { apiRequestId } = payload;
  783. async.waterfall(
  784. [
  785. next => {
  786. YouTubeModule.youtubeApiRequestModel
  787. .findOne({ _id: apiRequestId })
  788. .exec(next);
  789. },
  790. (apiRequest, next) => {
  791. CacheModule.runJob(
  792. "HGET",
  793. {
  794. table: "youtubeApiRequestParams",
  795. key: apiRequestId.toString()
  796. },
  797. this
  798. ).then(apiRequestParams => {
  799. next(null, {
  800. ...apiRequest._doc,
  801. params: apiRequestParams
  802. });
  803. }
  804. ).catch(err => next(err));
  805. },
  806. (apiRequest, next) => {
  807. CacheModule.runJob(
  808. "HGET",
  809. {
  810. table: "youtubeApiRequestResults",
  811. key: apiRequestId.toString()
  812. },
  813. this
  814. ).then(apiRequestResults => {
  815. next(null, {
  816. ...apiRequest,
  817. results: apiRequestResults
  818. });
  819. }).catch(err => next(err));
  820. }
  821. ],
  822. (err, apiRequest) => {
  823. if (err) reject(new Error(err));
  824. else resolve({ apiRequest });
  825. }
  826. );
  827. });
  828. }
  829. RESET_STORED_API_REQUESTS(payload) {
  830. return new Promise((resolve, reject) => {
  831. async.waterfall(
  832. [
  833. next => {
  834. YouTubeModule.youtubeApiRequestModel.deleteMany({}, err => {
  835. if (err) next("Couldn't reset stored YouTube API requests.");
  836. else {
  837. next();
  838. }
  839. });
  840. },
  841. next => {
  842. CacheModule.runJob(
  843. "DEL",
  844. {key: "youtubeApiRequestParams"},
  845. this
  846. ).then(next).catch(err => next(err));
  847. },
  848. next => {
  849. CacheModule.runJob(
  850. "DEL",
  851. {key: "youtubeApiRequestResults"},
  852. this
  853. ).then(next).catch(err => next(err));
  854. }
  855. ],
  856. err => {
  857. if (err) reject(new Error(err));
  858. else resolve();
  859. }
  860. );
  861. });
  862. }
  863. REMOVE_STORED_API_REQUEST(payload) {
  864. return new Promise((resolve, reject) => {
  865. async.waterfall(
  866. [
  867. next => {
  868. YouTubeModule.youtubeApiRequestModel.deleteOne({_id: payload.requestId}, err => {
  869. if (err) next("Couldn't remove stored YouTube API request.");
  870. else {
  871. next();
  872. }
  873. });
  874. },
  875. next => {
  876. CacheModule.runJob(
  877. "HDEL",
  878. {
  879. table: "youtubeApiRequestParams",
  880. key: payload.requestId.toString()
  881. },
  882. this
  883. ).then(next).catch(err => next(err));
  884. },
  885. next => {
  886. CacheModule.runJob(
  887. "HDEL",
  888. {
  889. table: "youtubeApiRequestResults",
  890. key: payload.requestId.toString()
  891. },
  892. this
  893. ).then(next).catch(err => next(err));
  894. }
  895. ],
  896. err => {
  897. if (err) reject(new Error(err));
  898. else resolve();
  899. }
  900. );
  901. });
  902. }
  903. }
  904. export default new _YouTubeModule();