youtube.js 50 KB

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