youtube.js 46 KB

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