youtube.js 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107
  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 from a username
  413. * @param {object} payload - object that contains the payload
  414. * @param {string} payload.username - the username of the YouTube channel
  415. * @returns {Promise} - returns promise (reject, resolve)
  416. */
  417. GET_CHANNEL_ID_FROM_USERNAME(payload) {
  418. return new Promise((resolve, reject) => {
  419. const params = {
  420. part: "id"
  421. };
  422. params.forUsername = payload.username;
  423. YouTubeModule.runJob(
  424. "API_GET_CHANNELS",
  425. {
  426. params
  427. },
  428. this
  429. )
  430. .then(({ response }) => {
  431. const { data } = response;
  432. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  433. const channelId = data.items[0].id;
  434. return resolve({ channelId });
  435. })
  436. .catch(err => {
  437. YouTubeModule.log("ERROR", "GET_CHANNEL_ID_FROM_USERNAME", `${err.message}`);
  438. if (err.message === "Request failed with status code 404")
  439. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  440. if (err.message === "Searching with YouTube is disabled.") return reject(err);
  441. return reject(new Error("An error has occured. Please try again later."));
  442. });
  443. });
  444. }
  445. /**
  446. * Gets the id of the channel upload playlist
  447. * @param {object} payload - object that contains the payload
  448. * @param {string} payload.id - the id of the YouTube channel. Optional: can be left out if specifying a username.
  449. * @param {string} payload.username - the username of the YouTube channel. Only gets used if no id is specified.
  450. * @returns {Promise} - returns promise (reject, resolve)
  451. */
  452. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  453. return new Promise((resolve, reject) => {
  454. const params = {
  455. part: "id,contentDetails"
  456. };
  457. if (payload.id) params.id = payload.id;
  458. else params.forUsername = payload.username;
  459. YouTubeModule.runJob(
  460. "API_GET_CHANNELS",
  461. {
  462. params
  463. },
  464. this
  465. )
  466. .then(({ response }) => {
  467. const { data } = response;
  468. if (data.pageInfo.totalResults === 0) return reject(new Error("Channel not found."));
  469. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  470. return resolve({ playlistId });
  471. })
  472. .catch(err => {
  473. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  474. if (err.message === "Request failed with status code 404")
  475. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  476. if (err.message === "Searching with YouTube is disabled.") return reject(err);
  477. return reject(new Error("An error has occured. Please try again later."));
  478. });
  479. });
  480. }
  481. /**
  482. * Gets the id of the channel from the custom URL
  483. * @param {object} payload - object that contains the payload
  484. * @param {string} payload.customUrl - the customUrl of the YouTube channel
  485. * @returns {Promise} - returns promise (reject, resolve)
  486. */
  487. GET_CHANNEL_ID_FROM_CUSTOM_URL(payload) {
  488. return new Promise((resolve, reject) => {
  489. async.waterfall(
  490. [
  491. next => {
  492. const params = {
  493. part: "snippet",
  494. type: "channel",
  495. maxResults: 50
  496. };
  497. params.q = payload.customUrl;
  498. YouTubeModule.runJob(
  499. "API_SEARCH",
  500. {
  501. params
  502. },
  503. this
  504. )
  505. .then(({ response }) => {
  506. const { data } = response;
  507. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  508. const channelIds = data.items.map(item => item.id.channelId);
  509. return next(null, channelIds);
  510. })
  511. .catch(err => {
  512. next(err);
  513. });
  514. },
  515. (channelIds, next) => {
  516. const params = {
  517. part: "snippet",
  518. id: channelIds.join(","),
  519. maxResults: 50
  520. };
  521. YouTubeModule.runJob(
  522. "API_GET_CHANNELS",
  523. {
  524. params
  525. },
  526. this
  527. )
  528. .then(({ response }) => {
  529. const { data } = response;
  530. if (data.pageInfo.totalResults === 0) return next("Channel not found.");
  531. let channelId = null;
  532. data.items.forEach(item => {
  533. if (
  534. item.snippet.customUrl &&
  535. item.snippet.customUrl.toLowerCase() === payload.customUrl.toLowerCase()
  536. ) {
  537. channelId = item.id;
  538. }
  539. });
  540. if (!channelId) return next("Channel not found.");
  541. return next(null, channelId);
  542. })
  543. .catch(err => {
  544. next(err);
  545. });
  546. }
  547. ],
  548. (err, channelId) => {
  549. if (err) {
  550. YouTubeModule.log("ERROR", "GET_CHANNEL_ID_FROM_CUSTOM_URL", `${err.message || err}`);
  551. if (err.message === "Request failed with status code 404")
  552. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  553. if (err.message === "Searching with YouTube is disabled.") return reject(err);
  554. return reject(new Error("An error has occured. Please try again later."));
  555. }
  556. return resolve({ channelId });
  557. }
  558. );
  559. });
  560. }
  561. /**
  562. * Returns an array of songs taken from a YouTube playlist
  563. * @param {object} payload - object that contains the payload
  564. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  565. * @param {string} payload.url - the url of the YouTube playlist
  566. * @returns {Promise} - returns promise (reject, resolve)
  567. */
  568. GET_PLAYLIST(payload) {
  569. return new Promise((resolve, reject) => {
  570. const regex = /[\\?&]list=([^&#]*)/;
  571. const splitQuery = regex.exec(payload.url);
  572. if (!splitQuery) {
  573. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  574. reject(new Error("Invalid playlist URL."));
  575. return;
  576. }
  577. const playlistId = splitQuery[1];
  578. let currentPage = 0;
  579. async.waterfall(
  580. [
  581. next => {
  582. YouTubeModule.runJob(
  583. "GET_PLAYLIST_INFO",
  584. {
  585. playlistId
  586. },
  587. this
  588. )
  589. .then(playlistInfo => {
  590. next(null, playlistInfo);
  591. })
  592. .catch(err => {
  593. console.log(123, err);
  594. next(err);
  595. });
  596. },
  597. (playlistInfo, next) => {
  598. if (playlistInfo.privacyStatus === "private") return next(new Error("Playlist is private."));
  599. const maxPages = playlistInfo.isMix
  600. ? 4
  601. : Number.parseInt(config.get("apis.youtube.maxPlaylistPages"));
  602. return next(null, maxPages, playlistInfo.isMix);
  603. },
  604. (maxPages, isMix, next) => {
  605. let songs = [];
  606. let nextPageToken = "";
  607. async.whilst(
  608. next => {
  609. if (payload.max > 0 && songs.length > payload.max) return next(null, false);
  610. if (nextPageToken === undefined) return next(null, false);
  611. if (currentPage >= maxPages) {
  612. YouTubeModule.log(
  613. isMix ? "INFO" : "ERROR",
  614. `Playlist ${playlistId}${
  615. isMix ? " (mix)" : ""
  616. } for job (${this.toString()}) has reached the max page limit.`
  617. );
  618. return next(null, false);
  619. }
  620. return next(null, true);
  621. },
  622. next => {
  623. currentPage += 1;
  624. YouTubeModule.log(
  625. "INFO",
  626. `Getting playlist progress for job (${this.toString()}): ${songs.length} songs gotten so far. Current page: ${currentPage}. Max: ${payload.max}.`
  627. );
  628. // Add 250ms delay between each job request
  629. setTimeout(() => {
  630. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  631. .then(response => {
  632. songs = songs.concat(response.songs);
  633. nextPageToken = response.nextPageToken;
  634. next();
  635. })
  636. .catch(err => next(err));
  637. }, 250);
  638. },
  639. err => next(err, songs)
  640. );
  641. },
  642. (songs, next) =>
  643. next(
  644. null,
  645. songs.map(song => song.contentDetails.videoId)
  646. ),
  647. (songs, next) => {
  648. if (payload.max > 0) songs.splice(payload.max);
  649. if (!payload.musicOnly) return next(true, { songs });
  650. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  651. .then(filteredSongs => next(null, { filteredSongs, songs }))
  652. .catch(next);
  653. }
  654. ],
  655. (err, response) => {
  656. if (err && err !== true) {
  657. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  658. reject(new Error(err.message));
  659. } else {
  660. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  661. }
  662. }
  663. );
  664. });
  665. }
  666. /**
  667. * Returns playlist info
  668. * @param {object} payload - object that contains the payload
  669. * @param {string} payload.playlistId - the playlist id
  670. * @returns {Promise} - returns promise (reject, resolve)
  671. */
  672. async GET_PLAYLIST_INFO(payload) {
  673. const { playlistId } = payload;
  674. const part = ["id", "snippet", "status", "localizations"].join(",");
  675. const params = {
  676. part,
  677. id: playlistId
  678. };
  679. const { response } = await YouTubeModule.runJob("API_GET_PLAYLIST", { params }, this);
  680. const [playlistInfo] = response.data.items;
  681. const channelId = playlistInfo?.snippet?.channelId;
  682. const title = playlistInfo?.snippet?.title;
  683. const enTitle = playlistInfo?.localizations?.en?.title;
  684. const privacyStatus = playlistInfo?.status?.privacyStatus;
  685. // Another way to possibly check for mix is if the first two letters of the playlist ID starts with RD
  686. const isMix =
  687. channelId === YOUTUBE_OFFICIAL_CHANNEL_ID &&
  688. (title?.startsWith(YOUTUBE_MIX_PLAYLIST_TITLE_PREFIX) ||
  689. enTitle?.startsWith(YOUTUBE_MIX_PLAYLIST_TITLE_PREFIX));
  690. return {
  691. channelId,
  692. title,
  693. enTitle,
  694. privacyStatus,
  695. isMix
  696. };
  697. }
  698. /**
  699. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST and GET_CHANNEL_VIDEOS.
  700. * @param {object} payload - object that contains the payload
  701. * @param {boolean} payload.playlistId - the playlist id to get videos from
  702. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  703. * @param {string} payload.url - the url of the YouTube playlist
  704. * @returns {Promise} - returns promise (reject, resolve)
  705. */
  706. GET_PLAYLIST_PAGE(payload) {
  707. return new Promise((resolve, reject) => {
  708. const params = {
  709. part: "contentDetails",
  710. playlistId: payload.playlistId,
  711. maxResults: 50
  712. };
  713. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  714. YouTubeModule.runJob(
  715. "API_GET_PLAYLIST_ITEMS",
  716. {
  717. params
  718. },
  719. this
  720. )
  721. .then(({ response }) => {
  722. const { data } = response;
  723. const songs = data.items;
  724. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  725. return resolve({ songs });
  726. })
  727. .catch(err => {
  728. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  729. if (err.message === "Request failed with status code 404")
  730. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  731. return reject(new Error("An error has occured. Please try again later."));
  732. });
  733. });
  734. }
  735. /**
  736. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  737. * @param {object} payload - object that contains the payload
  738. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  739. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  740. * @returns {Promise} - returns promise (reject, resolve)
  741. */
  742. FILTER_MUSIC_VIDEOS(payload) {
  743. return new Promise((resolve, reject) => {
  744. const page = payload.page ? payload.page : 0;
  745. const videosPerPage = 50;
  746. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  747. if (localVideoIds.length === 0) {
  748. resolve({ videoIds: [] });
  749. return;
  750. }
  751. const params = {
  752. part: "topicDetails",
  753. id: localVideoIds.join(","),
  754. maxResults: videosPerPage
  755. };
  756. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  757. .then(({ response }) => {
  758. const { data } = response;
  759. const videoIds = [];
  760. data.items.forEach(item => {
  761. const videoId = item.id;
  762. if (!item.topicDetails) return;
  763. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  764. videoIds.push(videoId);
  765. });
  766. return YouTubeModule.runJob(
  767. "FILTER_MUSIC_VIDEOS",
  768. { videoIds: payload.videoIds, page: page + 1 },
  769. this
  770. )
  771. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  772. .catch(err => reject(err));
  773. })
  774. .catch(err => {
  775. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  776. return reject(new Error("Failed to find playlist from YouTube"));
  777. });
  778. });
  779. }
  780. /**
  781. * Returns the channel ID from a provided URL
  782. * @param {object} payload - object that contains the payload
  783. * @param {boolean} payload.disableSearch - whether to allow searching for custom url/username
  784. * @param {string} payload.url - the url of the YouTube channel
  785. * @returns {Promise} - returns promise (reject, resolve)
  786. */
  787. GET_CHANNEL_ID(payload) {
  788. return new Promise((resolve, reject) => {
  789. const regex =
  790. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  791. const splitQuery = regex.exec(payload.url);
  792. if (!splitQuery) {
  793. YouTubeModule.log("ERROR", "GET_CHANNEL_ID", "Invalid YouTube channel URL query.");
  794. reject(new Error("Invalid playlist URL."));
  795. return;
  796. }
  797. const channelId = splitQuery[1];
  798. const channelUsername = splitQuery[2];
  799. const channelCustomUrl = splitQuery[3];
  800. const channelUsernameOrCustomUrl = splitQuery[4];
  801. const disableSearch = payload.disableSearch || false;
  802. async.waterfall(
  803. [
  804. next => {
  805. if (channelId) next(true, channelId);
  806. else if (!channelUsername) next(null, true, null);
  807. else {
  808. YouTubeModule.runJob("GET_CHANNEL_ID_FROM_USERNAME", { username: channelUsername }, this)
  809. .then(({ channelId }) => {
  810. next(null, null, channelId);
  811. })
  812. .catch(next);
  813. }
  814. },
  815. (getUsernameFromCustomUrl, channelId, next) => {
  816. if (!getUsernameFromCustomUrl) return next(null, channelId);
  817. if (disableSearch)
  818. return next(
  819. // eslint-disable-next-line
  820. "You are not allowed to look up this type of YouTube channel URL. Please provide a channel URL with the channel ID in it."
  821. );
  822. const payload = {};
  823. if (channelCustomUrl) payload.customUrl = channelCustomUrl;
  824. else if (channelUsernameOrCustomUrl) payload.customUrl = channelUsernameOrCustomUrl;
  825. else return next("No proper URL provided.");
  826. return YouTubeModule.runJob("GET_CHANNEL_ID_FROM_CUSTOM_URL", payload, this)
  827. .then(({ channelId }) => {
  828. next(null, channelId);
  829. })
  830. .catch(err => next(err));
  831. }
  832. ],
  833. (err, channelId) => {
  834. console.log(111, err, channelId);
  835. if (err && err !== true) {
  836. YouTubeModule.log("ERROR", "GET_CHANNEL_ID", "Some error has occurred.", err.message || err);
  837. reject(new Error(err.message || err));
  838. } else {
  839. resolve({ channelId });
  840. }
  841. }
  842. );
  843. });
  844. }
  845. /**
  846. * Returns an array of songs taken from a YouTube channel
  847. * @param {object} payload - object that contains the payload
  848. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the channel
  849. * @param {boolean} payload.disableSearch - whether to allow searching for custom url/username
  850. * @param {string} payload.url - the url of the YouTube channel
  851. * @returns {Promise} - returns promise (reject, resolve)
  852. */
  853. GET_CHANNEL_VIDEOS(payload) {
  854. return new Promise((resolve, reject) => {
  855. const regex =
  856. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  857. const splitQuery = regex.exec(payload.url);
  858. if (!splitQuery) {
  859. YouTubeModule.log("ERROR", "GET_CHANNEL_VIDEOS", "Invalid YouTube channel URL query.");
  860. reject(new Error("Invalid playlist URL."));
  861. return;
  862. }
  863. const channelId = splitQuery[1];
  864. const channelUsername = splitQuery[2];
  865. const channelCustomUrl = splitQuery[3];
  866. const channelUsernameOrCustomUrl = splitQuery[4];
  867. const disableSearch = payload.disableSearch || false;
  868. async.waterfall(
  869. [
  870. next => {
  871. const payload = {};
  872. if (channelId) payload.id = channelId;
  873. else if (channelUsername) payload.username = channelUsername;
  874. else return next(null, true, null);
  875. return YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", payload, this)
  876. .then(({ playlistId }) => {
  877. next(null, false, playlistId);
  878. })
  879. .catch(err => {
  880. if (err.message === "Channel not found. Is the channel public/unlisted?")
  881. next(null, true, null);
  882. else next(err);
  883. });
  884. },
  885. (getUsernameFromCustomUrl, playlistId, next) => {
  886. if (!getUsernameFromCustomUrl) return next(null, playlistId);
  887. if (disableSearch)
  888. return next(
  889. "Importing with this type of URL is disabled. Please provide a channel URL with the channel ID."
  890. );
  891. const payload = {};
  892. if (channelCustomUrl) payload.customUrl = channelCustomUrl;
  893. else if (channelUsernameOrCustomUrl) payload.customUrl = channelUsernameOrCustomUrl;
  894. else return next("No proper URL provided.");
  895. return YouTubeModule.runJob("GET_CHANNEL_ID_FROM_CUSTOM_URL", payload, this)
  896. .then(({ channelId }) => {
  897. YouTubeModule.runJob("GET_CHANNEL_UPLOADS_PLAYLIST_ID", { id: channelId }, this)
  898. .then(({ playlistId }) => {
  899. next(null, playlistId);
  900. })
  901. .catch(err => next(err));
  902. })
  903. .catch(err => next(err));
  904. },
  905. (playlistId, next) => {
  906. let songs = [];
  907. let nextPageToken = "";
  908. async.whilst(
  909. next => {
  910. if (payload.max > 0 && songs.length > payload.max) next(null, false);
  911. else {
  912. YouTubeModule.log(
  913. "INFO",
  914. `Getting channel progress for job (${this.toString()}): ${
  915. songs.length
  916. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  917. );
  918. next(null, nextPageToken !== undefined);
  919. }
  920. },
  921. next => {
  922. // Add 250ms delay between each job request
  923. setTimeout(() => {
  924. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  925. .then(response => {
  926. songs = songs.concat(response.songs);
  927. nextPageToken = response.nextPageToken;
  928. next();
  929. })
  930. .catch(err => next(err));
  931. }, 250);
  932. },
  933. err => next(err, songs)
  934. );
  935. },
  936. (songs, next) =>
  937. next(
  938. null,
  939. songs.map(song => song.contentDetails.videoId)
  940. ),
  941. (songs, next) => {
  942. if (payload.max > 0) songs.splice(payload.max);
  943. if (!payload.musicOnly) return next(true, { songs });
  944. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  945. .then(filteredSongs => next(null, { filteredSongs, songs }))
  946. .catch(next);
  947. }
  948. ],
  949. (err, response) => {
  950. if (err && err !== true) {
  951. YouTubeModule.log("ERROR", "GET_CHANNEL", "Some error has occurred.", err.message || err);
  952. reject(new Error(err.message || err));
  953. } else {
  954. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  955. }
  956. }
  957. );
  958. });
  959. }
  960. /**
  961. * Perform YouTube API get videos request
  962. * @param {object} payload - object that contains the payload
  963. * @param {object} payload.params - request parameters
  964. * @returns {Promise} - returns promise (reject, resolve)
  965. */
  966. API_GET_VIDEOS(payload) {
  967. return new Promise((resolve, reject) => {
  968. const { params } = payload;
  969. YouTubeModule.runJob(
  970. "API_CALL",
  971. {
  972. url: "https://www.googleapis.com/youtube/v3/videos",
  973. params: {
  974. key: config.get("apis.youtube.key"),
  975. ...params
  976. },
  977. quotaCost: 1
  978. },
  979. this
  980. )
  981. .then(response => {
  982. resolve(response);
  983. })
  984. .catch(err => {
  985. reject(err);
  986. });
  987. });
  988. }
  989. /**
  990. * Perform YouTube API get playlist items request
  991. * @param {object} payload - object that contains the payload
  992. * @param {object} payload.params - request parameters
  993. * @returns {Promise} - returns promise (reject, resolve)
  994. */
  995. async API_GET_PLAYLIST(payload) {
  996. const { params } = payload;
  997. return YouTubeModule.runJob(
  998. "API_CALL",
  999. {
  1000. url: "https://www.googleapis.com/youtube/v3/playlists",
  1001. params: {
  1002. key: config.get("apis.youtube.key"),
  1003. ...params
  1004. },
  1005. quotaCost: 1
  1006. },
  1007. this
  1008. );
  1009. }
  1010. /**
  1011. * Perform YouTube API get playlist items request
  1012. * @param {object} payload - object that contains the payload
  1013. * @param {object} payload.params - request parameters
  1014. * @returns {Promise} - returns promise (reject, resolve)
  1015. */
  1016. API_GET_PLAYLIST_ITEMS(payload) {
  1017. return new Promise((resolve, reject) => {
  1018. const { params } = payload;
  1019. YouTubeModule.runJob(
  1020. "API_CALL",
  1021. {
  1022. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  1023. params: {
  1024. key: config.get("apis.youtube.key"),
  1025. ...params
  1026. },
  1027. quotaCost: 1
  1028. },
  1029. this
  1030. )
  1031. .then(response => {
  1032. resolve(response);
  1033. })
  1034. .catch(err => {
  1035. reject(err);
  1036. });
  1037. });
  1038. }
  1039. /**
  1040. * Perform YouTube API get channels request
  1041. * @param {object} payload - object that contains the payload
  1042. * @param {object} payload.params - request parameters
  1043. * @returns {Promise} - returns promise (reject, resolve)
  1044. */
  1045. API_GET_CHANNELS(payload) {
  1046. return new Promise((resolve, reject) => {
  1047. const { params } = payload;
  1048. YouTubeModule.runJob(
  1049. "API_CALL",
  1050. {
  1051. url: "https://www.googleapis.com/youtube/v3/channels",
  1052. params: {
  1053. key: config.get("apis.youtube.key"),
  1054. ...params
  1055. },
  1056. quotaCost: 1
  1057. },
  1058. this
  1059. )
  1060. .then(response => {
  1061. resolve(response);
  1062. })
  1063. .catch(err => {
  1064. reject(err);
  1065. });
  1066. });
  1067. }
  1068. /**
  1069. * Perform YouTube API search request
  1070. * @param {object} payload - object that contains the payload
  1071. * @param {object} payload.params - request parameters
  1072. * @returns {Promise} - returns promise (reject, resolve)
  1073. */
  1074. API_SEARCH(payload) {
  1075. return new Promise((resolve, reject) => {
  1076. const { params } = payload;
  1077. if (config.get("experimental.disable_youtube_search")) {
  1078. reject(new Error("Searching with YouTube is disabled."));
  1079. return;
  1080. }
  1081. YouTubeModule.runJob(
  1082. "API_CALL",
  1083. {
  1084. url: "https://www.googleapis.com/youtube/v3/search",
  1085. params: {
  1086. key: config.get("apis.youtube.key"),
  1087. ...params
  1088. },
  1089. quotaCost: 100
  1090. },
  1091. this
  1092. )
  1093. .then(response => {
  1094. resolve(response);
  1095. })
  1096. .catch(err => {
  1097. reject(err);
  1098. });
  1099. });
  1100. }
  1101. /**
  1102. * Perform YouTube API call
  1103. * @param {object} payload - object that contains the payload
  1104. * @param {object} payload.url - request url
  1105. * @param {object} payload.params - request parameters
  1106. * @param {object} payload.quotaCost - request quotaCost
  1107. * @returns {Promise} - returns promise (reject, resolve)
  1108. */
  1109. API_CALL(payload) {
  1110. return new Promise((resolve, reject) => {
  1111. const { url, params, quotaCost } = payload;
  1112. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  1113. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  1114. else {
  1115. const youtubeApiRequest = new YouTubeModule.YoutubeApiRequestModel({
  1116. url,
  1117. date: Date.now(),
  1118. quotaCost
  1119. });
  1120. youtubeApiRequest.save();
  1121. const { ...keylessParams } = payload.params;
  1122. CacheModule.runJob("HSET", {
  1123. table: "youtubeApiRequestParams",
  1124. key: youtubeApiRequest._id.toString(),
  1125. value: JSON.stringify(keylessParams)
  1126. }).then();
  1127. YouTubeModule.apiCalls.push({ date: youtubeApiRequest.date, quotaCost });
  1128. YouTubeModule.axios
  1129. .get(url, {
  1130. params,
  1131. timeout: YouTubeModule.requestTimeout
  1132. })
  1133. .then(response => {
  1134. if (response.data.error) {
  1135. reject(new Error(response.data.error));
  1136. } else {
  1137. CacheModule.runJob("HSET", {
  1138. table: "youtubeApiRequestResults",
  1139. key: youtubeApiRequest._id.toString(),
  1140. value: JSON.stringify(response.data)
  1141. }).then();
  1142. resolve({ response });
  1143. }
  1144. })
  1145. .catch(err => {
  1146. reject(err);
  1147. });
  1148. }
  1149. });
  1150. }
  1151. /**
  1152. * Fetch all api requests
  1153. * @param {object} payload - object that contains the payload
  1154. * @param {object} payload.fromDate - data to fetch requests up to
  1155. * @returns {Promise} - returns promise (reject, resolve)
  1156. */
  1157. GET_API_REQUESTS(payload) {
  1158. return new Promise((resolve, reject) => {
  1159. const fromDate = payload.fromDate ? new Date(payload.fromDate) : new Date();
  1160. YouTubeModule.youtubeApiRequestModel
  1161. .find({ date: { $lte: fromDate } })
  1162. .sort({ date: -1 })
  1163. .exec((err, youtubeApiRequests) => {
  1164. if (err) reject(new Error("Couldn't load YouTube API requests."));
  1165. else {
  1166. resolve({ apiRequests: youtubeApiRequests });
  1167. }
  1168. });
  1169. });
  1170. }
  1171. /**
  1172. * Fetch an api request
  1173. * @param {object} payload - object that contains the payload
  1174. * @param {object} payload.apiRequestId - the api request id
  1175. * @returns {Promise} - returns promise (reject, resolve)
  1176. */
  1177. GET_API_REQUEST(payload) {
  1178. return new Promise((resolve, reject) => {
  1179. const { apiRequestId } = payload;
  1180. async.waterfall(
  1181. [
  1182. next => {
  1183. YouTubeModule.youtubeApiRequestModel.findOne({ _id: apiRequestId }).exec(next);
  1184. },
  1185. (apiRequest, next) => {
  1186. CacheModule.runJob(
  1187. "HGET",
  1188. {
  1189. table: "youtubeApiRequestParams",
  1190. key: apiRequestId.toString()
  1191. },
  1192. this
  1193. )
  1194. .then(apiRequestParams => {
  1195. next(null, {
  1196. ...apiRequest._doc,
  1197. params: apiRequestParams
  1198. });
  1199. })
  1200. .catch(err => next(err));
  1201. },
  1202. (apiRequest, next) => {
  1203. CacheModule.runJob(
  1204. "HGET",
  1205. {
  1206. table: "youtubeApiRequestResults",
  1207. key: apiRequestId.toString()
  1208. },
  1209. this
  1210. )
  1211. .then(apiRequestResults => {
  1212. next(null, {
  1213. ...apiRequest,
  1214. results: apiRequestResults
  1215. });
  1216. })
  1217. .catch(err => next(err));
  1218. }
  1219. ],
  1220. (err, apiRequest) => {
  1221. if (err) reject(new Error(err));
  1222. else resolve({ apiRequest });
  1223. }
  1224. );
  1225. });
  1226. }
  1227. /**
  1228. * Removed all stored api requests from mongo and redis
  1229. * @returns {Promise} - returns promise (reject, resolve)
  1230. */
  1231. RESET_STORED_API_REQUESTS() {
  1232. return new Promise((resolve, reject) => {
  1233. async.waterfall(
  1234. [
  1235. next => {
  1236. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 1)` });
  1237. YouTubeModule.youtubeApiRequestModel.find({}, next);
  1238. },
  1239. (apiRequests, next) => {
  1240. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 2)` });
  1241. YouTubeModule.youtubeApiRequestModel.deleteMany({}, err => {
  1242. if (err) next("Couldn't reset stored YouTube API requests.");
  1243. else {
  1244. next(null, apiRequests);
  1245. }
  1246. });
  1247. },
  1248. (apiRequests, next) => {
  1249. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 3)` });
  1250. CacheModule.runJob("DEL", { key: "youtubeApiRequestParams" }, this)
  1251. .then(() => next(null, apiRequests))
  1252. .catch(err => next(err));
  1253. },
  1254. (apiRequests, next) => {
  1255. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 4)` });
  1256. CacheModule.runJob("DEL", { key: "youtubeApiRequestResults" }, this)
  1257. .then(() => next(null, apiRequests))
  1258. .catch(err => next(err));
  1259. },
  1260. (apiRequests, next) => {
  1261. this.publishProgress({ status: "update", message: `Resetting stored API requests (stage 5)` });
  1262. async.eachLimit(
  1263. apiRequests.map(apiRequest => apiRequest._id),
  1264. 1,
  1265. (requestId, next) => {
  1266. CacheModule.runJob(
  1267. "PUB",
  1268. {
  1269. channel: "youtube.removeYoutubeApiRequest",
  1270. value: requestId
  1271. },
  1272. this
  1273. )
  1274. .then(() => {
  1275. next();
  1276. })
  1277. .catch(err => {
  1278. next(err);
  1279. });
  1280. },
  1281. err => {
  1282. if (err) next(err);
  1283. else next();
  1284. }
  1285. );
  1286. }
  1287. ],
  1288. err => {
  1289. if (err) reject(new Error(err));
  1290. else resolve();
  1291. }
  1292. );
  1293. });
  1294. }
  1295. /**
  1296. * Remove a stored api request
  1297. * @param {object} payload - object that contains the payload
  1298. * @param {object} payload.requestId - the api request id
  1299. * @returns {Promise} - returns promise (reject, resolve)
  1300. */
  1301. REMOVE_STORED_API_REQUEST(payload) {
  1302. return new Promise((resolve, reject) => {
  1303. async.waterfall(
  1304. [
  1305. next => {
  1306. YouTubeModule.youtubeApiRequestModel.deleteOne({ _id: payload.requestId }, err => {
  1307. if (err) next("Couldn't remove stored YouTube API request.");
  1308. else {
  1309. next();
  1310. }
  1311. });
  1312. },
  1313. next => {
  1314. CacheModule.runJob(
  1315. "HDEL",
  1316. {
  1317. table: "youtubeApiRequestParams",
  1318. key: payload.requestId.toString()
  1319. },
  1320. this
  1321. )
  1322. .then(next)
  1323. .catch(err => next(err));
  1324. },
  1325. next => {
  1326. CacheModule.runJob(
  1327. "HDEL",
  1328. {
  1329. table: "youtubeApiRequestResults",
  1330. key: payload.requestId.toString()
  1331. },
  1332. this
  1333. )
  1334. .then(next)
  1335. .catch(err => next(err));
  1336. },
  1337. next => {
  1338. CacheModule.runJob("PUB", {
  1339. channel: "youtube.removeYoutubeApiRequest",
  1340. value: payload.requestId.toString()
  1341. })
  1342. .then(next)
  1343. .catch(err => next(err));
  1344. }
  1345. ],
  1346. err => {
  1347. if (err) reject(new Error(err));
  1348. else resolve();
  1349. }
  1350. );
  1351. });
  1352. }
  1353. /**
  1354. * Create YouTube videos
  1355. * @param {object} payload - an object containing the payload
  1356. * @param {Array | object} payload.youtubeVideos - the youtubeVideo object or array of
  1357. * @returns {Promise} - returns a promise (resolve, reject)
  1358. */
  1359. CREATE_VIDEOS(payload) {
  1360. return new Promise((resolve, reject) => {
  1361. async.waterfall(
  1362. [
  1363. next => {
  1364. let { youtubeVideos } = payload;
  1365. if (typeof youtubeVideos !== "object") next("Invalid youtubeVideos type");
  1366. else {
  1367. if (!Array.isArray(youtubeVideos)) youtubeVideos = [youtubeVideos];
  1368. YouTubeModule.youtubeVideoModel.insertMany(youtubeVideos, next);
  1369. }
  1370. },
  1371. (youtubeVideos, next) => {
  1372. // TODO support spotify here
  1373. const mediaSources = youtubeVideos.map(video => `youtube:${video.youtubeId}`);
  1374. async.eachLimit(
  1375. mediaSources,
  1376. 2,
  1377. (mediaSource, next) => {
  1378. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  1379. .then(() => next())
  1380. .catch(next);
  1381. },
  1382. err => {
  1383. if (err) next(err);
  1384. else next(null, youtubeVideos);
  1385. }
  1386. );
  1387. }
  1388. ],
  1389. (err, youtubeVideos) => {
  1390. if (err) reject(new Error(err));
  1391. else resolve({ youtubeVideos });
  1392. }
  1393. );
  1394. });
  1395. }
  1396. /**
  1397. * Get YouTube videos
  1398. * @param {object} payload - an object containing the payload
  1399. * @param {Array} payload.identifiers - an array of YouTube video ObjectId's or YouTube ID's
  1400. * @param {boolean} payload.createMissing - attempt to fetch and create video's if not in db
  1401. * @param {boolean} payload.replaceExisting - replace existing
  1402. * @returns {Promise} - returns a promise (resolve, reject)
  1403. */
  1404. async GET_VIDEOS(payload) {
  1405. const getVideosFromYoutubeIds = async youtubeIds => {
  1406. const jobsToRun = [];
  1407. const chunkSize = 50;
  1408. while (youtubeIds.length > 0) {
  1409. const chunkedYoutubeIds = youtubeIds.splice(0, chunkSize);
  1410. const params = {
  1411. part: "snippet,contentDetails,statistics,status",
  1412. id: chunkedYoutubeIds.join(",")
  1413. };
  1414. jobsToRun.push(YouTubeModule.runJob("API_GET_VIDEOS", { params }, this));
  1415. }
  1416. const jobResponses = await Promise.all(jobsToRun);
  1417. return jobResponses
  1418. .map(jobResponse => jobResponse.response.data.items)
  1419. .flat()
  1420. .map(item => {
  1421. // TODO Clean up duration converter
  1422. let dur = item.contentDetails.duration;
  1423. dur = dur.replace("PT", "");
  1424. let duration = 0;
  1425. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  1426. v2 = Number(v2);
  1427. duration = v2 * 60 * 60;
  1428. return "";
  1429. });
  1430. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  1431. v2 = Number(v2);
  1432. duration += v2 * 60;
  1433. return "";
  1434. });
  1435. dur.replace(/([\d]*)S/, (v, v2) => {
  1436. v2 = Number(v2);
  1437. duration += v2;
  1438. return "";
  1439. });
  1440. const youtubeVideo = {
  1441. youtubeId: item.id,
  1442. title: item.snippet.title,
  1443. author: item.snippet.channelTitle,
  1444. thumbnail: item.snippet.thumbnails.default.url,
  1445. duration,
  1446. uploadedAt: new Date(item.snippet.publishedAt),
  1447. rawData: item
  1448. };
  1449. return youtubeVideo;
  1450. });
  1451. };
  1452. const { identifiers, createMissing, replaceExisting } = payload;
  1453. const stats = {};
  1454. const youtubeIds = identifiers.filter(identifier => !mongoose.Types.ObjectId.isValid(identifier));
  1455. const objectIds = identifiers.filter(identifier => mongoose.Types.ObjectId.isValid(identifier));
  1456. const existingVideos = (await YouTubeModule.youtubeVideoModel.find({ youtubeId: youtubeIds }))
  1457. .concat(await YouTubeModule.youtubeVideoModel.find({ _id: objectIds }))
  1458. .map(video => video._doc);
  1459. const existingYoutubeIds = existingVideos.map(existingVideo => existingVideo.youtubeId);
  1460. // const existingYoutubeObjectIds = existingVideos.map(existingVideo => existingVideo._id.toString());
  1461. if (payload.returnStats) {
  1462. stats.successful = existingYoutubeIds.length;
  1463. stats.alreadyInDatabase = existingYoutubeIds.length;
  1464. stats.failed = 0;
  1465. stats.failedVideoIds = [];
  1466. stats.successfulVideoIds = existingYoutubeIds;
  1467. }
  1468. if (!replaceExisting) {
  1469. if (!createMissing) {
  1470. return {
  1471. ...stats,
  1472. videos: existingVideos
  1473. };
  1474. }
  1475. if (identifiers.length === existingVideos.length || youtubeIds.length === 0) {
  1476. return {
  1477. ...stats,
  1478. videos: existingVideos
  1479. };
  1480. }
  1481. const missingYoutubeIds = youtubeIds.filter(youtubeId => existingYoutubeIds.indexOf(youtubeId) === -1);
  1482. if (missingYoutubeIds.length === 0)
  1483. return {
  1484. ...stats,
  1485. videos: existingVideos
  1486. };
  1487. const newVideos = await getVideosFromYoutubeIds(missingYoutubeIds);
  1488. await YouTubeModule.runJob("CREATE_VIDEOS", { youtubeVideos: newVideos }, this);
  1489. stats.successful += newVideos.length;
  1490. stats.successfulVideoIds = [...stats.successfulVideoIds, ...newVideos.map(newVideo => newVideo.youtubeId)];
  1491. // TODO actually handle failed videos I guess?
  1492. return {
  1493. ...stats,
  1494. videos: existingVideos.concat(newVideos)
  1495. };
  1496. }
  1497. const newVideos = await getVideosFromYoutubeIds(existingYoutubeIds);
  1498. const promises = newVideos.map(newVideo =>
  1499. YouTubeModule.youtubeVideoModel.updateOne(
  1500. { youtubeId: newVideo.youtubeId },
  1501. { $set: { ...newVideo, updatedAt: Date.now(), documentVersion: 2 } }
  1502. )
  1503. );
  1504. await Promise.allSettled(promises);
  1505. return {
  1506. ...stats,
  1507. videos: newVideos
  1508. };
  1509. }
  1510. /**
  1511. * Get YouTube channels
  1512. * @param {object} payload - an object containing the payload
  1513. * @param {Array} payload.channelIds - an array of YouTube channel id's
  1514. * @returns {Promise} - returns a promise (resolve, reject)
  1515. */
  1516. async GET_CHANNELS_FROM_IDS(payload) {
  1517. const getChannels = async channelIds => {
  1518. const jobsToRun = [];
  1519. const chunkSize = 50;
  1520. while (channelIds.length > 0) {
  1521. const chunkedChannelIds = channelIds.splice(0, chunkSize);
  1522. const params = {
  1523. part: [
  1524. "brandingSettings",
  1525. "contentDetails",
  1526. "contentOwnerDetails",
  1527. "id",
  1528. "localizations",
  1529. "snippet",
  1530. "statistics",
  1531. "status",
  1532. "topicDetails"
  1533. ].join(","),
  1534. id: chunkedChannelIds.join(",")
  1535. };
  1536. jobsToRun.push(YouTubeModule.runJob("API_GET_CHANNELS", { params }, this));
  1537. }
  1538. const jobResponses = await Promise.all(jobsToRun);
  1539. return jobResponses
  1540. .map(jobResponse => jobResponse.response.data.items)
  1541. .flat()
  1542. .map(item => {
  1543. const youtubeChannel = {
  1544. channelId: item.id,
  1545. title: item.snippet.title,
  1546. customUrl: item.snippet.customUrl,
  1547. rawData: item
  1548. };
  1549. return youtubeChannel;
  1550. });
  1551. };
  1552. const { channelIds } = payload;
  1553. const existingChannels = (await YouTubeModule.youtubeChannelModel.find({ channelId: channelIds })).map(
  1554. channel => channel._doc
  1555. );
  1556. const existingChannelIds = existingChannels.map(existingChannel => existingChannel.channelId);
  1557. // const existingChannelObjectIds = existingChannels.map(existingChannel => existingChannel._id.toString());
  1558. if (channelIds.length === existingChannels.length) return { channels: existingChannels };
  1559. const missingChannelIds = channelIds.filter(channelId => existingChannelIds.indexOf(channelId) === -1);
  1560. if (missingChannelIds.length === 0) return { videos: existingChannels };
  1561. const newChannels = await getChannels(missingChannelIds);
  1562. await YouTubeModule.youtubeChannelModel.insertMany(newChannels);
  1563. return { channels: existingChannels.concat(newChannels) };
  1564. }
  1565. /**
  1566. * Remove YouTube videos
  1567. * @param {object} payload - an object containing the payload
  1568. * @param {string} payload.videoIds - Array of youtubeVideo ObjectIds
  1569. * @returns {Promise} - returns a promise (resolve, reject)
  1570. */
  1571. REMOVE_VIDEOS(payload) {
  1572. return new Promise((resolve, reject) => {
  1573. let { videoIds } = payload;
  1574. if (!Array.isArray(videoIds)) videoIds = [videoIds];
  1575. async.waterfall(
  1576. [
  1577. next => {
  1578. if (!videoIds.every(videoId => mongoose.Types.ObjectId.isValid(videoId)))
  1579. next("One or more videoIds are not a valid ObjectId.");
  1580. else {
  1581. this.publishProgress({ status: "update", message: `Removing video (stage 1)` });
  1582. YouTubeModule.youtubeVideoModel.find({ _id: { $in: videoIds } }, (err, videos) => {
  1583. if (err) next(err);
  1584. else
  1585. next(
  1586. null,
  1587. videos.map(video => video.youtubeId)
  1588. );
  1589. });
  1590. }
  1591. },
  1592. (youtubeIds, next) => {
  1593. this.publishProgress({ status: "update", message: `Removing video (stage 2)` });
  1594. SongsModule.SongModel.find({ youtubeId: { $in: youtubeIds } }, (err, songs) => {
  1595. if (err) next(err);
  1596. else {
  1597. const filteredIds = youtubeIds.filter(
  1598. youtubeId => !songs.find(song => song.youtubeId === youtubeId)
  1599. );
  1600. if (filteredIds.length < youtubeIds.length)
  1601. next("One or more videos are attached to songs.");
  1602. else next(null, filteredIds);
  1603. }
  1604. });
  1605. },
  1606. (youtubeIds, next) => {
  1607. this.publishProgress({ status: "update", message: `Removing video (stage 3)` });
  1608. MediaModule.runJob("REMOVE_RATINGS", { youtubeIds }, this)
  1609. .then(() => next(null, youtubeIds))
  1610. .catch(next);
  1611. },
  1612. (youtubeIds, next) => {
  1613. this.publishProgress({ status: "update", message: `Removing video (stage 4)` });
  1614. async.eachLimit(
  1615. youtubeIds,
  1616. 2,
  1617. (youtubeId, next) => {
  1618. async.waterfall(
  1619. [
  1620. next => {
  1621. PlaylistsModule.playlistModel.find(
  1622. { "songs.youtubeId": youtubeId },
  1623. (err, playlists) => {
  1624. if (err) next(err);
  1625. else {
  1626. async.eachLimit(
  1627. playlists,
  1628. 1,
  1629. (playlist, next) => {
  1630. PlaylistsModule.runJob(
  1631. "REMOVE_FROM_PLAYLIST",
  1632. { playlistId: playlist._id, youtubeId },
  1633. this
  1634. )
  1635. .then(() => next())
  1636. .catch(next);
  1637. },
  1638. next
  1639. );
  1640. }
  1641. }
  1642. );
  1643. },
  1644. next => {
  1645. StationsModule.stationModel.find(
  1646. { "queue.youtubeId": youtubeId },
  1647. (err, stations) => {
  1648. if (err) next(err);
  1649. else {
  1650. async.eachLimit(
  1651. stations,
  1652. 1,
  1653. (station, next) => {
  1654. StationsModule.runJob(
  1655. "REMOVE_FROM_QUEUE",
  1656. { stationId: station._id, youtubeId },
  1657. this
  1658. )
  1659. .then(() => next())
  1660. .catch(err => {
  1661. if (
  1662. err === "Station not found" ||
  1663. err ===
  1664. "Song is not currently in the queue."
  1665. )
  1666. next();
  1667. else next(err);
  1668. });
  1669. },
  1670. next
  1671. );
  1672. }
  1673. }
  1674. );
  1675. },
  1676. next => {
  1677. StationsModule.stationModel.find(
  1678. { "currentSong.youtubeId": youtubeId },
  1679. (err, stations) => {
  1680. if (err) next(err);
  1681. else {
  1682. async.eachLimit(
  1683. stations,
  1684. 1,
  1685. (station, next) => {
  1686. StationsModule.runJob(
  1687. "SKIP_STATION",
  1688. {
  1689. stationId: station._id,
  1690. natural: false,
  1691. skipReason: "other"
  1692. },
  1693. this
  1694. )
  1695. .then(() => {
  1696. next();
  1697. })
  1698. .catch(err => {
  1699. if (err.message === "Station not found.")
  1700. next();
  1701. else next(err);
  1702. });
  1703. },
  1704. next
  1705. );
  1706. }
  1707. }
  1708. );
  1709. }
  1710. ],
  1711. next
  1712. );
  1713. },
  1714. next
  1715. );
  1716. },
  1717. next => {
  1718. this.publishProgress({ status: "update", message: `Removing video (stage 5)` });
  1719. YouTubeModule.youtubeVideoModel.deleteMany({ _id: { $in: videoIds } }, next);
  1720. },
  1721. (res, next) => {
  1722. this.publishProgress({ status: "update", message: `Removing video (stage 6)` });
  1723. CacheModule.runJob("PUB", {
  1724. channel: "youtube.removeVideos",
  1725. value: videoIds
  1726. })
  1727. .then(next)
  1728. .catch(err => next(err));
  1729. }
  1730. ],
  1731. err => {
  1732. if (err) reject(new Error(err));
  1733. else resolve();
  1734. }
  1735. );
  1736. });
  1737. }
  1738. /**
  1739. * Request a set of YouTube videos
  1740. * @param {object} payload - an object containing the payload
  1741. * @param {string} payload.url - the url of the the YouTube playlist or channel
  1742. * @param {boolean} payload.musicOnly - whether to only get music from the playlist/channel
  1743. * @param {boolean} payload.returnVideos - whether to return videos
  1744. * @returns {Promise} - returns a promise (resolve, reject)
  1745. */
  1746. REQUEST_SET(payload) {
  1747. return new Promise((resolve, reject) => {
  1748. async.waterfall(
  1749. [
  1750. next => {
  1751. const playlistRegex = /[\\?&]list=([^&#]*)/;
  1752. const channelRegex =
  1753. /\.[\w]+\/(?:(?:channel\/(UC[0-9A-Za-z_-]{21}[AQgw]))|(?:user\/?([\w-]+))|(?:c\/?([\w-]+))|(?:\/?([\w-]+)))/;
  1754. if (playlistRegex.exec(payload.url) || channelRegex.exec(payload.url))
  1755. YouTubeModule.runJob(
  1756. playlistRegex.exec(payload.url) ? "GET_PLAYLIST" : "GET_CHANNEL_VIDEOS",
  1757. {
  1758. url: payload.url,
  1759. musicOnly: payload.musicOnly,
  1760. max: payload.max
  1761. },
  1762. this
  1763. )
  1764. .then(res => {
  1765. next(null, res.songs);
  1766. })
  1767. .catch(next);
  1768. else next("Invalid YouTube URL.");
  1769. },
  1770. async youtubeIds => {
  1771. if (youtubeIds.length === 0) return { videos: [] };
  1772. const { videos, successful, failed, alreadyInDatabase, successfulVideoIds, failedVideoIds } =
  1773. await YouTubeModule.runJob(
  1774. "GET_VIDEOS",
  1775. {
  1776. identifiers: youtubeIds,
  1777. createMissing: true,
  1778. returnStats: true
  1779. },
  1780. this
  1781. );
  1782. return {
  1783. videos,
  1784. successful,
  1785. failed,
  1786. alreadyInDatabase,
  1787. successfulVideoIds,
  1788. failedVideoIds
  1789. };
  1790. }
  1791. ],
  1792. (err, response) => {
  1793. if (err) reject(new Error(err));
  1794. else resolve(response);
  1795. }
  1796. );
  1797. });
  1798. }
  1799. /**
  1800. * Gets missing YouTube video's from all playlists, stations and songs
  1801. * @returns {Promise} - returns a promise (resolve, reject)
  1802. */
  1803. async GET_MISSING_VIDEOS() {
  1804. const youtubeIds = Array.from(
  1805. new Set(
  1806. [
  1807. ...(await SongsModule.runJob("GET_ALL_MEDIA_SOURCES", {}, this)),
  1808. ...(await PlaylistsModule.runJob("GET_ALL_MEDIA_SOURCES", {}, this))
  1809. ]
  1810. .filter(mediaSource => mediaSource.startsWith("youtube:"))
  1811. .map(mediaSource => mediaSource.split(":")[1])
  1812. )
  1813. );
  1814. const existingYoutubeIds = await YouTubeModule.youtubeVideoModel.distinct("youtubeId");
  1815. const missingYoutubeIds = youtubeIds.filter(youtubeId => existingYoutubeIds.indexOf(youtubeId) === -1);
  1816. const res = await YouTubeModule.runJob(
  1817. "GET_VIDEOS",
  1818. { identifiers: missingYoutubeIds, createMissing: true },
  1819. this
  1820. );
  1821. const gotVideos = res.videos;
  1822. return {
  1823. all: youtubeIds.length,
  1824. existing: existingYoutubeIds.length,
  1825. missing: missingYoutubeIds.length,
  1826. got: gotVideos.length
  1827. };
  1828. }
  1829. /**
  1830. * Updates videos from version 1 to version 2
  1831. * @returns {Promise} - returns a promise (resolve, reject)
  1832. */
  1833. async UPDATE_VIDEOS_V1_TO_V2() {
  1834. const videoIds = await YouTubeModule.youtubeVideoModel.distinct("_id", { documentVersion: 1 });
  1835. const res = await YouTubeModule.runJob("GET_VIDEOS", { identifiers: videoIds, replaceExisting: true }, this);
  1836. const v1 = videoIds.length;
  1837. const v2 = res.videos.length;
  1838. return {
  1839. v1,
  1840. v2
  1841. };
  1842. }
  1843. /**
  1844. * Gets missing YouTube channels based on cached YouTube video's
  1845. * @returns {Promise} - returns a promise (resolve, reject)
  1846. */
  1847. async GET_MISSING_CHANNELS() {
  1848. const currentChannelIds = await YouTubeModule.youtubeChannelModel.distinct("channelId");
  1849. const videoChannelIds = await YouTubeModule.youtubeVideoModel.distinct("rawData.snippet.channelId");
  1850. const missingChannelIds = videoChannelIds.filter(channelId => currentChannelIds.indexOf(channelId) === -1);
  1851. const res = await YouTubeModule.runJob("GET_CHANNELS_FROM_IDS", { channelIds: missingChannelIds }, this);
  1852. const gotChannels = res.channels;
  1853. return {
  1854. current: currentChannelIds.length,
  1855. all: videoChannelIds.length,
  1856. missing: missingChannelIds.length,
  1857. got: gotChannels.length
  1858. };
  1859. }
  1860. }
  1861. export default new _YouTubeModule();