youtube.js 53 KB

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