youtube.js 61 KB

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