youtube.js 27 KB

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