youtube.js 55 KB

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