youtube.js 59 KB

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