youtube.js 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843
  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. * @param {number} timeBetween - The time between each allowed YouTube request
  11. */
  12. constructor(timeBetween) {
  13. this.dateStarted = Date.now();
  14. this.timeBetween = timeBetween;
  15. }
  16. /**
  17. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  18. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  19. */
  20. continue() {
  21. return new Promise(resolve => {
  22. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  23. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  24. });
  25. }
  26. /**
  27. * Restart the rate limit timer
  28. */
  29. restart() {
  30. this.dateStarted = Date.now();
  31. }
  32. }
  33. let YouTubeModule;
  34. let CacheModule;
  35. let DBModule;
  36. let MediaModule;
  37. let SongsModule;
  38. let StationsModule;
  39. let PlaylistsModule;
  40. let WSModule;
  41. const isQuotaExceeded = apiCalls => {
  42. const reversedApiCalls = apiCalls.slice().reverse();
  43. const quotas = config.get("apis.youtube.quotas").slice();
  44. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  45. let quotaExceeded = false;
  46. sortedQuotas.forEach(quota => {
  47. let quotaUsed = 0;
  48. let dateCutoff = null;
  49. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  50. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  51. else if (quota.type === "QUERIES_PER_DAY") {
  52. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  53. dateCutoff = new Date();
  54. dateCutoff.setUTCMilliseconds(0);
  55. dateCutoff.setUTCSeconds(0);
  56. dateCutoff.setUTCMinutes(0);
  57. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  58. dateCutoff.setUTCHours(0);
  59. }
  60. reversedApiCalls.forEach(apiCall => {
  61. if (apiCall.date >= dateCutoff) quotaUsed += apiCall.quotaCost;
  62. });
  63. if (quotaUsed >= quota.limit) {
  64. quotaExceeded = true;
  65. }
  66. });
  67. return quotaExceeded;
  68. };
  69. class _YouTubeModule extends CoreClass {
  70. // eslint-disable-next-line require-jsdoc
  71. constructor() {
  72. super("youtube", {
  73. concurrency: 10,
  74. priorities: {
  75. GET_PLAYLIST: 11
  76. }
  77. });
  78. YouTubeModule = this;
  79. }
  80. /**
  81. * Initialises the activities module
  82. * @returns {Promise} - returns promise (reject, resolve)
  83. */
  84. async initialize() {
  85. CacheModule = this.moduleManager.modules.cache;
  86. DBModule = this.moduleManager.modules.db;
  87. MediaModule = this.moduleManager.modules.media;
  88. SongsModule = this.moduleManager.modules.songs;
  89. StationsModule = this.moduleManager.modules.stations;
  90. PlaylistsModule = this.moduleManager.modules.playlists;
  91. WSModule = this.moduleManager.modules.ws;
  92. this.youtubeApiRequestModel = this.YoutubeApiRequestModel = await DBModule.runJob("GET_MODEL", {
  93. modelName: "youtubeApiRequest"
  94. });
  95. this.youtubeVideoModel = this.YoutubeVideoModel = await DBModule.runJob("GET_MODEL", {
  96. modelName: "youtubeVideo"
  97. });
  98. this.youtubeChannelModel = this.YoutubeChannelModel = await DBModule.runJob("GET_MODEL", {
  99. modelName: "youtubeChannel"
  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-media.youtube:${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. WSModule.runJob("EMIT_TO_ROOMS", {
  129. rooms: ["import-album", "edit-songs"],
  130. args: ["event:admin.youtubeVideo.removed", { videoId }]
  131. });
  132. });
  133. }
  134. });
  135. this.rateLimiter = new RateLimitter(config.get("apis.youtube.rateLimit"));
  136. this.requestTimeout = config.get("apis.youtube.requestTimeout");
  137. this.axios = axios.create();
  138. this.axios.defaults.raxConfig = {
  139. instance: this.axios,
  140. retry: config.get("apis.youtube.retryAmount"),
  141. noResponseRetries: config.get("apis.youtube.retryAmount")
  142. };
  143. rax.attach(this.axios);
  144. this.youtubeApiRequestModel
  145. .find(
  146. { date: { $gte: new Date() - 2 * 24 * 60 * 60 * 1000 } },
  147. { date: true, quotaCost: true, _id: false }
  148. )
  149. .sort({ date: 1 })
  150. .exec((err, youtubeApiRequests) => {
  151. if (err) console.log("Couldn't load YouTube API requests.");
  152. else {
  153. this.apiCalls = youtubeApiRequests;
  154. resolve();
  155. }
  156. });
  157. });
  158. }
  159. /**
  160. * Fetches a list of songs from Youtube's API
  161. * @param {object} payload - object that contains the payload
  162. * @param {string} payload.query - the query we'll pass to youtubes api
  163. * @param {string} payload.pageToken - (optional) if this exists, will search search youtube for a specific page reference
  164. * @returns {Promise} - returns promise (reject, resolve)
  165. */
  166. SEARCH(payload) {
  167. const params = {
  168. part: "snippet",
  169. q: payload.query,
  170. type: "video",
  171. maxResults: 10
  172. };
  173. if (payload.pageToken) params.pageToken = payload.pageToken;
  174. return new Promise((resolve, reject) => {
  175. YouTubeModule.runJob(
  176. "API_SEARCH",
  177. {
  178. params
  179. },
  180. this
  181. )
  182. .then(({ response }) => {
  183. const { data } = response;
  184. return resolve(data);
  185. })
  186. .catch(err => {
  187. YouTubeModule.log("ERROR", "SEARCH", `${err.message}`);
  188. if (err.message === "Searching with YouTube is disabled.") return reject(err);
  189. return reject(new Error("An error has occured. Please try again later."));
  190. });
  191. });
  192. }
  193. /**
  194. * Returns details about the YouTube quota usage
  195. * @param {object} payload - object that contains the payload
  196. * @param {string} payload.fromDate - date to select requests up to
  197. * @returns {Promise} - returns promise (reject, resolve)
  198. */
  199. GET_QUOTA_STATUS(payload) {
  200. return new Promise((resolve, reject) => {
  201. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  202. YouTubeModule.youtubeApiRequestModel
  203. .find(
  204. { date: { $gte: fromDate - 2 * 24 * 60 * 60 * 1000, $lte: fromDate } },
  205. { date: true, quotaCost: true, _id: false }
  206. )
  207. .sort({ date: 1 })
  208. .exec((err, youtubeApiRequests) => {
  209. if (err) reject(new Error("Couldn't load YouTube API requests."));
  210. else {
  211. const reversedApiCalls = youtubeApiRequests.slice().reverse();
  212. const quotas = config.get("apis.youtube.quotas").slice();
  213. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  214. const status = {};
  215. sortedQuotas.forEach(quota => {
  216. status[quota.type] = {
  217. title: quota.title,
  218. quotaUsed: 0,
  219. limit: quota.limit,
  220. quotaExceeded: false
  221. };
  222. let dateCutoff = null;
  223. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date(fromDate) - 1000 * 60;
  224. else if (quota.type === "QUERIES_PER_100_SECONDS")
  225. dateCutoff = new Date(fromDate) - 1000 * 100;
  226. else if (quota.type === "QUERIES_PER_DAY") {
  227. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  228. dateCutoff = new Date(fromDate);
  229. dateCutoff.setUTCMilliseconds(0);
  230. dateCutoff.setUTCSeconds(0);
  231. dateCutoff.setUTCMinutes(0);
  232. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  233. dateCutoff.setUTCHours(0);
  234. }
  235. reversedApiCalls.forEach(apiCall => {
  236. if (apiCall.date >= dateCutoff) status[quota.type].quotaUsed += apiCall.quotaCost;
  237. });
  238. if (status[quota.type].quotaUsed >= quota.limit && !status[quota.type].quotaExceeded)
  239. status[quota.type].quotaExceeded = true;
  240. });
  241. resolve({ status });
  242. }
  243. });
  244. });
  245. }
  246. /**
  247. * Returns YouTube quota chart data
  248. * @param {object} payload - object that contains the payload
  249. * @param {string} payload.timePeriod - either hours or days
  250. * @param {string} payload.startDate - beginning date
  251. * @param {string} payload.endDate - end date
  252. * @param {string} payload.dataType - either usage or count
  253. * @returns {Promise} - returns promise (reject, resolve)
  254. */
  255. GET_QUOTA_CHART_DATA(payload) {
  256. return new Promise((resolve, reject) => {
  257. const { timePeriod, startDate, endDate, dataType } = payload;
  258. // const timePeriod = "hours";
  259. // const startDate = new Date("2022-05-20 00:00:00");
  260. // const endDate = new Date("2022-05-21 00:00:00");
  261. // const timePeriod = "days";
  262. // const startDate = new Date("2022-05-15 00:00:00");
  263. // const endDate = new Date("2022-05-21 00:00:00");
  264. // const endDate = new Date("2022-05-30 00:00:00");
  265. // const dataType = "usage";
  266. // const dataType = "count";
  267. async.waterfall(
  268. [
  269. next => {
  270. let timeRanges = [];
  271. if (timePeriod === "hours") {
  272. startDate.setMinutes(0, 0, 0);
  273. endDate.setMinutes(0, 0, 0);
  274. const lastDate = new Date(startDate);
  275. do {
  276. const newDate = new Date(lastDate.getTime() + 1000 * 60 * 60);
  277. timeRanges.push({
  278. startDate: new Date(lastDate),
  279. endDate: newDate
  280. });
  281. lastDate.setTime(newDate.getTime());
  282. } while (lastDate.getTime() < endDate.getTime());
  283. if (timeRanges.length === 0 || timeRanges.length > 24)
  284. return next("No valid time ranges specified.");
  285. timeRanges = timeRanges.map(timeRange => ({
  286. ...timeRange,
  287. label: `${timeRange.startDate.getHours().toString().padStart(2, "0")}:00`
  288. }));
  289. } else if (timePeriod === "days") {
  290. startDate.setHours(0, 0, 0, 0);
  291. endDate.setHours(0, 0, 0, 0);
  292. const lastDate = new Date(startDate);
  293. do {
  294. const newDate = new Date(lastDate.getTime() + 1000 * 60 * 60 * 24);
  295. timeRanges.push({
  296. startDate: new Date(lastDate),
  297. endDate: newDate
  298. });
  299. lastDate.setTime(newDate.getTime());
  300. } while (lastDate.getTime() < endDate.getTime());
  301. if (timeRanges.length === 0 || timeRanges.length > 31)
  302. return next("No valid time ranges specified.");
  303. const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
  304. if (timeRanges.length <= 7)
  305. timeRanges = timeRanges.map(timeRange => ({
  306. ...timeRange,
  307. label: days[timeRange.startDate.getDay()]
  308. }));
  309. else
  310. timeRanges = timeRanges.map(timeRange => ({
  311. ...timeRange,
  312. label: `${timeRange.startDate.getDate().toString().padStart(2, "0")}-${(
  313. timeRange.startDate.getMonth() + 1
  314. )
  315. .toString()
  316. .padStart(2, "0")}`
  317. }));
  318. }
  319. return next(null, timeRanges);
  320. },
  321. (timeRanges, next) => {
  322. YouTubeModule.youtubeApiRequestModel
  323. .find({
  324. date: { $gte: startDate, $lte: endDate }
  325. })
  326. .sort({ date: 1 })
  327. .exec((err, youtubeApiRequests) => {
  328. next(err, timeRanges, youtubeApiRequests);
  329. });
  330. },
  331. (timeRanges, youtubeApiRequests, next) => {
  332. const regex = /https:\/\/www\.googleapis\.com\/youtube\/v3\/(.+)/;
  333. const requestTypes = Object.fromEntries(
  334. youtubeApiRequests
  335. .map(youtubeApiRequest => regex.exec(youtubeApiRequest.url)[1])
  336. .filter((requestType, index, array) => array.indexOf(requestType) === index)
  337. .map(requestType => [requestType, 0])
  338. );
  339. timeRanges = timeRanges.map(timeRange => ({
  340. ...timeRange,
  341. data: { total: 0, ...requestTypes }
  342. }));
  343. youtubeApiRequests.forEach(youtubeApiRequest => {
  344. timeRanges.forEach(timeRange => {
  345. if (
  346. timeRange.startDate <= youtubeApiRequest.date &&
  347. timeRange.endDate >= youtubeApiRequest.date
  348. ) {
  349. const requestType = regex.exec(youtubeApiRequest.url)[1];
  350. if (!timeRange.data[requestType]) timeRange.data[requestType] = 0;
  351. if (dataType === "usage") {
  352. timeRange.data[requestType] += youtubeApiRequest.quotaCost;
  353. timeRange.data.total += youtubeApiRequest.quotaCost;
  354. } else if (dataType === "count") {
  355. timeRange.data[requestType] += 1;
  356. timeRange.data.total += 1;
  357. }
  358. }
  359. });
  360. });
  361. next(null, timeRanges);
  362. },
  363. (timeRanges, next) => {
  364. const chartData = {};
  365. chartData.labels = timeRanges.map(timeRange => timeRange.label);
  366. const datasetTypes = Object.keys(timeRanges[0].data);
  367. const colors = {
  368. total: "rgb(2, 166, 242)",
  369. videos: "rgb(166, 2, 242)",
  370. search: "rgb(242, 2, 166)",
  371. channels: "rgb(2, 242, 166)",
  372. playlistItems: "rgb(242, 166, 2)"
  373. };
  374. chartData.datasets = datasetTypes.map(datasetType => {
  375. let label;
  376. switch (datasetType) {
  377. case "total":
  378. label = "Total";
  379. break;
  380. case "videos":
  381. label = "Videos";
  382. break;
  383. case "search":
  384. label = "Search";
  385. break;
  386. case "playlistItems":
  387. label = "Playlist Items";
  388. break;
  389. default:
  390. label = datasetType;
  391. }
  392. return {
  393. label,
  394. borderColor: colors[datasetType],
  395. backgroundColor: colors[datasetType],
  396. data: timeRanges.map(timeRange => timeRange.data[datasetType])
  397. };
  398. });
  399. next(null, chartData);
  400. }
  401. ],
  402. (err, chartData) => {
  403. if (err) reject(err);
  404. else resolve(chartData);
  405. }
  406. );
  407. });
  408. }
  409. /**
  410. * Gets the id of the channel upload playlist
  411. * @param {object} payload - object that contains the payload
  412. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  413. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  414. * @returns {Promise} - returns promise (reject, resolve)
  415. */
  416. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  417. return new Promise((resolve, reject) => {
  418. const params = {
  419. part: "id,contentDetails"
  420. };
  421. if (payload.id) params.id = payload.id;
  422. else params.forUsername = payload.username;
  423. YouTubeModule.runJob(
  424. "API_GET_CHANNELS",
  425. {
  426. params
  427. },
  428. this
  429. )
  430. .then(({ response }) => {
  431. const { data } = response;
  432. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  433. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  434. return resolve({ playlistId });
  435. })
  436. .catch(err => {
  437. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  438. if (err.message === "Request failed with status code 404")
  439. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  440. if (err.message === "Searching with YouTube is disabled.") return reject(err);
  441. return reject(new Error("An error has occured. Please try again later."));
  442. });
  443. });
  444. }
  445. /**
  446. * Gets the id of the channel from the custom URL
  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 || err}`);
  515. if (err.message === "Request failed with status code 404")
  516. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  517. if (err.message === "Searching with YouTube is disabled.") return reject(err);
  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. * @param {object} payload - object that contains the payload
  528. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  529. * @param {string} payload.url - the url of the YouTube playlist
  530. * @returns {Promise} - returns promise (reject, resolve)
  531. */
  532. GET_PLAYLIST(payload) {
  533. return new Promise((resolve, reject) => {
  534. const regex = /[\\?&]list=([^&#]*)/;
  535. const splitQuery = regex.exec(payload.url);
  536. if (!splitQuery) {
  537. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  538. reject(new Error("Invalid playlist URL."));
  539. return;
  540. }
  541. const playlistId = splitQuery[1];
  542. const maxPages = Number.parseInt(config.get("apis.youtube.maxPlaylistPages"));
  543. let currentPage = 0;
  544. async.waterfall(
  545. [
  546. next => {
  547. let songs = [];
  548. let nextPageToken = "";
  549. async.whilst(
  550. next => {
  551. YouTubeModule.log(
  552. "INFO",
  553. `Getting playlist progress for job (${this.toString()}): ${
  554. songs.length
  555. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  556. );
  557. next(null, nextPageToken !== undefined && currentPage < maxPages);
  558. },
  559. next => {
  560. currentPage += 1;
  561. // Add 250ms delay between each job request
  562. setTimeout(() => {
  563. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  564. .then(response => {
  565. songs = songs.concat(response.songs);
  566. nextPageToken = response.nextPageToken;
  567. next();
  568. })
  569. .catch(err => next(err));
  570. }, 250);
  571. },
  572. err => next(err, songs)
  573. );
  574. },
  575. (songs, next) =>
  576. next(
  577. null,
  578. songs.map(song => song.contentDetails.videoId)
  579. ),
  580. (songs, next) => {
  581. if (!payload.musicOnly) return next(true, { songs });
  582. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  583. .then(filteredSongs => next(null, { filteredSongs, songs }))
  584. .catch(next);
  585. }
  586. ],
  587. (err, response) => {
  588. if (err && err !== true) {
  589. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  590. reject(new Error(err.message));
  591. } else {
  592. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  593. }
  594. }
  595. );
  596. });
  597. }
  598. /**
  599. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL_VIDEOS.
  600. * @param {object} payload - object that contains the payload
  601. * @param {boolean} payload.playlistId - the playlist id to get videos from
  602. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  603. * @param {string} payload.url - the url of the YouTube playlist
  604. * @returns {Promise} - returns promise (reject, resolve)
  605. */
  606. GET_PLAYLIST_PAGE(payload) {
  607. return new Promise((resolve, reject) => {
  608. const params = {
  609. part: "contentDetails",
  610. playlistId: payload.playlistId,
  611. maxResults: 50
  612. };
  613. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  614. YouTubeModule.runJob(
  615. "API_GET_PLAYLIST_ITEMS",
  616. {
  617. params
  618. },
  619. this
  620. )
  621. .then(({ response }) => {
  622. const { data } = response;
  623. const songs = data.items;
  624. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  625. return resolve({ songs });
  626. })
  627. .catch(err => {
  628. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  629. if (err.message === "Request failed with status code 404")
  630. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  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. * @param {object} payload - object that contains the payload
  638. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  639. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  640. * @returns {Promise} - returns promise (reject, resolve)
  641. */
  642. FILTER_MUSIC_VIDEOS(payload) {
  643. return new Promise((resolve, reject) => {
  644. const page = payload.page ? payload.page : 0;
  645. const videosPerPage = 50;
  646. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  647. if (localVideoIds.length === 0) {
  648. resolve({ videoIds: [] });
  649. return;
  650. }
  651. const params = {
  652. part: "topicDetails",
  653. id: localVideoIds.join(","),
  654. maxResults: videosPerPage
  655. };
  656. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  657. .then(({ response }) => {
  658. const { data } = response;
  659. const videoIds = [];
  660. data.items.forEach(item => {
  661. const videoId = item.id;
  662. if (!item.topicDetails) return;
  663. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  664. videoIds.push(videoId);
  665. });
  666. return YouTubeModule.runJob(
  667. "FILTER_MUSIC_VIDEOS",
  668. { videoIds: payload.videoIds, page: page + 1 },
  669. this
  670. )
  671. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  672. .catch(err => reject(err));
  673. })
  674. .catch(err => {
  675. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  676. return reject(new Error("Failed to find playlist from YouTube"));
  677. });
  678. });
  679. }
  680. /**
  681. * Returns an array of songs taken from a YouTube channel
  682. * @param {object} payload - object that contains the payload
  683. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  684. * @param {boolean} payload.disableSearch - whether to allow searching for custom url/username
  685. * @param {string} payload.url - the url of the YouTube channel
  686. * @returns {Promise} - returns promise (reject, resolve)
  687. */
  688. GET_CHANNEL_VIDEOS(payload) {
  689. return new Promise((resolve, reject) => {
  690. const regex =
  691. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  692. const splitQuery = regex.exec(payload.url);
  693. if (!splitQuery) {
  694. YouTubeModule.log("ERROR", "GET_CHANNEL", "Invalid YouTube channel URL query.");
  695. reject(new Error("Invalid playlist URL."));
  696. return;
  697. }
  698. const channelId = splitQuery[1];
  699. const channelUsername = splitQuery[2];
  700. const channelCustomUrl = splitQuery[3];
  701. const channelUsernameOrCustomUrl = splitQuery[4];
  702. const disableSearch = payload.disableSearch || false;
  703. async.waterfall(
  704. [
  705. next => {
  706. const payload = {};
  707. if (channelId) payload.id = channelId;
  708. else if (channelUsername) payload.username = channelUsername;
  709. else return next(null, true, null);
  710. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  711. .then(({ playlistId }) => {
  712. next(null, false, playlistId);
  713. })
  714. .catch(err => {
  715. if (err.message === "Channel not found. Is the channel public/unlisted?")
  716. next(null, true, null);
  717. else next(err);
  718. });
  719. },
  720. (getUsernameFromCustomUrl, playlistId, next) => {
  721. if (!getUsernameFromCustomUrl) return next(null, playlistId);
  722. if (disableSearch)
  723. return next(
  724. "Importing with this type of URL is disabled. Please provide a channel URL with the channel ID."
  725. );
  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 || err);
  783. reject(new Error(err.message || err));
  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. * @param {object} payload - object that contains the payload
  794. * @param {object} payload.params - request parameters
  795. * @returns {Promise} - returns promise (reject, resolve)
  796. */
  797. API_GET_VIDEOS(payload) {
  798. return new Promise((resolve, reject) => {
  799. const { params } = payload;
  800. YouTubeModule.runJob(
  801. "API_CALL",
  802. {
  803. url: "https://www.googleapis.com/youtube/v3/videos",
  804. params: {
  805. key: config.get("apis.youtube.key"),
  806. ...params
  807. },
  808. quotaCost: 1
  809. },
  810. this
  811. )
  812. .then(response => {
  813. resolve(response);
  814. })
  815. .catch(err => {
  816. reject(err);
  817. });
  818. });
  819. }
  820. /**
  821. * Perform YouTube API get playlist items request
  822. * @param {object} payload - object that contains the payload
  823. * @param {object} payload.params - request parameters
  824. * @returns {Promise} - returns promise (reject, resolve)
  825. */
  826. API_GET_PLAYLIST_ITEMS(payload) {
  827. return new Promise((resolve, reject) => {
  828. const { params } = payload;
  829. YouTubeModule.runJob(
  830. "API_CALL",
  831. {
  832. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  833. params: {
  834. key: config.get("apis.youtube.key"),
  835. ...params
  836. },
  837. quotaCost: 1
  838. },
  839. this
  840. )
  841. .then(response => {
  842. resolve(response);
  843. })
  844. .catch(err => {
  845. reject(err);
  846. });
  847. });
  848. }
  849. /**
  850. * Perform YouTube API get channels request
  851. * @param {object} payload - object that contains the payload
  852. * @param {object} payload.params - request parameters
  853. * @returns {Promise} - returns promise (reject, resolve)
  854. */
  855. API_GET_CHANNELS(payload) {
  856. return new Promise((resolve, reject) => {
  857. const { params } = payload;
  858. YouTubeModule.runJob(
  859. "API_CALL",
  860. {
  861. url: "https://www.googleapis.com/youtube/v3/channels",
  862. params: {
  863. key: config.get("apis.youtube.key"),
  864. ...params
  865. },
  866. quotaCost: 1
  867. },
  868. this
  869. )
  870. .then(response => {
  871. resolve(response);
  872. })
  873. .catch(err => {
  874. reject(err);
  875. });
  876. });
  877. }
  878. /**
  879. * Perform YouTube API search request
  880. * @param {object} payload - object that contains the payload
  881. * @param {object} payload.params - request parameters
  882. * @returns {Promise} - returns promise (reject, resolve)
  883. */
  884. API_SEARCH(payload) {
  885. return new Promise((resolve, reject) => {
  886. const { params } = payload;
  887. if (config.get("experimental.disable_youtube_search")) {
  888. reject(new Error("Searching with YouTube is disabled."));
  889. return;
  890. }
  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. * @param {object} payload - object that contains the payload
  914. * @param {object} payload.url - request url
  915. * @param {object} payload.params - request parameters
  916. * @param {object} payload.quotaCost - request quotaCost
  917. * @returns {Promise} - returns promise (reject, resolve)
  918. */
  919. API_CALL(payload) {
  920. return new Promise((resolve, reject) => {
  921. const { url, params, quotaCost } = payload;
  922. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  923. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  924. else {
  925. const youtubeApiRequest = new YouTubeModule.YoutubeApiRequestModel({
  926. url,
  927. date: Date.now(),
  928. quotaCost
  929. });
  930. youtubeApiRequest.save();
  931. const { ...keylessParams } = payload.params;
  932. CacheModule.runJob("HSET", {
  933. table: "youtubeApiRequestParams",
  934. key: youtubeApiRequest._id.toString(),
  935. value: JSON.stringify(keylessParams)
  936. }).then();
  937. YouTubeModule.apiCalls.push({ date: youtubeApiRequest.date, quotaCost });
  938. YouTubeModule.axios
  939. .get(url, {
  940. params,
  941. timeout: YouTubeModule.requestTimeout
  942. })
  943. .then(response => {
  944. if (response.data.error) {
  945. reject(new Error(response.data.error));
  946. } else {
  947. CacheModule.runJob("HSET", {
  948. table: "youtubeApiRequestResults",
  949. key: youtubeApiRequest._id.toString(),
  950. value: JSON.stringify(response.data)
  951. }).then();
  952. resolve({ response });
  953. }
  954. })
  955. .catch(err => {
  956. reject(err);
  957. });
  958. }
  959. });
  960. }
  961. /**
  962. * Fetch all api requests
  963. * @param {object} payload - object that contains the payload
  964. * @param {object} payload.fromDate - data to fetch requests up to
  965. * @returns {Promise} - returns promise (reject, resolve)
  966. */
  967. GET_API_REQUESTS(payload) {
  968. return new Promise((resolve, reject) => {
  969. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  970. YouTubeModule.youtubeApiRequestModel
  971. .find({ date: { $lte: fromDate } })
  972. .sort({ date: -1 })
  973. .exec((err, youtubeApiRequests) => {
  974. if (err) reject(new Error("Couldn't load YouTube API requests."));
  975. else {
  976. resolve({ apiRequests: youtubeApiRequests });
  977. }
  978. });
  979. });
  980. }
  981. /**
  982. * Fetch an api request
  983. * @param {object} payload - object that contains the payload
  984. * @param {object} payload.apiRequestId - the api request id
  985. * @returns {Promise} - returns promise (reject, resolve)
  986. */
  987. GET_API_REQUEST(payload) {
  988. return new Promise((resolve, reject) => {
  989. const { apiRequestId } = payload;
  990. async.waterfall(
  991. [
  992. next => {
  993. YouTubeModule.youtubeApiRequestModel.findOne({ _id: apiRequestId }).exec(next);
  994. },
  995. (apiRequest, next) => {
  996. CacheModule.runJob(
  997. "HGET",
  998. {
  999. table: "youtubeApiRequestParams",
  1000. key: apiRequestId.toString()
  1001. },
  1002. this
  1003. )
  1004. .then(apiRequestParams => {
  1005. next(null, {
  1006. ...apiRequest._doc,
  1007. params: apiRequestParams
  1008. });
  1009. })
  1010. .catch(err => next(err));
  1011. },
  1012. (apiRequest, next) => {
  1013. CacheModule.runJob(
  1014. "HGET",
  1015. {
  1016. table: "youtubeApiRequestResults",
  1017. key: apiRequestId.toString()
  1018. },
  1019. this
  1020. )
  1021. .then(apiRequestResults => {
  1022. next(null, {
  1023. ...apiRequest,
  1024. results: apiRequestResults
  1025. });
  1026. })
  1027. .catch(err => next(err));
  1028. }
  1029. ],
  1030. (err, apiRequest) => {
  1031. if (err) reject(new Error(err));
  1032. else resolve({ apiRequest });
  1033. }
  1034. );
  1035. });
  1036. }
  1037. /**
  1038. * Removed all stored api requests from mongo and redis
  1039. * @returns {Promise} - returns promise (reject, resolve)
  1040. */
  1041. RESET_STORED_API_REQUESTS() {
  1042. return new Promise((resolve, reject) => {
  1043. async.waterfall(
  1044. [
  1045. next => {
  1046. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 1)` });
  1047. YouTubeModule.youtubeApiRequestModel.find({}, next);
  1048. },
  1049. (apiRequests, next) => {
  1050. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 2)` });
  1051. YouTubeModule.youtubeApiRequestModel.deleteMany({}, err => {
  1052. if (err) next("Couldn't reset stored YouTube API requests.");
  1053. else {
  1054. next(null, apiRequests);
  1055. }
  1056. });
  1057. },
  1058. (apiRequests, next) => {
  1059. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 3)` });
  1060. CacheModule.runJob("DEL", { key: "youtubeApiRequestParams" }, this)
  1061. .then(() => next(null, apiRequests))
  1062. .catch(err => next(err));
  1063. },
  1064. (apiRequests, next) => {
  1065. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 4)` });
  1066. CacheModule.runJob("DEL", { key: "youtubeApiRequestResults" }, this)
  1067. .then(() => next(null, apiRequests))
  1068. .catch(err => next(err));
  1069. },
  1070. (apiRequests, next) => {
  1071. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 5)` });
  1072. async.eachLimit(
  1073. apiRequests.map(apiRequest => apiRequest._id),
  1074. 1,
  1075. (requestId, next) => {
  1076. CacheModule.runJob(
  1077. "PUB",
  1078. {
  1079. channel: "youtube.removeYoutubeApiRequest",
  1080. value: requestId
  1081. },
  1082. this
  1083. )
  1084. .then(() => {
  1085. next();
  1086. })
  1087. .catch(err => {
  1088. next(err);
  1089. });
  1090. },
  1091. err => {
  1092. if (err) next(err);
  1093. else next();
  1094. }
  1095. );
  1096. }
  1097. ],
  1098. err => {
  1099. if (err) reject(new Error(err));
  1100. else resolve();
  1101. }
  1102. );
  1103. });
  1104. }
  1105. /**
  1106. * Remove a stored api request
  1107. * @param {object} payload - object that contains the payload
  1108. * @param {object} payload.requestId - the api request id
  1109. * @returns {Promise} - returns promise (reject, resolve)
  1110. */
  1111. REMOVE_STORED_API_REQUEST(payload) {
  1112. return new Promise((resolve, reject) => {
  1113. async.waterfall(
  1114. [
  1115. next => {
  1116. YouTubeModule.youtubeApiRequestModel.deleteOne({ _id: payload.requestId }, err => {
  1117. if (err) next("Couldn't remove stored YouTube API request.");
  1118. else {
  1119. next();
  1120. }
  1121. });
  1122. },
  1123. next => {
  1124. CacheModule.runJob(
  1125. "HDEL",
  1126. {
  1127. table: "youtubeApiRequestParams",
  1128. key: payload.requestId.toString()
  1129. },
  1130. this
  1131. )
  1132. .then(next)
  1133. .catch(err => next(err));
  1134. },
  1135. next => {
  1136. CacheModule.runJob(
  1137. "HDEL",
  1138. {
  1139. table: "youtubeApiRequestResults",
  1140. key: payload.requestId.toString()
  1141. },
  1142. this
  1143. )
  1144. .then(next)
  1145. .catch(err => next(err));
  1146. },
  1147. next => {
  1148. CacheModule.runJob("PUB", {
  1149. channel: "youtube.removeYoutubeApiRequest",
  1150. value: payload.requestId.toString()
  1151. })
  1152. .then(next)
  1153. .catch(err => next(err));
  1154. }
  1155. ],
  1156. err => {
  1157. if (err) reject(new Error(err));
  1158. else resolve();
  1159. }
  1160. );
  1161. });
  1162. }
  1163. /**
  1164. * Create YouTube videos
  1165. * @param {object} payload - an object containing the payload
  1166. * @param {Array | object} payload.youtubeVideos - the youtubeVideo object or array of
  1167. * @returns {Promise} - returns a promise (resolve, reject)
  1168. */
  1169. CREATE_VIDEOS(payload) {
  1170. return new Promise((resolve, reject) => {
  1171. async.waterfall(
  1172. [
  1173. next => {
  1174. let { youtubeVideos } = payload;
  1175. if (typeof youtubeVideos !== "object") next("Invalid youtubeVideos type");
  1176. else {
  1177. if (!Array.isArray(youtubeVideos)) youtubeVideos = [youtubeVideos];
  1178. YouTubeModule.youtubeVideoModel.insertMany(youtubeVideos, next);
  1179. }
  1180. },
  1181. (youtubeVideos, next) => {
  1182. // TODO support spotify here
  1183. const mediaSources = youtubeVideos.map(video => `youtube:${video.youtubeId}`);
  1184. async.eachLimit(
  1185. mediaSources,
  1186. 2,
  1187. (mediaSource, next) => {
  1188. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  1189. .then(() => next())
  1190. .catch(next);
  1191. },
  1192. err => {
  1193. if (err) next(err);
  1194. else next(null, youtubeVideos);
  1195. }
  1196. );
  1197. }
  1198. ],
  1199. (err, youtubeVideos) => {
  1200. if (err) reject(new Error(err));
  1201. else resolve({ youtubeVideos });
  1202. }
  1203. );
  1204. });
  1205. }
  1206. /**
  1207. * Get YouTube videos
  1208. * @param {object} payload - an object containing the payload
  1209. * @param {Array} payload.identifiers - an array of YouTube video ObjectId's or YouTube ID's
  1210. * @param {boolean} payload.createMissing - attempt to fetch and create video's if not in db
  1211. * @param {boolean} payload.replaceExisting - replace existing
  1212. * @returns {Promise} - returns a promise (resolve, reject)
  1213. */
  1214. async GET_VIDEOS(payload) {
  1215. const getVideosFromYoutubeIds = async youtubeIds => {
  1216. const jobsToRun = [];
  1217. const chunkSize = 50;
  1218. while (youtubeIds.length > 0) {
  1219. const chunkedYoutubeIds = youtubeIds.splice(0, chunkSize);
  1220. const params = {
  1221. part: "snippet,contentDetails,statistics,status",
  1222. id: chunkedYoutubeIds.join(",")
  1223. };
  1224. jobsToRun.push(YouTubeModule.runJob("API_GET_VIDEOS", { params }, this));
  1225. }
  1226. const jobResponses = await Promise.all(jobsToRun);
  1227. return jobResponses
  1228. .map(jobResponse => jobResponse.response.data.items)
  1229. .flat()
  1230. .map(item => {
  1231. // TODO Clean up duration converter
  1232. let dur = item.contentDetails.duration;
  1233. dur = dur.replace("PT", "");
  1234. let duration = 0;
  1235. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  1236. v2 = Number(v2);
  1237. duration = v2 * 60 * 60;
  1238. return "";
  1239. });
  1240. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  1241. v2 = Number(v2);
  1242. duration += v2 * 60;
  1243. return "";
  1244. });
  1245. dur.replace(/([\d]*)S/, (v, v2) => {
  1246. v2 = Number(v2);
  1247. duration += v2;
  1248. return "";
  1249. });
  1250. const youtubeVideo = {
  1251. youtubeId: item.id,
  1252. title: item.snippet.title,
  1253. author: item.snippet.channelTitle,
  1254. thumbnail: item.snippet.thumbnails.default.url,
  1255. duration,
  1256. uploadedAt: new Date(item.snippet.publishedAt),
  1257. rawData: item
  1258. };
  1259. return youtubeVideo;
  1260. });
  1261. };
  1262. const { identifiers, createMissing, replaceExisting } = payload;
  1263. const youtubeIds = identifiers.filter(identifier => !mongoose.Types.ObjectId.isValid(identifier));
  1264. const objectIds = identifiers.filter(identifier => mongoose.Types.ObjectId.isValid(identifier));
  1265. const existingVideos = (await YouTubeModule.youtubeVideoModel.find({ youtubeId: youtubeIds }))
  1266. .concat(await YouTubeModule.youtubeVideoModel.find({ _id: objectIds }))
  1267. .map(video => video._doc);
  1268. const existingYoutubeIds = existingVideos.map(existingVideo => existingVideo.youtubeId);
  1269. // const existingYoutubeObjectIds = existingVideos.map(existingVideo => existingVideo._id.toString());
  1270. if (!replaceExisting) {
  1271. if (!createMissing) return { videos: existingVideos };
  1272. if (identifiers.length === existingVideos.length || youtubeIds.length === 0)
  1273. return { videos: existingVideos };
  1274. const missingYoutubeIds = youtubeIds.filter(youtubeId => existingYoutubeIds.indexOf(youtubeId) === -1);
  1275. if (missingYoutubeIds.length === 0) return { videos: existingVideos };
  1276. const newVideos = await getVideosFromYoutubeIds(missingYoutubeIds);
  1277. await YouTubeModule.runJob("CREATE_VIDEOS", { youtubeVideos: newVideos }, this);
  1278. return { videos: existingVideos.concat(newVideos) };
  1279. }
  1280. const newVideos = await getVideosFromYoutubeIds(existingYoutubeIds);
  1281. const promises = newVideos.map(newVideo =>
  1282. YouTubeModule.youtubeVideoModel.updateOne(
  1283. { youtubeId: newVideo.youtubeId },
  1284. { $set: { ...newVideo, updatedAt: Date.now(), documentVersion: 2 } }
  1285. )
  1286. );
  1287. await Promise.allSettled(promises);
  1288. return { videos: newVideos };
  1289. }
  1290. /**
  1291. * Get YouTube channels
  1292. * @param {object} payload - an object containing the payload
  1293. * @param {Array} payload.channelIds - an array of YouTube channel id's
  1294. * @returns {Promise} - returns a promise (resolve, reject)
  1295. */
  1296. async GET_CHANNELS_FROM_IDS(payload) {
  1297. const getChannels = async channelIds => {
  1298. const jobsToRun = [];
  1299. const chunkSize = 50;
  1300. while (channelIds.length > 0) {
  1301. const chunkedChannelIds = channelIds.splice(0, chunkSize);
  1302. const params = {
  1303. part: [
  1304. "brandingSettings",
  1305. "contentDetails",
  1306. "contentOwnerDetails",
  1307. "id",
  1308. "localizations",
  1309. "snippet",
  1310. "statistics",
  1311. "status",
  1312. "topicDetails"
  1313. ].join(","),
  1314. id: chunkedChannelIds.join(",")
  1315. };
  1316. jobsToRun.push(YouTubeModule.runJob("API_GET_CHANNELS", { params }, this));
  1317. }
  1318. const jobResponses = await Promise.all(jobsToRun);
  1319. return jobResponses
  1320. .map(jobResponse => jobResponse.response.data.items)
  1321. .flat()
  1322. .map(item => {
  1323. const youtubeChannel = {
  1324. channelId: item.id,
  1325. title: item.snippet.title,
  1326. customUrl: item.snippet.customUrl,
  1327. rawData: item
  1328. };
  1329. return youtubeChannel;
  1330. });
  1331. };
  1332. const { channelIds } = payload;
  1333. const existingChannels = (await YouTubeModule.youtubeChannelModel.find({ channelId: channelIds })).map(
  1334. channel => channel._doc
  1335. );
  1336. const existingChannelIds = existingChannels.map(existingChannel => existingChannel.channelId);
  1337. // const existingChannelObjectIds = existingChannels.map(existingChannel => existingChannel._id.toString());
  1338. if (channelIds.length === existingChannels.length) return { channels: existingChannels };
  1339. const missingChannelIds = channelIds.filter(channelId => existingChannelIds.indexOf(channelId) === -1);
  1340. if (missingChannelIds.length === 0) return { videos: existingChannels };
  1341. const newChannels = await getChannels(missingChannelIds);
  1342. await YouTubeModule.youtubeChannelModel.insertMany(newChannels);
  1343. return { channels: existingChannels.concat(newChannels) };
  1344. }
  1345. /**
  1346. * Remove YouTube videos
  1347. * @param {object} payload - an object containing the payload
  1348. * @param {string} payload.videoIds - Array of youtubeVideo ObjectIds
  1349. * @returns {Promise} - returns a promise (resolve, reject)
  1350. */
  1351. REMOVE_VIDEOS(payload) {
  1352. return new Promise((resolve, reject) => {
  1353. let { videoIds } = payload;
  1354. if (!Array.isArray(videoIds)) videoIds = [videoIds];
  1355. async.waterfall(
  1356. [
  1357. next => {
  1358. if (!videoIds.every(videoId => mongoose.Types.ObjectId.isValid(videoId)))
  1359. next("One or more videoIds are not a valid ObjectId.");
  1360. else {
  1361. this.publishProgress({ status: "update", message: `Removing video (stage 1)` });
  1362. YouTubeModule.youtubeVideoModel.find({ _id: { $in: videoIds } }, (err, videos) => {
  1363. if (err) next(err);
  1364. else
  1365. next(
  1366. null,
  1367. videos.map(video => video.youtubeId)
  1368. );
  1369. });
  1370. }
  1371. },
  1372. (youtubeIds, next) => {
  1373. this.publishProgress({ status: "update", message: `Removing video (stage 2)` });
  1374. SongsModule.SongModel.find({ youtubeId: { $in: youtubeIds } }, (err, songs) => {
  1375. if (err) next(err);
  1376. else {
  1377. const filteredIds = youtubeIds.filter(
  1378. youtubeId => !songs.find(song => song.youtubeId === youtubeId)
  1379. );
  1380. if (filteredIds.length < youtubeIds.length)
  1381. next("One or more videos are attached to songs.");
  1382. else next(null, filteredIds);
  1383. }
  1384. });
  1385. },
  1386. (youtubeIds, next) => {
  1387. this.publishProgress({ status: "update", message: `Removing video (stage 3)` });
  1388. MediaModule.runJob("REMOVE_RATINGS", { youtubeIds }, this)
  1389. .then(() => next(null, youtubeIds))
  1390. .catch(next);
  1391. },
  1392. (youtubeIds, next) => {
  1393. this.publishProgress({ status: "update", message: `Removing video (stage 4)` });
  1394. async.eachLimit(
  1395. youtubeIds,
  1396. 2,
  1397. (youtubeId, next) => {
  1398. async.waterfall(
  1399. [
  1400. next => {
  1401. PlaylistsModule.playlistModel.find(
  1402. { "songs.youtubeId": youtubeId },
  1403. (err, playlists) => {
  1404. if (err) next(err);
  1405. else {
  1406. async.eachLimit(
  1407. playlists,
  1408. 1,
  1409. (playlist, next) => {
  1410. PlaylistsModule.runJob(
  1411. "REMOVE_FROM_PLAYLIST",
  1412. { playlistId: playlist._id, youtubeId },
  1413. this
  1414. )
  1415. .then(() => next())
  1416. .catch(next);
  1417. },
  1418. next
  1419. );
  1420. }
  1421. }
  1422. );
  1423. },
  1424. next => {
  1425. StationsModule.stationModel.find(
  1426. { "queue.youtubeId": youtubeId },
  1427. (err, stations) => {
  1428. if (err) next(err);
  1429. else {
  1430. async.eachLimit(
  1431. stations,
  1432. 1,
  1433. (station, next) => {
  1434. StationsModule.runJob(
  1435. "REMOVE_FROM_QUEUE",
  1436. { stationId: station._id, youtubeId },
  1437. this
  1438. )
  1439. .then(() => next())
  1440. .catch(err => {
  1441. if (
  1442. err === "Station not found" ||
  1443. err ===
  1444. "Song is not currently in the queue."
  1445. )
  1446. next();
  1447. else next(err);
  1448. });
  1449. },
  1450. next
  1451. );
  1452. }
  1453. }
  1454. );
  1455. },
  1456. next => {
  1457. StationsModule.stationModel.find(
  1458. { "currentSong.youtubeId": youtubeId },
  1459. (err, stations) => {
  1460. if (err) next(err);
  1461. else {
  1462. async.eachLimit(
  1463. stations,
  1464. 1,
  1465. (station, next) => {
  1466. StationsModule.runJob(
  1467. "SKIP_STATION",
  1468. {
  1469. stationId: station._id,
  1470. natural: false,
  1471. skipReason: "other"
  1472. },
  1473. this
  1474. )
  1475. .then(() => {
  1476. next();
  1477. })
  1478. .catch(err => {
  1479. if (err.message === "Station not found.")
  1480. next();
  1481. else next(err);
  1482. });
  1483. },
  1484. next
  1485. );
  1486. }
  1487. }
  1488. );
  1489. }
  1490. ],
  1491. next
  1492. );
  1493. },
  1494. next
  1495. );
  1496. },
  1497. next => {
  1498. this.publishProgress({ status: "update", message: `Removing video (stage 5)` });
  1499. YouTubeModule.youtubeVideoModel.deleteMany({ _id: { $in: videoIds } }, next);
  1500. },
  1501. (res, next) => {
  1502. this.publishProgress({ status: "update", message: `Removing video (stage 6)` });
  1503. CacheModule.runJob("PUB", {
  1504. channel: "youtube.removeVideos",
  1505. value: videoIds
  1506. })
  1507. .then(next)
  1508. .catch(err => next(err));
  1509. }
  1510. ],
  1511. err => {
  1512. if (err) reject(new Error(err));
  1513. else resolve();
  1514. }
  1515. );
  1516. });
  1517. }
  1518. /**
  1519. * Request a set of YouTube videos
  1520. * @param {object} payload - an object containing the payload
  1521. * @param {string} payload.url - the url of the the YouTube playlist or channel
  1522. * @param {boolean} payload.musicOnly - whether to only get music from the playlist/channel
  1523. * @param {boolean} payload.returnVideos - whether to return videos
  1524. * @returns {Promise} - returns a promise (resolve, reject)
  1525. */
  1526. REQUEST_SET(payload) {
  1527. return new Promise((resolve, reject) => {
  1528. async.waterfall(
  1529. [
  1530. next => {
  1531. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1532. const channelRegex =
  1533. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1534. if (playlistRegex.exec(payload.url) || channelRegex.exec(payload.url))
  1535. YouTubeModule.runJob(
  1536. playlistRegex.exec(payload.url) ? "GET_PLAYLIST" : "GET_CHANNEL_VIDEOS",
  1537. {
  1538. url: payload.url,
  1539. musicOnly: payload.musicOnly
  1540. },
  1541. this
  1542. )
  1543. .then(res => {
  1544. next(null, res.songs);
  1545. })
  1546. .catch(next);
  1547. else next("Invalid YouTube URL.");
  1548. },
  1549. async youtubeIds => {
  1550. if (youtubeIds.length === 0) return { videos: [] };
  1551. const { videos } = await YouTubeModule.runJob(
  1552. "GET_VIDEOS",
  1553. { identifiers: youtubeIds, createMissing: true },
  1554. this
  1555. );
  1556. return { videos };
  1557. }
  1558. ],
  1559. (err, response) => {
  1560. if (err) reject(new Error(err));
  1561. else resolve(response);
  1562. }
  1563. );
  1564. });
  1565. }
  1566. /**
  1567. * Gets missing YouTube video's from all playlists, stations and songs
  1568. * @returns {Promise} - returns a promise (resolve, reject)
  1569. */
  1570. async GET_MISSING_VIDEOS() {
  1571. const youtubeIds = Array.from(
  1572. new Set(
  1573. [
  1574. ...(await SongsModule.runJob("GET_ALL_MEDIA_SOURCES", {}, this)),
  1575. ...(await PlaylistsModule.runJob("GET_ALL_MEDIA_SOURCES", {}, this))
  1576. ]
  1577. .filter(mediaSource => mediaSource.startsWith("youtube:"))
  1578. .map(mediaSource => mediaSource.split(":")[1])
  1579. )
  1580. );
  1581. const existingYoutubeIds = await YouTubeModule.youtubeVideoModel.distinct("youtubeId");
  1582. const missingYoutubeIds = youtubeIds.filter(youtubeId => existingYoutubeIds.indexOf(youtubeId) === -1);
  1583. const res = await YouTubeModule.runJob(
  1584. "GET_VIDEOS",
  1585. { identifiers: missingYoutubeIds, createMissing: true },
  1586. this
  1587. );
  1588. const gotVideos = res.videos;
  1589. return {
  1590. all: youtubeIds.length,
  1591. existing: existingYoutubeIds.length,
  1592. missing: missingYoutubeIds.length,
  1593. got: gotVideos.length
  1594. };
  1595. }
  1596. /**
  1597. * Updates videos from version 1 to version 2
  1598. * @returns {Promise} - returns a promise (resolve, reject)
  1599. */
  1600. async UPDATE_VIDEOS_V1_TO_V2() {
  1601. const videoIds = await YouTubeModule.youtubeVideoModel.distinct("_id", { documentVersion: 1 });
  1602. const res = await YouTubeModule.runJob("GET_VIDEOS", { identifiers: videoIds, replaceExisting: true }, this);
  1603. const v1 = videoIds.length;
  1604. const v2 = res.videos.length;
  1605. return {
  1606. v1,
  1607. v2
  1608. };
  1609. }
  1610. /**
  1611. * Gets missing YouTube channels based on cached YouTube video's
  1612. * @returns {Promise} - returns a promise (resolve, reject)
  1613. */
  1614. async GET_MISSING_CHANNELS() {
  1615. const currentChannelIds = await YouTubeModule.youtubeChannelModel.distinct("channelId");
  1616. const videoChannelIds = await YouTubeModule.youtubeVideoModel.distinct("rawData.snippet.channelId");
  1617. const missingChannelIds = videoChannelIds.filter(channelId => currentChannelIds.indexOf(channelId) === -1);
  1618. const res = await YouTubeModule.runJob("GET_CHANNELS_FROM_IDS", { channelIds: missingChannelIds }, this);
  1619. const gotChannels = res.channels;
  1620. return {
  1621. current: currentChannelIds.length,
  1622. all: videoChannelIds.length,
  1623. missing: missingChannelIds.length,
  1624. got: gotChannels.length
  1625. };
  1626. }
  1627. }
  1628. export default new _YouTubeModule();