youtube.js 29 KB

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