youtube.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. /* eslint-disable */
  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. const quotas = [
  37. {
  38. type: "QUERIES_PER_DAY",
  39. limit: 10000
  40. },
  41. {
  42. type: "QUERIES_PER_MINUTE",
  43. limit: 1800000
  44. },
  45. {
  46. type: "QUERIES_PER_100_SECONDS",
  47. limit: 3000000
  48. }
  49. ];
  50. // const dummyApiCalls = [
  51. // {
  52. // quotaCost: 100,
  53. // date: new Date(new Date() - (1000 * 120))
  54. // },
  55. // {
  56. // quotaCost: 2,
  57. // date: new Date(new Date() - (1000 * 120))
  58. // },
  59. // {
  60. // quotaCost: 1,
  61. // date: new Date()
  62. // },
  63. // {
  64. // quotaCost: 100,
  65. // date: new Date()
  66. // }
  67. // ];
  68. const isQuotaExceeded = apiCalls => {
  69. const reversedApiCalls = apiCalls.slice().reverse();
  70. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  71. let quotaExceeded = false;
  72. for (const quota of sortedQuotas) {
  73. let quotaUsed = 0;
  74. let dateCutoff = null;
  75. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  76. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  77. else if (quota.type === "QUERIES_PER_DAY") {
  78. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  79. dateCutoff = new Date();
  80. dateCutoff.setUTCMilliseconds(0);
  81. dateCutoff.setUTCSeconds(0);
  82. dateCutoff.setUTCMinutes(0);
  83. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  84. dateCutoff.setUTCHours(0);
  85. }
  86. for (const apiCall of reversedApiCalls) {
  87. if (apiCall.date >= dateCutoff) quotaUsed += apiCall.quotaCost;
  88. else break;
  89. }
  90. if (quotaUsed >= quota.limit) {
  91. quotaExceeded = true;
  92. break;
  93. }
  94. }
  95. return quotaExceeded;
  96. };
  97. const getQuotaStatus = apiCalls => {
  98. const reversedApiCalls = apiCalls.slice().reverse();
  99. const sortedQuotas = quotas.sort((a, b) => a.limit > b.limit);
  100. const status = {};
  101. for (const quota of sortedQuotas) {
  102. status[quota.type] = {
  103. quotaUsed: 0,
  104. limit: quota.limit,
  105. quotaExceeded: false
  106. };
  107. let dateCutoff = null;
  108. if (quota.type === "QUERIES_PER_MINUTE") dateCutoff = new Date() - 1000 * 60;
  109. else if (quota.type === "QUERIES_PER_100_SECONDS") dateCutoff = new Date() - 1000 * 100;
  110. else if (quota.type === "QUERIES_PER_DAY") {
  111. // Quota resets at midnight PT, this is my best guess to convert the current date to the last midnight PT
  112. dateCutoff = new Date();
  113. dateCutoff.setUTCMilliseconds(0);
  114. dateCutoff.setUTCSeconds(0);
  115. dateCutoff.setUTCMinutes(0);
  116. dateCutoff.setUTCHours(dateCutoff.getUTCHours() - 7);
  117. dateCutoff.setUTCHours(0);
  118. }
  119. for (const apiCall of reversedApiCalls) {
  120. if (apiCall.date >= dateCutoff) status[quota.type].quotaUsed += apiCall.quotaCost;
  121. else break;
  122. }
  123. if (status[quota.type].quotaUsed >= quota.limit && !status[quota.type].quotaExceeded)
  124. status[quota.type].quotaExceeded = true;
  125. }
  126. return status;
  127. };
  128. class _YouTubeModule extends CoreClass {
  129. // eslint-disable-next-line require-jsdoc
  130. constructor() {
  131. super("youtube", {
  132. concurrency: 1,
  133. priorities: {
  134. GET_PLAYLIST: 11
  135. }
  136. });
  137. YouTubeModule = this;
  138. }
  139. /**
  140. * Initialises the activities module
  141. *
  142. * @returns {Promise} - returns promise (reject, resolve)
  143. */
  144. initialize() {
  145. return new Promise(resolve => {
  146. this.rateLimiter = new RateLimitter(config.get("apis.youtube.rateLimit"));
  147. this.requestTimeout = config.get("apis.youtube.requestTimeout");
  148. this.axios = axios.create();
  149. this.axios.defaults.raxConfig = {
  150. instance: this.axios,
  151. retry: config.get("apis.youtube.retryAmount"),
  152. noResponseRetries: config.get("apis.youtube.retryAmount")
  153. };
  154. rax.attach(this.axios);
  155. this.apiCalls = [];
  156. resolve();
  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. * Gets the details of a song using the YouTube API
  195. *
  196. * @param {object} payload - object that contains the payload
  197. * @param {string} payload.youtubeId - the YouTube API id of the song
  198. * @returns {Promise} - returns promise (reject, resolve)
  199. */
  200. GET_SONG(payload) {
  201. return new Promise((resolve, reject) => {
  202. const params = {
  203. part: "snippet,contentDetails,statistics,status",
  204. id: payload.youtubeId
  205. };
  206. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  207. .then(({ response }) => {
  208. const { data } = response;
  209. if (data.items[0] === undefined)
  210. return reject(new Error("The specified video does not exist or cannot be publicly accessed."));
  211. // TODO Clean up duration converter
  212. let dur = data.items[0].contentDetails.duration;
  213. dur = dur.replace("PT", "");
  214. let duration = 0;
  215. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  216. v2 = Number(v2);
  217. duration = v2 * 60 * 60;
  218. return "";
  219. });
  220. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  221. v2 = Number(v2);
  222. duration += v2 * 60;
  223. return "";
  224. });
  225. // eslint-disable-next-line no-unused-vars
  226. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  227. v2 = Number(v2);
  228. duration += v2;
  229. return "";
  230. });
  231. const song = {
  232. youtubeId: data.items[0].id,
  233. title: data.items[0].snippet.title,
  234. thumbnail: data.items[0].snippet.thumbnails.default.url,
  235. duration
  236. };
  237. return resolve({ song });
  238. })
  239. .catch(err => {
  240. YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
  241. return reject(new Error("An error has occured. Please try again later."));
  242. });
  243. });
  244. }
  245. /**
  246. * Gets the id of the channel upload playlist
  247. *
  248. * @param {object} payload - object that contains the payload
  249. * @param {string} payload.channelId - the id of the YouTube channel
  250. * @returns {Promise} - returns promise (reject, resolve)
  251. */
  252. GET_CHANNEL_UPLOADS_PLAYLIST_ID(payload) {
  253. return new Promise((resolve, reject) => {
  254. const params = {
  255. part: "contentDetails",
  256. id: payload.channelId
  257. };
  258. YouTubeModule.runJob(
  259. "API_GET_CHANNELS",
  260. {
  261. params
  262. },
  263. this
  264. )
  265. .then(({ response }) => {
  266. const { data } = response;
  267. if (data.items.length === 0) return reject(new Error("Channel not found."));
  268. const playlistId = data.items[0].contentDetails.relatedPlaylists.uploads;
  269. return resolve({ playlistId });
  270. })
  271. .catch(err => {
  272. YouTubeModule.log("ERROR", "GET_CHANNEL_UPLOADS_PLAYLIST_ID", `${err.message}`);
  273. if (err.message === "Request failed with status code 404") {
  274. return reject(new Error("Channel not found. Is the channel public/unlisted?"));
  275. }
  276. return reject(new Error("An error has occured. Please try again later."));
  277. });
  278. });
  279. }
  280. /**
  281. * Returns an array of songs taken from a YouTube playlist
  282. *
  283. * @param {object} payload - object that contains the payload
  284. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  285. * @param {string} payload.url - the url of the YouTube playlist
  286. * @returns {Promise} - returns promise (reject, resolve)
  287. */
  288. GET_PLAYLIST(payload) {
  289. return new Promise((resolve, reject) => {
  290. const regex = /[\\?&]list=([^&#]*)/;
  291. const splitQuery = regex.exec(payload.url);
  292. if (!splitQuery) {
  293. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  294. reject(new Error("Invalid playlist URL."));
  295. return;
  296. }
  297. const playlistId = splitQuery[1];
  298. async.waterfall(
  299. [
  300. next => {
  301. let songs = [];
  302. let nextPageToken = "";
  303. async.whilst(
  304. next => {
  305. YouTubeModule.log(
  306. "INFO",
  307. `Getting playlist progress for job (${this.toString()}): ${
  308. songs.length
  309. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  310. );
  311. next(null, nextPageToken !== undefined);
  312. },
  313. next => {
  314. // Add 250ms delay between each job request
  315. setTimeout(() => {
  316. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  317. .then(response => {
  318. songs = songs.concat(response.songs);
  319. nextPageToken = response.nextPageToken;
  320. next();
  321. })
  322. .catch(err => next(err));
  323. }, 250);
  324. },
  325. err => next(err, songs)
  326. );
  327. },
  328. (songs, next) =>
  329. next(
  330. null,
  331. songs.map(song => song.contentDetails.videoId)
  332. ),
  333. (songs, next) => {
  334. if (!payload.musicOnly) return next(true, { songs });
  335. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  336. .then(filteredSongs => next(null, { filteredSongs, songs }))
  337. .catch(next);
  338. }
  339. ],
  340. (err, response) => {
  341. if (err && err !== true) {
  342. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  343. reject(new Error(err.message));
  344. } else {
  345. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  346. }
  347. }
  348. );
  349. });
  350. }
  351. /**
  352. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST.
  353. *
  354. * @param {object} payload - object that contains the payload
  355. * @param {boolean} payload.playlistId - the playlist id to get videos from
  356. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  357. * @param {string} payload.url - the url of the YouTube playlist
  358. * @returns {Promise} - returns promise (reject, resolve)
  359. */
  360. GET_PLAYLIST_PAGE(payload) {
  361. return new Promise((resolve, reject) => {
  362. const params = {
  363. part: "contentDetails",
  364. playlistId: payload.playlistId,
  365. maxResults: 50
  366. };
  367. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  368. YouTubeModule.runJob(
  369. "GET_PLAYLIST_ITEMS",
  370. {
  371. params
  372. },
  373. this
  374. )
  375. .then(({ response }) => {
  376. const { data } = response;
  377. const songs = data.items;
  378. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  379. return resolve({ songs });
  380. })
  381. .catch(err => {
  382. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  383. if (err.message === "Request failed with status code 404") {
  384. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  385. }
  386. return reject(new Error("An error has occured. Please try again later."));
  387. });
  388. });
  389. }
  390. /**
  391. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  392. *
  393. * @param {object} payload - object that contains the payload
  394. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  395. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  396. * @returns {Promise} - returns promise (reject, resolve)
  397. */
  398. FILTER_MUSIC_VIDEOS(payload) {
  399. return new Promise((resolve, reject) => {
  400. const page = payload.page ? payload.page : 0;
  401. const videosPerPage = 50;
  402. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  403. if (localVideoIds.length === 0) {
  404. resolve({ videoIds: [] });
  405. return;
  406. }
  407. const params = {
  408. part: "topicDetails",
  409. id: localVideoIds.join(","),
  410. maxResults: videosPerPage
  411. };
  412. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  413. .then(({ response }) => {
  414. const { data } = response;
  415. const videoIds = [];
  416. data.items.forEach(item => {
  417. const videoId = item.id;
  418. if (!item.topicDetails) return;
  419. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  420. videoIds.push(videoId);
  421. });
  422. return YouTubeModule.runJob(
  423. "FILTER_MUSIC_VIDEOS",
  424. { videoIds: payload.videoIds, page: page + 1 },
  425. this
  426. )
  427. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  428. .catch(err => reject(err));
  429. })
  430. .catch(err => {
  431. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  432. return reject(new Error("Failed to find playlist from YouTube"));
  433. });
  434. });
  435. }
  436. API_GET_VIDEOS(payload) {
  437. return new Promise((resolve, reject) => {
  438. const { params } = payload;
  439. YouTubeModule.runJob(
  440. "API_CALL",
  441. {
  442. url: "https://www.googleapis.com/youtube/v3/videos",
  443. params: {
  444. key: config.get("apis.youtube.key"),
  445. ...params
  446. },
  447. quotaCost: 1
  448. },
  449. this
  450. )
  451. .then(response => {
  452. resolve(response);
  453. })
  454. .catch(err => {
  455. reject(err);
  456. });
  457. });
  458. }
  459. API_GET_PLAYLIST_ITEMS(payload) {
  460. return new Promise((resolve, reject) => {
  461. const { params } = payload;
  462. YouTubeModule.runJob(
  463. "API_CALL",
  464. {
  465. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  466. params: {
  467. key: config.get("apis.youtube.key"),
  468. ...params
  469. },
  470. quotaCost: 1
  471. },
  472. this
  473. )
  474. .then(response => {
  475. resolve(response);
  476. })
  477. .catch(err => {
  478. reject(err);
  479. });
  480. });
  481. }
  482. API_GET_CHANNELS(payload) {
  483. return new Promise((resolve, reject) => {
  484. const { params } = payload;
  485. YouTubeModule.runJob(
  486. "API_CALL",
  487. {
  488. url: "https://www.googleapis.com/youtube/v3/channels",
  489. params: {
  490. key: config.get("apis.youtube.key"),
  491. ...params
  492. },
  493. quotaCost: 1
  494. },
  495. this
  496. )
  497. .then(response => {
  498. resolve(response);
  499. })
  500. .catch(err => {
  501. reject(err);
  502. });
  503. });
  504. }
  505. API_SEARCH(payload) {
  506. return new Promise((resolve, reject) => {
  507. const { params } = payload;
  508. YouTubeModule.runJob(
  509. "API_CALL",
  510. {
  511. url: "https://www.googleapis.com/youtube/v3/search",
  512. params: {
  513. key: config.get("apis.youtube.key"),
  514. ...params
  515. },
  516. quotaCost: 100
  517. },
  518. this
  519. )
  520. .then(response => {
  521. resolve(response);
  522. })
  523. .catch(err => {
  524. reject(err);
  525. });
  526. });
  527. }
  528. API_CALL(payload) {
  529. return new Promise((resolve, reject) => {
  530. const { url, params, quotaCost } = payload;
  531. const quotaExceeded = isQuotaExceeded(YouTubeModule.apiCalls);
  532. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  533. else {
  534. YouTubeModule.apiCalls.push({
  535. quotaCost,
  536. date: new Date()
  537. });
  538. YouTubeModule.axios
  539. .get(url, {
  540. params,
  541. timeout: YouTubeModule.requestTimeout
  542. })
  543. .then(response => {
  544. if (response.data.error) {
  545. reject(new Error(response.data.error));
  546. } else {
  547. resolve({ response });
  548. }
  549. })
  550. .catch(err => {
  551. reject(err);
  552. });
  553. }
  554. });
  555. }
  556. }
  557. export default new _YouTubeModule();