youtube.js 37 KB

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