youtube.js 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. * @param {string} payload.createMissing - attempt to fetch and create video if not in db
  941. * @returns {Promise} - returns a promise (resolve, reject)
  942. */
  943. GET_VIDEO(payload) {
  944. return new Promise((resolve, reject) => {
  945. async.waterfall(
  946. [
  947. next => {
  948. const query = mongoose.Types.ObjectId.isValid(payload.identifier) ?
  949. { _id: payload.identifier } :
  950. { youtubeId: payload.identifier };
  951. return YouTubeModule.youtubeVideoModel.findOne(query, next);
  952. },
  953. (video, next) => {
  954. if (video) return next(null, video, false);
  955. if (mongoose.Types.ObjectId.isValid(payload.identifier) || !payload.createMissing) return next("YouTube video not found.");
  956. return YouTubeModule.runJob("GET_SONG", { youtubeId: payload.identifier }, this)
  957. .then(response => next(null, false, response.song))
  958. .catch(next);
  959. },
  960. (video, youtubeVideo, next) => {
  961. if (video) return next(null, video);
  962. return YouTubeModule.runJob("CREATE_VIDEOS", { youtubeVideos: youtubeVideo }, this)
  963. .then(res => {
  964. if (res.youtubeVideos.length === 1) next(null, res.youtubeVideos[0])
  965. else next("YouTube video not found.")
  966. })
  967. .catch(next);
  968. }
  969. ],
  970. (err, video) => {
  971. if (err) reject(new Error(err));
  972. else resolve({ video });
  973. }
  974. )
  975. });
  976. }
  977. /**
  978. * Remove YouTube videos
  979. *
  980. * @param {object} payload - an object containing the payload
  981. * @param {string} payload.videoIds - Array of youtubeVideo ObjectIds
  982. * @returns {Promise} - returns a promise (resolve, reject)
  983. */
  984. REMOVE_VIDEOS(payload) {
  985. return new Promise((resolve, reject) => {
  986. async.waterfall(
  987. [
  988. next => {
  989. let videoIds = payload.videoIds;
  990. if (!Array.isArray(videoIds)) videoIds = [videoIds];
  991. if (!videoIds.every(videoId => mongoose.Types.ObjectId.isValid(videoId)))
  992. next("One or more videoIds are not a valid ObjectId.");
  993. else {
  994. YouTubeModule.youtubeVideoModel.deleteMany({_id: { $in: videoIds }}, next);
  995. }
  996. }
  997. ],
  998. err => {
  999. if (err) reject(new Error(err));
  1000. else resolve();
  1001. }
  1002. )
  1003. });
  1004. }
  1005. }
  1006. export default new _YouTubeModule();