youtube.js 46 KB

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