youtube.js 39 KB

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