youtube.js 55 KB

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