youtube.js 48 KB

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