youtube.js 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  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. RESET_STORED_API_REQUESTS(payload) {
  841. return new Promise((resolve, reject) => {
  842. async.waterfall(
  843. [
  844. next => {
  845. YouTubeModule.youtubeApiRequestModel.deleteMany({}, err => {
  846. if (err) next("Couldn't reset stored YouTube API requests.");
  847. else {
  848. next();
  849. }
  850. });
  851. },
  852. next => {
  853. CacheModule.runJob(
  854. "DEL",
  855. {key: "youtubeApiRequestParams"},
  856. this
  857. ).then(next).catch(err => next(err));
  858. },
  859. next => {
  860. CacheModule.runJob(
  861. "DEL",
  862. {key: "youtubeApiRequestResults"},
  863. this
  864. ).then(next).catch(err => next(err));
  865. }
  866. ],
  867. err => {
  868. if (err) reject(new Error(err));
  869. else resolve();
  870. }
  871. );
  872. });
  873. }
  874. REMOVE_STORED_API_REQUEST(payload) {
  875. return new Promise((resolve, reject) => {
  876. async.waterfall(
  877. [
  878. next => {
  879. YouTubeModule.youtubeApiRequestModel.deleteOne({_id: payload.requestId}, err => {
  880. if (err) next("Couldn't remove stored YouTube API request.");
  881. else {
  882. next();
  883. }
  884. });
  885. },
  886. next => {
  887. CacheModule.runJob(
  888. "HDEL",
  889. {
  890. table: "youtubeApiRequestParams",
  891. key: payload.requestId.toString()
  892. },
  893. this
  894. ).then(next).catch(err => next(err));
  895. },
  896. next => {
  897. CacheModule.runJob(
  898. "HDEL",
  899. {
  900. table: "youtubeApiRequestResults",
  901. key: payload.requestId.toString()
  902. },
  903. this
  904. ).then(next).catch(err => next(err));
  905. }
  906. ],
  907. err => {
  908. if (err) reject(new Error(err));
  909. else resolve();
  910. }
  911. );
  912. });
  913. }
  914. }
  915. export default new _YouTubeModule();