youtube.js 45 KB

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