youtube.js 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199
  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 id of the channel upload playlist
  196. *
  197. * @param {object} payload - object that contains the payload
  198. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  199. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  200. * @returns {Promise} - returns promise (reject, resolve)
  201. */
  202. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  203. return new Promise((resolve, reject) => {
  204. const params = {
  205. part: "id,contentDetails"
  206. };
  207. if (payload.id) params.id = payload.id;
  208. else params.forUsername = payload.username;
  209. YouTubeModule.runJob(
  210. "API_GET_CHANNELS",
  211. {
  212. params
  213. },
  214. this
  215. )
  216. .then(({ response }) => {
  217. const { data } = response;
  218. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  219. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  220. return resolve({ playlistId });
  221. })
  222. .catch(err => {
  223. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  224. if (err.message === "Request failed with status code 404") {
  225. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  226. }
  227. return reject(new Error("An error has occured. Please try again later."));
  228. });
  229. });
  230. }
  231. /**
  232. * Gets the id of the channel from the custom URL
  233. *
  234. * @param {object} payload - object that contains the payload
  235. * @param {string} payload.customUrl - the customUrl of the YouTube channel
  236. * @returns {Promise} - returns promise (reject, resolve)
  237. */
  238. GET_CHANNEL_ID_FROM_CUSTOM_URL(payload) {
  239. return new Promise((resolve, reject) => {
  240. async.waterfall(
  241. [
  242. next => {
  243. const params = {
  244. part: "snippet",
  245. type: "channel",
  246. maxResults: 50
  247. };
  248. params.q = payload.customUrl;
  249. YouTubeModule.runJob(
  250. "API_SEARCH",
  251. {
  252. params
  253. },
  254. this
  255. )
  256. .then(({ response }) => {
  257. const { data } = response;
  258. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  259. const channelIds = data.items.map(item => item.id.channelId);
  260. return next(null, channelIds);
  261. })
  262. .catch(err => {
  263. next(err);
  264. });
  265. },
  266. (channelIds, next) => {
  267. const params = {
  268. part: "snippet",
  269. id: channelIds.join(","),
  270. maxResults: 50
  271. };
  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 next("Channel not found.");
  282. let channelId = null;
  283. for (const item of data.items) {
  284. if (
  285. item.snippet.customUrl &&
  286. item.snippet.customUrl.toLowerCase() === payload.customUrl.toLowerCase()
  287. ) {
  288. channelId = item.id;
  289. break;
  290. }
  291. }
  292. if (!channelId) return next("Channel not found.");
  293. return next(null, channelId);
  294. })
  295. .catch(err => {
  296. next(err);
  297. });
  298. }
  299. ],
  300. (err, channelId) => {
  301. if (err) {
  302. YouTubeModule.log("ERROR", "GET_CHANNEL_ID_FROM_CUSTOM_URL", `${err.message}`);
  303. if (err.message === "Request failed with status code 404") {
  304. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  305. }
  306. return reject(new Error("An error has occured. Please try again later."));
  307. }
  308. return resolve({ channelId });
  309. }
  310. );
  311. });
  312. }
  313. /**
  314. * Returns an array of songs taken from a YouTube playlist
  315. *
  316. * @param {object} payload - object that contains the payload
  317. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  318. * @param {string} payload.url - the url of the YouTube playlist
  319. * @returns {Promise} - returns promise (reject, resolve)
  320. */
  321. GET_PLAYLIST(payload) {
  322. return new Promise((resolve, reject) => {
  323. const regex = /[\\?&]list=([^&#]*)/;
  324. const splitQuery = regex.exec(payload.url);
  325. if (!splitQuery) {
  326. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  327. reject(new Error("Invalid playlist URL."));
  328. return;
  329. }
  330. const playlistId = splitQuery[1];
  331. async.waterfall(
  332. [
  333. next => {
  334. let songs = [];
  335. let nextPageToken = "";
  336. async.whilst(
  337. next => {
  338. YouTubeModule.log(
  339. "INFO",
  340. `Getting playlist progress for job (${this.toString()}): ${songs.length
  341. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  342. );
  343. next(null, nextPageToken !== undefined);
  344. },
  345. next => {
  346. // Add 250ms delay between each job request
  347. setTimeout(() => {
  348. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  349. .then(response => {
  350. songs = songs.concat(response.songs);
  351. nextPageToken = response.nextPageToken;
  352. next();
  353. })
  354. .catch(err => next(err));
  355. }, 250);
  356. },
  357. err => next(err, songs)
  358. );
  359. },
  360. (songs, next) =>
  361. next(
  362. null,
  363. songs.map(song => song.contentDetails.videoId)
  364. ),
  365. (songs, next) => {
  366. if (!payload.musicOnly) return next(true, { songs });
  367. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  368. .then(filteredSongs => next(null, { filteredSongs, songs }))
  369. .catch(next);
  370. }
  371. ],
  372. (err, response) => {
  373. if (err && err !== true) {
  374. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  375. reject(new Error(err.message));
  376. } else {
  377. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  378. }
  379. }
  380. );
  381. });
  382. }
  383. /**
  384. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL.
  385. *
  386. * @param {object} payload - object that contains the payload
  387. * @param {boolean} payload.playlistId - the playlist id to get videos from
  388. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  389. * @param {string} payload.url - the url of the YouTube playlist
  390. * @returns {Promise} - returns promise (reject, resolve)
  391. */
  392. GET_PLAYLIST_PAGE(payload) {
  393. return new Promise((resolve, reject) => {
  394. const params = {
  395. part: "contentDetails",
  396. playlistId: payload.playlistId,
  397. maxResults: 50
  398. };
  399. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  400. YouTubeModule.runJob(
  401. "API_GET_PLAYLIST_ITEMS",
  402. {
  403. params
  404. },
  405. this
  406. )
  407. .then(({ response }) => {
  408. const { data } = response;
  409. const songs = data.items;
  410. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  411. return resolve({ songs });
  412. })
  413. .catch(err => {
  414. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  415. if (err.message === "Request failed with status code 404") {
  416. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  417. }
  418. return reject(new Error("An error has occured. Please try again later."));
  419. });
  420. });
  421. }
  422. /**
  423. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  424. *
  425. * @param {object} payload - object that contains the payload
  426. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  427. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  428. * @returns {Promise} - returns promise (reject, resolve)
  429. */
  430. FILTER_MUSIC_VIDEOS(payload) {
  431. return new Promise((resolve, reject) => {
  432. const page = payload.page ? payload.page : 0;
  433. const videosPerPage = 50;
  434. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  435. if (localVideoIds.length === 0) {
  436. resolve({ videoIds: [] });
  437. return;
  438. }
  439. const params = {
  440. part: "topicDetails",
  441. id: localVideoIds.join(","),
  442. maxResults: videosPerPage
  443. };
  444. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  445. .then(({ response }) => {
  446. const { data } = response;
  447. const videoIds = [];
  448. data.items.forEach(item => {
  449. const videoId = item.id;
  450. if (!item.topicDetails) return;
  451. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  452. videoIds.push(videoId);
  453. });
  454. return YouTubeModule.runJob(
  455. "FILTER_MUSIC_VIDEOS",
  456. { videoIds: payload.videoIds, page: page + 1 },
  457. this
  458. )
  459. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  460. .catch(err => reject(err));
  461. })
  462. .catch(err => {
  463. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  464. return reject(new Error("Failed to find playlist from YouTube"));
  465. });
  466. });
  467. }
  468. /**
  469. * Returns an array of songs taken from a YouTube channel
  470. *
  471. * @param {object} payload - object that contains the payload
  472. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  473. * @param {string} payload.url - the url of the YouTube channel
  474. * @returns {Promise} - returns promise (reject, resolve)
  475. */
  476. GET_CHANNEL(payload) {
  477. return new Promise((resolve, reject) => {
  478. const regex =
  479. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  480. const splitQuery = regex.exec(payload.url);
  481. if (!splitQuery) {
  482. YouTubeModule.log("ERROR", "GET_CHANNEL", "Invalid YouTube channel URL query.");
  483. reject(new Error("Invalid playlist URL."));
  484. return;
  485. }
  486. const channelId = splitQuery[1];
  487. const channelUsername = splitQuery[2];
  488. const channelCustomUrl = splitQuery[3];
  489. const channelUsernameOrCustomUrl = splitQuery[4];
  490. console.log(`Channel id: ${channelId}`);
  491. console.log(`Channel username: ${channelUsername}`);
  492. console.log(`Channel custom URL: ${channelCustomUrl}`);
  493. console.log(`Channel username or custom URL: ${channelUsernameOrCustomUrl}`);
  494. async.waterfall(
  495. [
  496. next => {
  497. const payload = {};
  498. if (channelId) payload.id = channelId;
  499. else if (channelUsername) payload.username = channelUsername;
  500. else return next(null, true, null);
  501. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  502. .then(({ playlistId }) => {
  503. next(null, false, playlistId);
  504. })
  505. .catch(err => {
  506. if (err.message === "Channel not found. Is the channel public/unlisted?") next(null, true, null);
  507. else next(err);
  508. });
  509. },
  510. (getUsernameFromCustomUrl, playlistId, next) => {
  511. if (!getUsernameFromCustomUrl) return next(null, playlistId);
  512. const payload = {};
  513. if (channelCustomUrl) payload.customUrl = channelCustomUrl;
  514. else if (channelUsernameOrCustomUrl) payload.customUrl = channelUsernameOrCustomUrl;
  515. else next("No proper URL provided.");
  516. YouTubeModule.runJob("GET_CHANNEL_ID_FROM_CUSTOM_URL", payload, this)
  517. .then(({ channelId }) => {
  518. YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", { id: channelId }, this)
  519. .then(({ playlistId }) => {
  520. next(null, playlistId);
  521. })
  522. .catch(err => next(err));
  523. })
  524. .catch(err => next(err));
  525. },
  526. (playlistId, next) => {
  527. let songs = [];
  528. let nextPageToken = "";
  529. async.whilst(
  530. next => {
  531. YouTubeModule.log(
  532. "INFO",
  533. `Getting channel progress for job (${this.toString()}): ${songs.length
  534. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  535. );
  536. next(null, nextPageToken !== undefined);
  537. },
  538. next => {
  539. // Add 250ms delay between each job request
  540. setTimeout(() => {
  541. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  542. .then(response => {
  543. songs = songs.concat(response.songs);
  544. nextPageToken = response.nextPageToken;
  545. next();
  546. })
  547. .catch(err => next(err));
  548. }, 250);
  549. },
  550. err => next(err, songs)
  551. );
  552. },
  553. (songs, next) =>
  554. next(
  555. null,
  556. songs.map(song => song.contentDetails.videoId)
  557. ),
  558. (songs, next) => {
  559. if (!payload.musicOnly) return next(true, { songs });
  560. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  561. .then(filteredSongs => next(null, { filteredSongs, songs }))
  562. .catch(next);
  563. }
  564. ],
  565. (err, response) => {
  566. if (err && err !== true) {
  567. YouTubeModule.log("ERROR", "GET_CHANNEL", "Some error has occurred.", err.message);
  568. reject(new Error(err.message));
  569. } else {
  570. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  571. }
  572. }
  573. );
  574. });
  575. }
  576. API_GET_VIDEOS(payload) {
  577. return new Promise((resolve, reject) => {
  578. const { params } = payload;
  579. YouTubeModule.runJob(
  580. "API_CALL",
  581. {
  582. url: "https://www.googleapis.com/youtube/v3/videos",
  583. params: {
  584. key: config.get("apis.youtube.key"),
  585. ...params
  586. },
  587. quotaCost: 1
  588. },
  589. this
  590. )
  591. .then(response => {
  592. resolve(response);
  593. })
  594. .catch(err => {
  595. reject(err);
  596. });
  597. });
  598. }
  599. API_GET_PLAYLIST_ITEMS(payload) {
  600. return new Promise((resolve, reject) => {
  601. const { params } = payload;
  602. YouTubeModule.runJob(
  603. "API_CALL",
  604. {
  605. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  606. params: {
  607. key: config.get("apis.youtube.key"),
  608. ...params
  609. },
  610. quotaCost: 1
  611. },
  612. this
  613. )
  614. .then(response => {
  615. resolve(response);
  616. })
  617. .catch(err => {
  618. reject(err);
  619. });
  620. });
  621. }
  622. API_GET_CHANNELS(payload) {
  623. return new Promise((resolve, reject) => {
  624. const { params } = payload;
  625. YouTubeModule.runJob(
  626. "API_CALL",
  627. {
  628. url: "https://www.googleapis.com/youtube/v3/channels",
  629. params: {
  630. key: config.get("apis.youtube.key"),
  631. ...params
  632. },
  633. quotaCost: 1
  634. },
  635. this
  636. )
  637. .then(response => {
  638. resolve(response);
  639. })
  640. .catch(err => {
  641. reject(err);
  642. });
  643. });
  644. }
  645. API_SEARCH(payload) {
  646. return new Promise((resolve, reject) => {
  647. const { params } = payload;
  648. YouTubeModule.runJob(
  649. "API_CALL",
  650. {
  651. url: "https://www.googleapis.com/youtube/v3/search",
  652. params: {
  653. key: config.get("apis.youtube.key"),
  654. ...params
  655. },
  656. quotaCost: 100
  657. },
  658. this
  659. )
  660. .then(response => {
  661. resolve(response);
  662. })
  663. .catch(err => {
  664. reject(err);
  665. });
  666. });
  667. }
  668. API_CALL(payload) {
  669. return new Promise((resolve, reject) => {
  670. const { url, params, quotaCost } = payload;
  671. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  672. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  673. else {
  674. const youtubeApiRequest = new YouTubeModule.YoutubeApiRequestModel({
  675. url,
  676. date: Date.now(),
  677. quotaCost
  678. });
  679. youtubeApiRequest.save();
  680. const { key, ...keylessParams } = payload.params;
  681. CacheModule.runJob(
  682. "HSET",
  683. {
  684. table: "youtubeApiRequestParams",
  685. key: youtubeApiRequest._id.toString(),
  686. value: JSON.stringify(keylessParams)
  687. },
  688. this
  689. ).then();
  690. YouTubeModule.apiCalls.push({ date: youtubeApiRequest.date, quotaCost });
  691. YouTubeModule.axios
  692. .get(url, {
  693. params,
  694. timeout: YouTubeModule.requestTimeout
  695. })
  696. .then(response => {
  697. if (response.data.error) {
  698. reject(new Error(response.data.error));
  699. } else {
  700. CacheModule.runJob(
  701. "HSET",
  702. {
  703. table: "youtubeApiRequestResults",
  704. key: youtubeApiRequest._id.toString(),
  705. value: JSON.stringify(response.data)
  706. },
  707. this
  708. ).then();
  709. resolve({ response });
  710. }
  711. })
  712. .catch(err => {
  713. reject(err);
  714. });
  715. }
  716. });
  717. }
  718. GET_API_REQUESTS(payload) {
  719. return new Promise((resolve, reject) => {
  720. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  721. YouTubeModule.youtubeApiRequestModel
  722. .find({ date: { $lte: fromDate } })
  723. .sort({ date: -1 })
  724. .exec((err, youtubeApiRequests) => {
  725. if (err) reject(new Error("Couldn't load YouTube API requests."));
  726. else {
  727. resolve({ apiRequests: youtubeApiRequests });
  728. }
  729. });
  730. });
  731. }
  732. GET_API_REQUEST(payload) {
  733. return new Promise((resolve, reject) => {
  734. const { apiRequestId } = payload;
  735. async.waterfall(
  736. [
  737. next => {
  738. YouTubeModule.youtubeApiRequestModel
  739. .findOne({ _id: apiRequestId })
  740. .exec(next);
  741. },
  742. (apiRequest, next) => {
  743. CacheModule.runJob(
  744. "HGET",
  745. {
  746. table: "youtubeApiRequestParams",
  747. key: apiRequestId.toString()
  748. },
  749. this
  750. ).then(apiRequestParams => {
  751. next(null, {
  752. ...apiRequest._doc,
  753. params: apiRequestParams
  754. });
  755. }
  756. ).catch(err => next(err));
  757. },
  758. (apiRequest, next) => {
  759. CacheModule.runJob(
  760. "HGET",
  761. {
  762. table: "youtubeApiRequestResults",
  763. key: apiRequestId.toString()
  764. },
  765. this
  766. ).then(apiRequestResults => {
  767. next(null, {
  768. ...apiRequest,
  769. results: apiRequestResults
  770. });
  771. }).catch(err => next(err));
  772. }
  773. ],
  774. (err, apiRequest) => {
  775. if (err) reject(new Error(err));
  776. else resolve({ apiRequest });
  777. }
  778. );
  779. });
  780. }
  781. RESET_STORED_API_REQUESTS(payload) {
  782. return new Promise((resolve, reject) => {
  783. async.waterfall(
  784. [
  785. next => {
  786. YouTubeModule.youtubeApiRequestModel.deleteMany({}, err => {
  787. if (err) next("Couldn't reset stored YouTube API requests.");
  788. else {
  789. next();
  790. }
  791. });
  792. },
  793. next => {
  794. CacheModule.runJob(
  795. "DEL",
  796. {key: "youtubeApiRequestParams"},
  797. this
  798. ).then(next).catch(err => next(err));
  799. },
  800. next => {
  801. CacheModule.runJob(
  802. "DEL",
  803. {key: "youtubeApiRequestResults"},
  804. this
  805. ).then(next).catch(err => next(err));
  806. }
  807. ],
  808. err => {
  809. if (err) reject(new Error(err));
  810. else resolve();
  811. }
  812. );
  813. });
  814. }
  815. REMOVE_STORED_API_REQUEST(payload) {
  816. return new Promise((resolve, reject) => {
  817. async.waterfall(
  818. [
  819. next => {
  820. YouTubeModule.youtubeApiRequestModel.deleteOne({_id: payload.requestId}, err => {
  821. if (err) next("Couldn't remove stored YouTube API request.");
  822. else {
  823. next();
  824. }
  825. });
  826. },
  827. next => {
  828. CacheModule.runJob(
  829. "HDEL",
  830. {
  831. table: "youtubeApiRequestParams",
  832. key: payload.requestId.toString()
  833. },
  834. this
  835. ).then(next).catch(err => next(err));
  836. },
  837. next => {
  838. CacheModule.runJob(
  839. "HDEL",
  840. {
  841. table: "youtubeApiRequestResults",
  842. key: payload.requestId.toString()
  843. },
  844. this
  845. ).then(next).catch(err => next(err));
  846. }
  847. ],
  848. err => {
  849. if (err) reject(new Error(err));
  850. else resolve();
  851. }
  852. );
  853. });
  854. }
  855. /**
  856. * Create YouTube videos
  857. *
  858. * @param {object} payload - an object containing the payload
  859. * @param {string} payload.youtubeVideos - the youtubeVideo object or array of
  860. * @returns {Promise} - returns a promise (resolve, reject)
  861. */
  862. CREATE_VIDEOS(payload) {
  863. return new Promise((resolve, reject) => {
  864. async.waterfall(
  865. [
  866. next => {
  867. let youtubeVideos = payload.youtubeVideos;
  868. if (typeof youtubeVideos !== "object") next("Invalid youtubeVideos type");
  869. else {
  870. if (!Array.isArray(youtubeVideos)) youtubeVideos = [youtubeVideos];
  871. YouTubeModule.youtubeVideoModel.insertMany(youtubeVideos, next);
  872. }
  873. }
  874. ],
  875. (err, youtubeVideos) => {
  876. if (err) reject(new Error(err));
  877. else resolve({ youtubeVideos });
  878. }
  879. )
  880. });
  881. }
  882. /**
  883. * Get YouTube video
  884. *
  885. * @param {object} payload - an object containing the payload
  886. * @param {string} payload.identifier - the youtube video ObjectId or YouTube ID
  887. * @param {string} payload.createMissing - attempt to fetch and create video if not in db
  888. * @returns {Promise} - returns a promise (resolve, reject)
  889. */
  890. GET_VIDEO(payload) {
  891. return new Promise((resolve, reject) => {
  892. async.waterfall(
  893. [
  894. next => {
  895. const query = mongoose.Types.ObjectId.isValid(payload.identifier) ?
  896. { _id: payload.identifier } :
  897. { youtubeId: payload.identifier };
  898. return YouTubeModule.youtubeVideoModel.findOne(query, next);
  899. },
  900. (video, next) => {
  901. if (video) return next(null, video, false);
  902. if (mongoose.Types.ObjectId.isValid(payload.identifier) || !payload.createMissing) return next("YouTube video not found.");
  903. const params = {
  904. part: "snippet,contentDetails,statistics,status",
  905. id: payload.identifier
  906. };
  907. return YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  908. .then(({ response }) => {
  909. const { data } = response;
  910. if (data.items[0] === undefined)
  911. return next("The specified video does not exist or cannot be publicly accessed.");
  912. // TODO Clean up duration converter
  913. let dur = data.items[0].contentDetails.duration;
  914. dur = dur.replace("PT", "");
  915. let duration = 0;
  916. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  917. v2 = Number(v2);
  918. duration = v2 * 60 * 60;
  919. return "";
  920. });
  921. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  922. v2 = Number(v2);
  923. duration += v2 * 60;
  924. return "";
  925. });
  926. // eslint-disable-next-line no-unused-vars
  927. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  928. v2 = Number(v2);
  929. duration += v2;
  930. return "";
  931. });
  932. const youtubeVideo = {
  933. youtubeId: data.items[0].id,
  934. title: data.items[0].snippet.title,
  935. author: data.items[0].snippet.channelTitle,
  936. thumbnail: data.items[0].snippet.thumbnails.default.url,
  937. duration
  938. };
  939. return next(null, false, youtubeVideo);
  940. })
  941. .catch(next);
  942. },
  943. (video, youtubeVideo, next) => {
  944. if (video) return next(null, video, true);
  945. return YouTubeModule.runJob("CREATE_VIDEOS", { youtubeVideos: youtubeVideo }, this)
  946. .then(res => {
  947. if (res.youtubeVideos.length === 1) next(null, res.youtubeVideos[0], false)
  948. else next("YouTube video not found.")
  949. })
  950. .catch(next);
  951. }
  952. ],
  953. (err, video, existing) => {
  954. if (err) reject(new Error(err));
  955. else resolve({ video, existing });
  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. * Request a set of YouTube videos
  990. *
  991. * @param {object} payload - an object containing the payload
  992. * @param {string} payload.url - the url of the the YouTube playlist or channel
  993. * @param {boolean} payload.musicOnly - whether to only get music from the playlist/channel
  994. * @param {boolean} payload.returnVideos - whether to return videos
  995. * @returns {Promise} - returns a promise (resolve, reject)
  996. */
  997. REQUEST_SET(payload) {
  998. return new Promise((resolve, reject) => {
  999. async.waterfall(
  1000. [
  1001. next => {
  1002. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1003. const channelRegex =
  1004. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1005. if (playlistRegex.exec(payload.url) || channelRegex.exec(payload.url))
  1006. YouTubeModule.runJob(
  1007. playlistRegex.exec(payload.url) ? "GET_PLAYLIST" : "GET_CHANNEL",
  1008. {
  1009. url: payload.url,
  1010. musicOnly: payload.musicOnly
  1011. },
  1012. this
  1013. )
  1014. .then(res => {
  1015. next(null, res.songs);
  1016. })
  1017. .catch(next);
  1018. else next("Invalid YouTube URL.");
  1019. },
  1020. (youtubeIds, next) => {
  1021. let successful = 0;
  1022. let videos = {};
  1023. let failed = 0;
  1024. let alreadyInDatabase = 0;
  1025. if (youtubeIds.length === 0) next();
  1026. async.eachOfLimit(
  1027. youtubeIds,
  1028. 1,
  1029. (youtubeId, index, next2) => {
  1030. YouTubeModule.runJob("GET_VIDEO", { identifier: youtubeId, createMissing: true }, this)
  1031. .then(res => {
  1032. successful += 1;
  1033. if (res.existing) alreadyInDatabase += 1;
  1034. if (res.video) videos[index] = res.video;
  1035. })
  1036. .catch(() => {
  1037. failed += 1;
  1038. })
  1039. .finally(() => {
  1040. next2();
  1041. });
  1042. },
  1043. () => {
  1044. if (payload.returnVideos)
  1045. videos = Object.keys(videos)
  1046. .sort()
  1047. .map(key => videos[key]);
  1048. next(null, { successful, failed, alreadyInDatabase, videos });
  1049. }
  1050. );
  1051. }
  1052. ],
  1053. (err, response) => {
  1054. if (err) reject(new Error(err));
  1055. else resolve(response);
  1056. }
  1057. )
  1058. });
  1059. }
  1060. }
  1061. export default new _YouTubeModule();