youtube.js 35 KB

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