youtube.js 53 KB

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