youtube.js 45 KB

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