youtube.js 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602
  1. import mongoose from "mongoose";
  2. import async from "async";
  3. import config from "config";
  4. import * as rax from "retry-axios";
  5. import axios from "axios";
  6. import CoreClass from "../core";
  7. class RateLimitter {
  8. /**
  9. * Constructor
  10. *
  11. * @param {number} timeBetween - The time between each allowed YouTube request
  12. */
  13. constructor(timeBetween) {
  14. this.dateStarted = Date.now();
  15. this.timeBetween = timeBetween;
  16. }
  17. /**
  18. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  19. *
  20. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  21. */
  22. continue() {
  23. return new Promise(resolve => {
  24. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  25. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  26. });
  27. }
  28. /**
  29. * Restart the rate limit timer
  30. */
  31. restart() {
  32. this.dateStarted = Date.now();
  33. }
  34. }
  35. let YouTubeModule;
  36. let CacheModule;
  37. let DBModule;
  38. let RatingsModule;
  39. let SongsModule;
  40. let StationsModule;
  41. let PlaylistsModule;
  42. let WSModule;
  43. const isQuotaExceeded = apiCalls => {
  44. const reversedApiCalls = apiCalls.slice().reverse();
  45. const quotas = config.get("apis.youtube.quotas").slice();
  46. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  47. let quotaExceeded = false;
  48. sortedQuotas.forEach(quota => {
  49. let quotaUsed = 0;
  50. let dateCutoff = null;
  51. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  52. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  53. else if (quota.type === "QUERIES_PER_DAY") {
  54. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  55. dateCutoff = new Date();
  56. dateCutoff.setUTCMilliseconds(0);
  57. dateCutoff.setUTCSeconds(0);
  58. dateCutoff.setUTCMinutes(0);
  59. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  60. dateCutoff.setUTCHours(0);
  61. }
  62. reversedApiCalls.forEach(apiCall => {
  63. if (apiCall.date >= dateCutoff) quotaUsed += apiCall.quotaCost;
  64. });
  65. if (quotaUsed >= quota.limit) {
  66. quotaExceeded = true;
  67. }
  68. });
  69. return quotaExceeded;
  70. };
  71. class _YouTubeModule extends CoreClass {
  72. // eslint-disable-next-line require-jsdoc
  73. constructor() {
  74. super("youtube", {
  75. concurrency: 10,
  76. priorities: {
  77. GET_PLAYLIST: 11
  78. }
  79. });
  80. YouTubeModule = this;
  81. }
  82. /**
  83. * Initialises the activities module
  84. *
  85. * @returns {Promise} - returns promise (reject, resolve)
  86. */
  87. async initialize() {
  88. CacheModule = this.moduleManager.modules.cache;
  89. DBModule = this.moduleManager.modules.db;
  90. RatingsModule = this.moduleManager.modules.ratings;
  91. SongsModule = this.moduleManager.modules.songs;
  92. StationsModule = this.moduleManager.modules.stations;
  93. PlaylistsModule = this.moduleManager.modules.playlists;
  94. WSModule = this.moduleManager.modules.ws;
  95. this.youtubeApiRequestModel = this.YoutubeApiRequestModel = await DBModule.runJob("GET_MODEL", {
  96. modelName: "youtubeApiRequest"
  97. });
  98. this.youtubeVideoModel = this.YoutubeVideoModel = await DBModule.runJob("GET_MODEL", {
  99. modelName: "youtubeVideo"
  100. });
  101. return new Promise(resolve => {
  102. CacheModule.runJob("SUB", {
  103. channel: "youtube.removeYoutubeApiRequest",
  104. cb: requestId => {
  105. WSModule.runJob("EMIT_TO_ROOM", {
  106. room: `view-api-request.${requestId}`,
  107. args: ["event:youtubeApiRequest.removed"]
  108. });
  109. WSModule.runJob("EMIT_TO_ROOM", {
  110. room: "admin.youtube",
  111. args: ["event:admin.youtubeApiRequest.removed", { data: { requestId } }]
  112. });
  113. }
  114. });
  115. CacheModule.runJob("SUB", {
  116. channel: "youtube.removeVideos",
  117. cb: videoIds => {
  118. const videos = Array.isArray(videoIds) ? videoIds : [videoIds];
  119. videos.forEach(videoId => {
  120. WSModule.runJob("EMIT_TO_ROOM", {
  121. room: `view-youtube-video.${videoId}`,
  122. args: ["event:youtubeVideo.removed"]
  123. });
  124. WSModule.runJob("EMIT_TO_ROOM", {
  125. room: "admin.youtubeVideos",
  126. args: ["event:admin.youtubeVideo.removed", { data: { videoId } }]
  127. });
  128. });
  129. }
  130. });
  131. this.rateLimiter = new RateLimitter(config.get("apis.youtube.rateLimit"));
  132. this.requestTimeout = config.get("apis.youtube.requestTimeout");
  133. this.axios = axios.create();
  134. this.axios.defaults.raxConfig = {
  135. instance: this.axios,
  136. retry: config.get("apis.youtube.retryAmount"),
  137. noResponseRetries: config.get("apis.youtube.retryAmount")
  138. };
  139. rax.attach(this.axios);
  140. this.youtubeApiRequestModel
  141. .find(
  142. { date: { $gte: new Date() - 2 * 24 * 60 * 60 * 1000 } },
  143. { date: true, quotaCost: true, _id: false }
  144. )
  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. /**
  190. * Returns details about the YouTube quota usage
  191. *
  192. * @param {object} payload - object that contains the payload
  193. * @param {string} payload.fromDate - date to select requests up to
  194. * @returns {Promise} - returns promise (reject, resolve)
  195. */
  196. GET_QUOTA_STATUS(payload) {
  197. return new Promise((resolve, reject) => {
  198. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  199. YouTubeModule.youtubeApiRequestModel
  200. .find(
  201. { date: { $gte: fromDate - 2 * 24 * 60 * 60 * 1000, $lte: fromDate } },
  202. { date: true, quotaCost: true, _id: false }
  203. )
  204. .sort({ date: 1 })
  205. .exec((err, youtubeApiRequests) => {
  206. if (err) reject(new Error("Couldn't load YouTube API requests."));
  207. else {
  208. const reversedApiCalls = youtubeApiRequests.slice().reverse();
  209. const quotas = config.get("apis.youtube.quotas").slice();
  210. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  211. const status = {};
  212. sortedQuotas.forEach(quota => {
  213. status[quota.type] = {
  214. title: quota.title,
  215. quotaUsed: 0,
  216. limit: quota.limit,
  217. quotaExceeded: false
  218. };
  219. let dateCutoff = null;
  220. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date(fromDate) - 1000 * 60;
  221. else if (quota.type === "QUERIES_PER_100_SECONDS")
  222. dateCutoff = new Date(fromDate) - 1000 * 100;
  223. else if (quota.type === "QUERIES_PER_DAY") {
  224. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  225. dateCutoff = new Date(fromDate);
  226. dateCutoff.setUTCMilliseconds(0);
  227. dateCutoff.setUTCSeconds(0);
  228. dateCutoff.setUTCMinutes(0);
  229. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  230. dateCutoff.setUTCHours(0);
  231. }
  232. reversedApiCalls.forEach(apiCall => {
  233. if (apiCall.date >= dateCutoff) status[quota.type].quotaUsed += apiCall.quotaCost;
  234. });
  235. if (status[quota.type].quotaUsed >= quota.limit && !status[quota.type].quotaExceeded)
  236. status[quota.type].quotaExceeded = true;
  237. });
  238. resolve({ status });
  239. }
  240. });
  241. });
  242. }
  243. /**
  244. * Returns YouTube quota chart data
  245. *
  246. * @returns {Promise} - returns promise (reject, resolve)
  247. */
  248. GET_QUOTA_CHART_DATA() {
  249. return new Promise((resolve, reject) => {
  250. async.waterfall(
  251. [
  252. next => {
  253. const fromDate = new Date(new Date() - 6 * 24 * 60 * 60 * 1000);
  254. fromDate.setUTCHours(0, 0, 0);
  255. const dates = [];
  256. const tempDate = new Date(fromDate.getTime());
  257. while (dates.length < 7) {
  258. dates.push(new Date(tempDate));
  259. tempDate.setDate(tempDate.getDate() + 1);
  260. }
  261. next(null, fromDate, dates);
  262. },
  263. (fromDate, dates, next) => {
  264. YouTubeModule.youtubeApiRequestModel
  265. .aggregate([
  266. {
  267. $match: { date: { $gte: fromDate } }
  268. },
  269. {
  270. $group: {
  271. _id: { $dateToString: { format: "%Y-%m-%d", date: "$date" } },
  272. usage: { $sum: "$quotaCost" },
  273. count: { $sum: 1 }
  274. }
  275. },
  276. {
  277. $sort: { _id: 1 }
  278. },
  279. {
  280. $project: { date: "$_id", usage: 1, count: 1 }
  281. }
  282. ])
  283. .exec((err, data) => {
  284. if (err) next(err);
  285. else next(null, dates, data);
  286. });
  287. },
  288. (dates, data, next) => {
  289. const filteredData = dates.map(date => {
  290. const dayData = data.find(row => new Date(row.date).getDate() === date.getDate());
  291. if (dayData) return { date, usage: dayData.usage, count: dayData.count };
  292. return { date, usage: 0, count: 0 };
  293. });
  294. const friendlyDates = dates.map(date => date.toISOString().split("T")[0]);
  295. next(null, {
  296. quotaUsage: {
  297. labels: friendlyDates,
  298. datasets: [
  299. {
  300. label: "All",
  301. data: filteredData.map(row => row.usage),
  302. borderColor: "rgb(2, 166, 242)"
  303. }
  304. ]
  305. },
  306. apiRequests: {
  307. labels: friendlyDates,
  308. datasets: [
  309. {
  310. label: "All",
  311. data: filteredData.map(row => row.count),
  312. borderColor: "rgb(2, 166, 242)"
  313. }
  314. ]
  315. }
  316. });
  317. }
  318. ],
  319. (err, data) => {
  320. if (err) reject(err);
  321. else resolve(data);
  322. }
  323. );
  324. });
  325. }
  326. /**
  327. * Gets the id of the channel upload playlist
  328. *
  329. * @param {object} payload - object that contains the payload
  330. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  331. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  332. * @returns {Promise} - returns promise (reject, resolve)
  333. */
  334. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  335. return new Promise((resolve, reject) => {
  336. const params = {
  337. part: "id,contentDetails"
  338. };
  339. if (payload.id) params.id = payload.id;
  340. else params.forUsername = payload.username;
  341. YouTubeModule.runJob(
  342. "API_GET_CHANNELS",
  343. {
  344. params
  345. },
  346. this
  347. )
  348. .then(({ response }) => {
  349. const { data } = response;
  350. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  351. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  352. return resolve({ playlistId });
  353. })
  354. .catch(err => {
  355. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  356. if (err.message === "Request failed with status code 404") {
  357. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  358. }
  359. return reject(new Error("An error has occured. Please try again later."));
  360. });
  361. });
  362. }
  363. /**
  364. * Gets the id of the channel from the custom URL
  365. *
  366. * @param {object} payload - object that contains the payload
  367. * @param {string} payload.customUrl - the customUrl of the YouTube channel
  368. * @returns {Promise} - returns promise (reject, resolve)
  369. */
  370. GET_CHANNEL_ID_FROM_CUSTOM_URL(payload) {
  371. return new Promise((resolve, reject) => {
  372. async.waterfall(
  373. [
  374. next => {
  375. const params = {
  376. part: "snippet",
  377. type: "channel",
  378. maxResults: 50
  379. };
  380. params.q = payload.customUrl;
  381. YouTubeModule.runJob(
  382. "API_SEARCH",
  383. {
  384. params
  385. },
  386. this
  387. )
  388. .then(({ response }) => {
  389. const { data } = response;
  390. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  391. const channelIds = data.items.map(item => item.id.channelId);
  392. return next(null, channelIds);
  393. })
  394. .catch(err => {
  395. next(err);
  396. });
  397. },
  398. (channelIds, next) => {
  399. const params = {
  400. part: "snippet",
  401. id: channelIds.join(","),
  402. maxResults: 50
  403. };
  404. YouTubeModule.runJob(
  405. "API_GET_CHANNELS",
  406. {
  407. params
  408. },
  409. this
  410. )
  411. .then(({ response }) => {
  412. const { data } = response;
  413. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  414. let channelId = null;
  415. data.items.forEach(item => {
  416. if (
  417. item.snippet.customUrl &&
  418. item.snippet.customUrl.toLowerCase() === payload.customUrl.toLowerCase()
  419. ) {
  420. channelId = item.id;
  421. }
  422. });
  423. if (!channelId) return next("Channel not found.");
  424. return next(null, channelId);
  425. })
  426. .catch(err => {
  427. next(err);
  428. });
  429. }
  430. ],
  431. (err, channelId) => {
  432. if (err) {
  433. YouTubeModule.log("ERROR", "GET_CHANNEL_ID_FROM_CUSTOM_URL", `${err.message}`);
  434. if (err.message === "Request failed with status code 404") {
  435. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  436. }
  437. return reject(new Error("An error has occured. Please try again later."));
  438. }
  439. return resolve({ channelId });
  440. }
  441. );
  442. });
  443. }
  444. /**
  445. * Returns an array of songs taken from a YouTube playlist
  446. *
  447. * @param {object} payload - object that contains the payload
  448. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  449. * @param {string} payload.url - the url of the YouTube playlist
  450. * @returns {Promise} - returns promise (reject, resolve)
  451. */
  452. GET_PLAYLIST(payload) {
  453. return new Promise((resolve, reject) => {
  454. const regex = /[\\?&]list=([^&#]*)/;
  455. const splitQuery = regex.exec(payload.url);
  456. if (!splitQuery) {
  457. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  458. reject(new Error("Invalid playlist URL."));
  459. return;
  460. }
  461. const playlistId = splitQuery[1];
  462. async.waterfall(
  463. [
  464. next => {
  465. let songs = [];
  466. let nextPageToken = "";
  467. async.whilst(
  468. next => {
  469. YouTubeModule.log(
  470. "INFO",
  471. `Getting playlist progress for job (${this.toString()}): ${
  472. songs.length
  473. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  474. );
  475. next(null, nextPageToken !== undefined);
  476. },
  477. next => {
  478. // Add 250ms delay between each job request
  479. setTimeout(() => {
  480. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  481. .then(response => {
  482. songs = songs.concat(response.songs);
  483. nextPageToken = response.nextPageToken;
  484. next();
  485. })
  486. .catch(err => next(err));
  487. }, 250);
  488. },
  489. err => next(err, songs)
  490. );
  491. },
  492. (songs, next) =>
  493. next(
  494. null,
  495. songs.map(song => song.contentDetails.videoId)
  496. ),
  497. (songs, next) => {
  498. if (!payload.musicOnly) return next(true, { songs });
  499. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  500. .then(filteredSongs => next(null, { filteredSongs, songs }))
  501. .catch(next);
  502. }
  503. ],
  504. (err, response) => {
  505. if (err && err !== true) {
  506. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  507. reject(new Error(err.message));
  508. } else {
  509. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  510. }
  511. }
  512. );
  513. });
  514. }
  515. /**
  516. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL.
  517. *
  518. * @param {object} payload - object that contains the payload
  519. * @param {boolean} payload.playlistId - the playlist id to get videos from
  520. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  521. * @param {string} payload.url - the url of the YouTube playlist
  522. * @returns {Promise} - returns promise (reject, resolve)
  523. */
  524. GET_PLAYLIST_PAGE(payload) {
  525. return new Promise((resolve, reject) => {
  526. const params = {
  527. part: "contentDetails",
  528. playlistId: payload.playlistId,
  529. maxResults: 50
  530. };
  531. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  532. YouTubeModule.runJob(
  533. "API_GET_PLAYLIST_ITEMS",
  534. {
  535. params
  536. },
  537. this
  538. )
  539. .then(({ response }) => {
  540. const { data } = response;
  541. const songs = data.items;
  542. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  543. return resolve({ songs });
  544. })
  545. .catch(err => {
  546. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  547. if (err.message === "Request failed with status code 404") {
  548. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  549. }
  550. return reject(new Error("An error has occured. Please try again later."));
  551. });
  552. });
  553. }
  554. /**
  555. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  556. *
  557. * @param {object} payload - object that contains the payload
  558. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  559. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  560. * @returns {Promise} - returns promise (reject, resolve)
  561. */
  562. FILTER_MUSIC_VIDEOS(payload) {
  563. return new Promise((resolve, reject) => {
  564. const page = payload.page ? payload.page : 0;
  565. const videosPerPage = 50;
  566. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  567. if (localVideoIds.length === 0) {
  568. resolve({ videoIds: [] });
  569. return;
  570. }
  571. const params = {
  572. part: "topicDetails",
  573. id: localVideoIds.join(","),
  574. maxResults: videosPerPage
  575. };
  576. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  577. .then(({ response }) => {
  578. const { data } = response;
  579. const videoIds = [];
  580. data.items.forEach(item => {
  581. const videoId = item.id;
  582. if (!item.topicDetails) return;
  583. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  584. videoIds.push(videoId);
  585. });
  586. return YouTubeModule.runJob(
  587. "FILTER_MUSIC_VIDEOS",
  588. { videoIds: payload.videoIds, page: page + 1 },
  589. this
  590. )
  591. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  592. .catch(err => reject(err));
  593. })
  594. .catch(err => {
  595. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  596. return reject(new Error("Failed to find playlist from YouTube"));
  597. });
  598. });
  599. }
  600. /**
  601. * Returns an array of songs taken from a YouTube channel
  602. *
  603. * @param {object} payload - object that contains the payload
  604. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  605. * @param {string} payload.url - the url of the YouTube channel
  606. * @returns {Promise} - returns promise (reject, resolve)
  607. */
  608. GET_CHANNEL(payload) {
  609. return new Promise((resolve, reject) => {
  610. const regex =
  611. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  612. const splitQuery = regex.exec(payload.url);
  613. if (!splitQuery) {
  614. YouTubeModule.log("ERROR", "GET_CHANNEL", "Invalid YouTube channel URL query.");
  615. reject(new Error("Invalid playlist URL."));
  616. return;
  617. }
  618. const channelId = splitQuery[1];
  619. const channelUsername = splitQuery[2];
  620. const channelCustomUrl = splitQuery[3];
  621. const channelUsernameOrCustomUrl = splitQuery[4];
  622. console.log(`Channel id: ${channelId}`);
  623. console.log(`Channel username: ${channelUsername}`);
  624. console.log(`Channel custom URL: ${channelCustomUrl}`);
  625. console.log(`Channel username or custom URL: ${channelUsernameOrCustomUrl}`);
  626. async.waterfall(
  627. [
  628. next => {
  629. const payload = {};
  630. if (channelId) payload.id = channelId;
  631. else if (channelUsername) payload.username = channelUsername;
  632. else return next(null, true, null);
  633. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  634. .then(({ playlistId }) => {
  635. next(null, false, playlistId);
  636. })
  637. .catch(err => {
  638. if (err.message === "Channel not found. Is the channel public/unlisted?")
  639. next(null, true, null);
  640. else next(err);
  641. });
  642. },
  643. (getUsernameFromCustomUrl, playlistId, next) => {
  644. if (!getUsernameFromCustomUrl) return next(null, playlistId);
  645. const payload = {};
  646. if (channelCustomUrl) payload.customUrl = channelCustomUrl;
  647. else if (channelUsernameOrCustomUrl) payload.customUrl = channelUsernameOrCustomUrl;
  648. else return next("No proper URL provided.");
  649. return YouTubeModule.runJob("GET_CHANNEL_ID_FROM_CUSTOM_URL", payload, this)
  650. .then(({ channelId }) => {
  651. YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", { id: channelId }, this)
  652. .then(({ playlistId }) => {
  653. next(null, playlistId);
  654. })
  655. .catch(err => next(err));
  656. })
  657. .catch(err => next(err));
  658. },
  659. (playlistId, next) => {
  660. let songs = [];
  661. let nextPageToken = "";
  662. async.whilst(
  663. next => {
  664. YouTubeModule.log(
  665. "INFO",
  666. `Getting channel progress for job (${this.toString()}): ${
  667. songs.length
  668. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  669. );
  670. next(null, nextPageToken !== undefined);
  671. },
  672. next => {
  673. // Add 250ms delay between each job request
  674. setTimeout(() => {
  675. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  676. .then(response => {
  677. songs = songs.concat(response.songs);
  678. nextPageToken = response.nextPageToken;
  679. next();
  680. })
  681. .catch(err => next(err));
  682. }, 250);
  683. },
  684. err => next(err, songs)
  685. );
  686. },
  687. (songs, next) =>
  688. next(
  689. null,
  690. songs.map(song => song.contentDetails.videoId)
  691. ),
  692. (songs, next) => {
  693. if (!payload.musicOnly) return next(true, { songs });
  694. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  695. .then(filteredSongs => next(null, { filteredSongs, songs }))
  696. .catch(next);
  697. }
  698. ],
  699. (err, response) => {
  700. if (err && err !== true) {
  701. YouTubeModule.log("ERROR", "GET_CHANNEL", "Some error has occurred.", err.message);
  702. reject(new Error(err.message));
  703. } else {
  704. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  705. }
  706. }
  707. );
  708. });
  709. }
  710. /**
  711. * Perform YouTube API get videos request
  712. *
  713. * @param {object} payload - object that contains the payload
  714. * @param {object} payload.params - request parameters
  715. * @returns {Promise} - returns promise (reject, resolve)
  716. */
  717. API_GET_VIDEOS(payload) {
  718. return new Promise((resolve, reject) => {
  719. const { params } = payload;
  720. YouTubeModule.runJob(
  721. "API_CALL",
  722. {
  723. url: "https://www.googleapis.com/youtube/v3/videos",
  724. params: {
  725. key: config.get("apis.youtube.key"),
  726. ...params
  727. },
  728. quotaCost: 1
  729. },
  730. this
  731. )
  732. .then(response => {
  733. resolve(response);
  734. })
  735. .catch(err => {
  736. reject(err);
  737. });
  738. });
  739. }
  740. /**
  741. * Perform YouTube API get playlist items request
  742. *
  743. * @param {object} payload - object that contains the payload
  744. * @param {object} payload.params - request parameters
  745. * @returns {Promise} - returns promise (reject, resolve)
  746. */
  747. API_GET_PLAYLIST_ITEMS(payload) {
  748. return new Promise((resolve, reject) => {
  749. const { params } = payload;
  750. YouTubeModule.runJob(
  751. "API_CALL",
  752. {
  753. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  754. params: {
  755. key: config.get("apis.youtube.key"),
  756. ...params
  757. },
  758. quotaCost: 1
  759. },
  760. this
  761. )
  762. .then(response => {
  763. resolve(response);
  764. })
  765. .catch(err => {
  766. reject(err);
  767. });
  768. });
  769. }
  770. /**
  771. * Perform YouTube API get channels request
  772. *
  773. * @param {object} payload - object that contains the payload
  774. * @param {object} payload.params - request parameters
  775. * @returns {Promise} - returns promise (reject, resolve)
  776. */
  777. API_GET_CHANNELS(payload) {
  778. return new Promise((resolve, reject) => {
  779. const { params } = payload;
  780. YouTubeModule.runJob(
  781. "API_CALL",
  782. {
  783. url: "https://www.googleapis.com/youtube/v3/channels",
  784. params: {
  785. key: config.get("apis.youtube.key"),
  786. ...params
  787. },
  788. quotaCost: 1
  789. },
  790. this
  791. )
  792. .then(response => {
  793. resolve(response);
  794. })
  795. .catch(err => {
  796. reject(err);
  797. });
  798. });
  799. }
  800. /**
  801. * Perform YouTube API search request
  802. *
  803. * @param {object} payload - object that contains the payload
  804. * @param {object} payload.params - request parameters
  805. * @returns {Promise} - returns promise (reject, resolve)
  806. */
  807. API_SEARCH(payload) {
  808. return new Promise((resolve, reject) => {
  809. const { params } = payload;
  810. YouTubeModule.runJob(
  811. "API_CALL",
  812. {
  813. url: "https://www.googleapis.com/youtube/v3/search",
  814. params: {
  815. key: config.get("apis.youtube.key"),
  816. ...params
  817. },
  818. quotaCost: 100
  819. },
  820. this
  821. )
  822. .then(response => {
  823. resolve(response);
  824. })
  825. .catch(err => {
  826. reject(err);
  827. });
  828. });
  829. }
  830. /**
  831. * Perform YouTube API call
  832. *
  833. * @param {object} payload - object that contains the payload
  834. * @param {object} payload.url - request url
  835. * @param {object} payload.params - request parameters
  836. * @param {object} payload.quotaCost - request quotaCost
  837. * @returns {Promise} - returns promise (reject, resolve)
  838. */
  839. API_CALL(payload) {
  840. return new Promise((resolve, reject) => {
  841. const { url, params, quotaCost } = payload;
  842. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  843. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  844. else {
  845. const youtubeApiRequest = new YouTubeModule.YoutubeApiRequestModel({
  846. url,
  847. date: Date.now(),
  848. quotaCost
  849. });
  850. youtubeApiRequest.save();
  851. const { key, ...keylessParams } = payload.params;
  852. CacheModule.runJob(
  853. "HSET",
  854. {
  855. table: "youtubeApiRequestParams",
  856. key: youtubeApiRequest._id.toString(),
  857. value: JSON.stringify(keylessParams)
  858. },
  859. this
  860. ).then();
  861. YouTubeModule.apiCalls.push({ date: youtubeApiRequest.date, quotaCost });
  862. YouTubeModule.axios
  863. .get(url, {
  864. params,
  865. timeout: YouTubeModule.requestTimeout
  866. })
  867. .then(response => {
  868. if (response.data.error) {
  869. reject(new Error(response.data.error));
  870. } else {
  871. CacheModule.runJob(
  872. "HSET",
  873. {
  874. table: "youtubeApiRequestResults",
  875. key: youtubeApiRequest._id.toString(),
  876. value: JSON.stringify(response.data)
  877. },
  878. this
  879. ).then();
  880. resolve({ response });
  881. }
  882. })
  883. .catch(err => {
  884. reject(err);
  885. });
  886. }
  887. });
  888. }
  889. /**
  890. * Fetch all api requests
  891. *
  892. * @param {object} payload - object that contains the payload
  893. * @param {object} payload.fromDate - data to fetch requests up to
  894. * @returns {Promise} - returns promise (reject, resolve)
  895. */
  896. GET_API_REQUESTS(payload) {
  897. return new Promise((resolve, reject) => {
  898. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  899. YouTubeModule.youtubeApiRequestModel
  900. .find({ date: { $lte: fromDate } })
  901. .sort({ date: -1 })
  902. .exec((err, youtubeApiRequests) => {
  903. if (err) reject(new Error("Couldn't load YouTube API requests."));
  904. else {
  905. resolve({ apiRequests: youtubeApiRequests });
  906. }
  907. });
  908. });
  909. }
  910. /**
  911. * Fetch an api request
  912. *
  913. * @param {object} payload - object that contains the payload
  914. * @param {object} payload.apiRequestId - the api request id
  915. * @returns {Promise} - returns promise (reject, resolve)
  916. */
  917. GET_API_REQUEST(payload) {
  918. return new Promise((resolve, reject) => {
  919. const { apiRequestId } = payload;
  920. async.waterfall(
  921. [
  922. next => {
  923. YouTubeModule.youtubeApiRequestModel.findOne({ _id: apiRequestId }).exec(next);
  924. },
  925. (apiRequest, next) => {
  926. CacheModule.runJob(
  927. "HGET",
  928. {
  929. table: "youtubeApiRequestParams",
  930. key: apiRequestId.toString()
  931. },
  932. this
  933. )
  934. .then(apiRequestParams => {
  935. next(null, {
  936. ...apiRequest._doc,
  937. params: apiRequestParams
  938. });
  939. })
  940. .catch(err => next(err));
  941. },
  942. (apiRequest, next) => {
  943. CacheModule.runJob(
  944. "HGET",
  945. {
  946. table: "youtubeApiRequestResults",
  947. key: apiRequestId.toString()
  948. },
  949. this
  950. )
  951. .then(apiRequestResults => {
  952. next(null, {
  953. ...apiRequest,
  954. results: apiRequestResults
  955. });
  956. })
  957. .catch(err => next(err));
  958. }
  959. ],
  960. (err, apiRequest) => {
  961. if (err) reject(new Error(err));
  962. else resolve({ apiRequest });
  963. }
  964. );
  965. });
  966. }
  967. /**
  968. * Removed all stored api requests from mongo and redis
  969. *
  970. * @returns {Promise} - returns promise (reject, resolve)
  971. */
  972. RESET_STORED_API_REQUESTS() {
  973. return new Promise((resolve, reject) => {
  974. async.waterfall(
  975. [
  976. next => {
  977. YouTubeModule.youtubeApiRequestModel.find({}, next);
  978. },
  979. (apiRequests, next) => {
  980. YouTubeModule.youtubeApiRequestModel.deleteMany({}, err => {
  981. if (err) next("Couldn't reset stored YouTube API requests.");
  982. else {
  983. next(null, apiRequests);
  984. }
  985. });
  986. },
  987. (apiRequests, next) => {
  988. CacheModule.runJob("DEL", { key: "youtubeApiRequestParams" }, this)
  989. .then(() => next(null, apiRequests))
  990. .catch(err => next(err));
  991. },
  992. (apiRequests, next) => {
  993. CacheModule.runJob("DEL", { key: "youtubeApiRequestResults" }, this)
  994. .then(() => next(null, apiRequests))
  995. .catch(err => next(err));
  996. },
  997. (apiRequests, next) => {
  998. async.eachLimit(
  999. apiRequests.map(apiRequest => apiRequest._id),
  1000. 1,
  1001. (requestId, next) => {
  1002. CacheModule.runJob(
  1003. "PUB",
  1004. {
  1005. channel: "youtube.removeYoutubeApiRequest",
  1006. value: requestId
  1007. },
  1008. this
  1009. )
  1010. .then(() => {
  1011. next();
  1012. })
  1013. .catch(err => {
  1014. next(err);
  1015. });
  1016. },
  1017. err => {
  1018. if (err) next(err);
  1019. else next();
  1020. }
  1021. );
  1022. }
  1023. ],
  1024. err => {
  1025. if (err) reject(new Error(err));
  1026. else resolve();
  1027. }
  1028. );
  1029. });
  1030. }
  1031. /**
  1032. * Remove a stored api request
  1033. *
  1034. * @param {object} payload - object that contains the payload
  1035. * @param {object} payload.requestId - the api request id
  1036. * @returns {Promise} - returns promise (reject, resolve)
  1037. */
  1038. REMOVE_STORED_API_REQUEST(payload) {
  1039. return new Promise((resolve, reject) => {
  1040. async.waterfall(
  1041. [
  1042. next => {
  1043. YouTubeModule.youtubeApiRequestModel.deleteOne({ _id: payload.requestId }, err => {
  1044. if (err) next("Couldn't remove stored YouTube API request.");
  1045. else {
  1046. next();
  1047. }
  1048. });
  1049. },
  1050. next => {
  1051. CacheModule.runJob(
  1052. "HDEL",
  1053. {
  1054. table: "youtubeApiRequestParams",
  1055. key: payload.requestId.toString()
  1056. },
  1057. this
  1058. )
  1059. .then(next)
  1060. .catch(err => next(err));
  1061. },
  1062. next => {
  1063. CacheModule.runJob(
  1064. "HDEL",
  1065. {
  1066. table: "youtubeApiRequestResults",
  1067. key: payload.requestId.toString()
  1068. },
  1069. this
  1070. )
  1071. .then(next)
  1072. .catch(err => next(err));
  1073. },
  1074. next => {
  1075. CacheModule.runJob("PUB", {
  1076. channel: "youtube.removeYoutubeApiRequest",
  1077. value: payload.requestId.toString()
  1078. })
  1079. .then(next)
  1080. .catch(err => next(err));
  1081. }
  1082. ],
  1083. err => {
  1084. if (err) reject(new Error(err));
  1085. else resolve();
  1086. }
  1087. );
  1088. });
  1089. }
  1090. /**
  1091. * Create YouTube videos
  1092. *
  1093. * @param {object} payload - an object containing the payload
  1094. * @param {string} payload.youtubeVideos - the youtubeVideo object or array of
  1095. * @returns {Promise} - returns a promise (resolve, reject)
  1096. */
  1097. CREATE_VIDEOS(payload) {
  1098. return new Promise((resolve, reject) => {
  1099. async.waterfall(
  1100. [
  1101. next => {
  1102. let { youtubeVideos } = payload;
  1103. if (typeof youtubeVideos !== "object") next("Invalid youtubeVideos type");
  1104. else {
  1105. if (!Array.isArray(youtubeVideos)) youtubeVideos = [youtubeVideos];
  1106. YouTubeModule.youtubeVideoModel.insertMany(youtubeVideos, next);
  1107. }
  1108. },
  1109. (youtubeVideos, next) => {
  1110. const youtubeIds = youtubeVideos.map(video => video.youtubeId);
  1111. async.eachLimit(
  1112. youtubeIds,
  1113. 2,
  1114. (youtubeId, next) => {
  1115. RatingsModule.runJob("RECALCULATE_RATINGS", { youtubeId }, this)
  1116. .then(() => next())
  1117. .catch(next);
  1118. },
  1119. err => {
  1120. if (err) next(err);
  1121. else next(null, youtubeVideos);
  1122. }
  1123. );
  1124. }
  1125. ],
  1126. (err, youtubeVideos) => {
  1127. if (err) reject(new Error(err));
  1128. else resolve({ youtubeVideos });
  1129. }
  1130. );
  1131. });
  1132. }
  1133. /**
  1134. * Get YouTube video
  1135. *
  1136. * @param {object} payload - an object containing the payload
  1137. * @param {string} payload.identifier - the youtube video ObjectId or YouTube ID
  1138. * @param {string} payload.createMissing - attempt to fetch and create video if not in db
  1139. * @returns {Promise} - returns a promise (resolve, reject)
  1140. */
  1141. GET_VIDEO(payload) {
  1142. return new Promise((resolve, reject) => {
  1143. async.waterfall(
  1144. [
  1145. next => {
  1146. const query = mongoose.Types.ObjectId.isValid(payload.identifier)
  1147. ? { _id: payload.identifier }
  1148. : { youtubeId: payload.identifier };
  1149. return YouTubeModule.youtubeVideoModel.findOne(query, next);
  1150. },
  1151. (video, next) => {
  1152. if (video) return next(null, video, false);
  1153. if (mongoose.Types.ObjectId.isValid(payload.identifier) || !payload.createMissing)
  1154. return next("YouTube video not found.");
  1155. const params = {
  1156. part: "snippet,contentDetails,statistics,status",
  1157. id: payload.identifier
  1158. };
  1159. return YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  1160. .then(({ response }) => {
  1161. const { data } = response;
  1162. if (data.items[0] === undefined)
  1163. return next("The specified video does not exist or cannot be publicly accessed.");
  1164. // TODO Clean up duration converter
  1165. let dur = data.items[0].contentDetails.duration;
  1166. dur = dur.replace("PT", "");
  1167. let duration = 0;
  1168. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  1169. v2 = Number(v2);
  1170. duration = v2 * 60 * 60;
  1171. return "";
  1172. });
  1173. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  1174. v2 = Number(v2);
  1175. duration += v2 * 60;
  1176. return "";
  1177. });
  1178. dur.replace(/([\d]*)S/, (v, v2) => {
  1179. v2 = Number(v2);
  1180. duration += v2;
  1181. return "";
  1182. });
  1183. const youtubeVideo = {
  1184. youtubeId: data.items[0].id,
  1185. title: data.items[0].snippet.title,
  1186. author: data.items[0].snippet.channelTitle,
  1187. thumbnail: data.items[0].snippet.thumbnails.default.url,
  1188. duration
  1189. };
  1190. return next(null, false, youtubeVideo);
  1191. })
  1192. .catch(next);
  1193. },
  1194. (video, youtubeVideo, next) => {
  1195. if (video) return next(null, video, true);
  1196. return YouTubeModule.runJob("CREATE_VIDEOS", { youtubeVideos: youtubeVideo }, this)
  1197. .then(res => {
  1198. if (res.youtubeVideos.length === 1) next(null, res.youtubeVideos[0], false);
  1199. else next("YouTube video not found.");
  1200. })
  1201. .catch(next);
  1202. }
  1203. ],
  1204. (err, video, existing) => {
  1205. if (err) reject(new Error(err));
  1206. else resolve({ video, existing });
  1207. }
  1208. );
  1209. });
  1210. }
  1211. /**
  1212. * Remove YouTube videos
  1213. *
  1214. * @param {object} payload - an object containing the payload
  1215. * @param {string} payload.videoIds - Array of youtubeVideo ObjectIds
  1216. * @returns {Promise} - returns a promise (resolve, reject)
  1217. */
  1218. REMOVE_VIDEOS(payload) {
  1219. return new Promise((resolve, reject) => {
  1220. let { videoIds } = payload;
  1221. if (!Array.isArray(videoIds)) videoIds = [videoIds];
  1222. async.waterfall(
  1223. [
  1224. next => {
  1225. if (!videoIds.every(videoId => mongoose.Types.ObjectId.isValid(videoId)))
  1226. next("One or more videoIds are not a valid ObjectId.");
  1227. else {
  1228. YouTubeModule.youtubeVideoModel.find({ _id: { $in: videoIds } }, (err, videos) => {
  1229. if (err) next(err);
  1230. else
  1231. next(
  1232. null,
  1233. videos.map(video => video.youtubeId)
  1234. );
  1235. });
  1236. }
  1237. },
  1238. (youtubeIds, next) => {
  1239. SongsModule.SongModel.find({ youtubeId: { $in: youtubeIds } }, (err, songs) => {
  1240. if (err) next(err);
  1241. else {
  1242. const filteredIds = youtubeIds.filter(
  1243. youtubeId => !songs.find(song => song.youtubeId === youtubeId)
  1244. );
  1245. if (filteredIds.length < youtubeIds.length)
  1246. next("One or more videos are attached to songs.");
  1247. else next(null, filteredIds);
  1248. }
  1249. });
  1250. },
  1251. (youtubeIds, next) => {
  1252. RatingsModule.runJob("REMOVE_RATINGS", { youtubeIds }, this)
  1253. .then(() => next(null, youtubeIds))
  1254. .catch(next);
  1255. },
  1256. (youtubeIds, next) => {
  1257. async.eachLimit(
  1258. youtubeIds,
  1259. 2,
  1260. (youtubeId, next) => {
  1261. async.waterfall(
  1262. [
  1263. next => {
  1264. PlaylistsModule.playlistModel.find(
  1265. { "songs.youtubeId": youtubeId },
  1266. (err, playlists) => {
  1267. if (err) next(err);
  1268. else {
  1269. async.eachLimit(
  1270. playlists,
  1271. 1,
  1272. (playlist, next) => {
  1273. PlaylistsModule.runJob(
  1274. "REMOVE_FROM_PLAYLIST",
  1275. { playlistId: playlist._id, youtubeId },
  1276. this
  1277. )
  1278. .then(() => next())
  1279. .catch(next);
  1280. },
  1281. next
  1282. );
  1283. }
  1284. }
  1285. );
  1286. },
  1287. next => {
  1288. StationsModule.stationModel.find(
  1289. { "queue.youtubeId": youtubeId },
  1290. (err, stations) => {
  1291. if (err) next(err);
  1292. else {
  1293. async.eachLimit(
  1294. stations,
  1295. 1,
  1296. (station, next) => {
  1297. StationsModule.runJob(
  1298. "REMOVE_FROM_QUEUE",
  1299. { stationId: station._id, youtubeId },
  1300. this
  1301. )
  1302. .then(() => next())
  1303. .catch(err => {
  1304. if (
  1305. err === "Station not found" ||
  1306. err ===
  1307. "Song is not currently in the queue."
  1308. )
  1309. next();
  1310. else next(err);
  1311. });
  1312. },
  1313. next
  1314. );
  1315. }
  1316. }
  1317. );
  1318. },
  1319. next => {
  1320. StationsModule.stationModel.find(
  1321. { "currentSong.youtubeId": youtubeId },
  1322. (err, stations) => {
  1323. if (err) next(err);
  1324. else {
  1325. async.eachLimit(
  1326. stations,
  1327. 1,
  1328. (station, next) => {
  1329. StationsModule.runJob(
  1330. "SKIP_STATION",
  1331. { stationId: station._id, natural: false },
  1332. this
  1333. )
  1334. .then(() => {
  1335. next();
  1336. })
  1337. .catch(err => {
  1338. if (err.message === "Station not found.")
  1339. next();
  1340. else next(err);
  1341. });
  1342. },
  1343. next
  1344. );
  1345. }
  1346. }
  1347. );
  1348. }
  1349. ],
  1350. next
  1351. );
  1352. },
  1353. next
  1354. );
  1355. },
  1356. next => {
  1357. YouTubeModule.youtubeVideoModel.deleteMany({ _id: { $in: videoIds } }, next);
  1358. },
  1359. (res, next) => {
  1360. CacheModule.runJob("PUB", {
  1361. channel: "youtube.removeVideos",
  1362. value: videoIds
  1363. })
  1364. .then(next)
  1365. .catch(err => next(err));
  1366. }
  1367. ],
  1368. err => {
  1369. if (err) reject(new Error(err));
  1370. else resolve();
  1371. }
  1372. );
  1373. });
  1374. }
  1375. /**
  1376. * Request a set of YouTube videos
  1377. *
  1378. * @param {object} payload - an object containing the payload
  1379. * @param {string} payload.url - the url of the the YouTube playlist or channel
  1380. * @param {boolean} payload.musicOnly - whether to only get music from the playlist/channel
  1381. * @param {boolean} payload.returnVideos - whether to return videos
  1382. * @returns {Promise} - returns a promise (resolve, reject)
  1383. */
  1384. REQUEST_SET(payload) {
  1385. return new Promise((resolve, reject) => {
  1386. async.waterfall(
  1387. [
  1388. next => {
  1389. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1390. const channelRegex =
  1391. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1392. if (playlistRegex.exec(payload.url) || channelRegex.exec(payload.url))
  1393. YouTubeModule.runJob(
  1394. playlistRegex.exec(payload.url) ? "GET_PLAYLIST" : "GET_CHANNEL",
  1395. {
  1396. url: payload.url,
  1397. musicOnly: payload.musicOnly
  1398. },
  1399. this
  1400. )
  1401. .then(res => {
  1402. next(null, res.songs);
  1403. })
  1404. .catch(next);
  1405. else next("Invalid YouTube URL.");
  1406. },
  1407. (youtubeIds, next) => {
  1408. let successful = 0;
  1409. let videos = {};
  1410. let failed = 0;
  1411. let alreadyInDatabase = 0;
  1412. if (youtubeIds.length === 0) next();
  1413. async.eachOfLimit(
  1414. youtubeIds,
  1415. 1,
  1416. (youtubeId, index, next2) => {
  1417. YouTubeModule.runJob("GET_VIDEO", { identifier: youtubeId, createMissing: true }, this)
  1418. .then(res => {
  1419. successful += 1;
  1420. if (res.existing) alreadyInDatabase += 1;
  1421. if (res.video) videos[index] = res.video;
  1422. })
  1423. .catch(() => {
  1424. failed += 1;
  1425. })
  1426. .finally(() => {
  1427. next2();
  1428. });
  1429. },
  1430. () => {
  1431. if (payload.returnVideos)
  1432. videos = Object.keys(videos)
  1433. .sort()
  1434. .map(key => videos[key]);
  1435. next(null, { successful, failed, alreadyInDatabase, videos });
  1436. }
  1437. );
  1438. }
  1439. ],
  1440. (err, response) => {
  1441. if (err) reject(new Error(err));
  1442. else resolve(response);
  1443. }
  1444. );
  1445. });
  1446. }
  1447. }
  1448. export default new _YouTubeModule();