youtube.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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 quotaExceeded = 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 quotaStatus = 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. * Returns an array of songs taken from a YouTube playlist
  247. *
  248. * @param {object} payload - object that contains the payload
  249. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  250. * @param {string} payload.url - the url of the YouTube playlist
  251. * @returns {Promise} - returns promise (reject, resolve)
  252. */
  253. GET_PLAYLIST(payload) {
  254. return new Promise((resolve, reject) => {
  255. const regex = /[\\?&]list=([^&#]*)/;
  256. const splitQuery = regex.exec(payload.url);
  257. if (!splitQuery) {
  258. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  259. reject(new Error("Invalid playlist URL."));
  260. return;
  261. }
  262. const playlistId = splitQuery[1];
  263. async.waterfall(
  264. [
  265. next => {
  266. let songs = [];
  267. let nextPageToken = "";
  268. async.whilst(
  269. next => {
  270. YouTubeModule.log(
  271. "INFO",
  272. `Getting playlist progress for job (${this.toString()}): ${
  273. songs.length
  274. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  275. );
  276. next(null, nextPageToken !== undefined);
  277. },
  278. next => {
  279. // Add 250ms delay between each job request
  280. setTimeout(() => {
  281. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  282. .then(response => {
  283. songs = songs.concat(response.songs);
  284. nextPageToken = response.nextPageToken;
  285. next();
  286. })
  287. .catch(err => next(err));
  288. }, 250);
  289. },
  290. err => next(err, songs)
  291. );
  292. },
  293. (songs, next) =>
  294. next(
  295. null,
  296. songs.map(song => song.contentDetails.videoId)
  297. ),
  298. (songs, next) => {
  299. if (!payload.musicOnly) return next(true, { songs });
  300. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  301. .then(filteredSongs => next(null, { filteredSongs, songs }))
  302. .catch(next);
  303. }
  304. ],
  305. (err, response) => {
  306. if (err && err !== true) {
  307. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  308. reject(new Error(err.message));
  309. } else {
  310. resolve({ songs: response.filteredSongs ? response.filteredSongs.videoIds : response.songs });
  311. }
  312. }
  313. );
  314. });
  315. }
  316. /**
  317. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST.
  318. *
  319. * @param {object} payload - object that contains the payload
  320. * @param {boolean} payload.playlistId - the playlist id to get videos from
  321. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  322. * @param {string} payload.url - the url of the YouTube playlist
  323. * @returns {Promise} - returns promise (reject, resolve)
  324. */
  325. GET_PLAYLIST_PAGE(payload) {
  326. return new Promise((resolve, reject) => {
  327. const params = {
  328. part: "contentDetails",
  329. playlistId: payload.playlistId,
  330. maxResults: 50
  331. };
  332. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  333. YouTubeModule.runJob(
  334. "GET_PLAYLIST_ITEMS",
  335. {
  336. params
  337. },
  338. this
  339. )
  340. .then(({ response }) => {
  341. const { data } = response;
  342. const songs = data.items;
  343. if (data.nextPageToken) return resolve({ nextPageToken: data.nextPageToken, songs });
  344. return resolve({ songs });
  345. })
  346. .catch(err => {
  347. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  348. if (err.message === "Request failed with status code 404") {
  349. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  350. }
  351. return reject(new Error("An error has occured. Please try again later."));
  352. });
  353. });
  354. }
  355. /**
  356. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  357. *
  358. * @param {object} payload - object that contains the payload
  359. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  360. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  361. * @returns {Promise} - returns promise (reject, resolve)
  362. */
  363. FILTER_MUSIC_VIDEOS(payload) {
  364. return new Promise((resolve, reject) => {
  365. const page = payload.page ? payload.page : 0;
  366. const videosPerPage = 50;
  367. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  368. if (localVideoIds.length === 0) {
  369. resolve({ videoIds: [] });
  370. return;
  371. }
  372. const params = {
  373. part: "topicDetails",
  374. id: localVideoIds.join(","),
  375. maxResults: videosPerPage
  376. };
  377. YouTubeModule.runJob("API_GET_VIDEOS", { params }, this)
  378. .then(({ response }) => {
  379. const { data } = response;
  380. const videoIds = [];
  381. data.items.forEach(item => {
  382. const videoId = item.id;
  383. if (!item.topicDetails) return;
  384. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  385. videoIds.push(videoId);
  386. });
  387. return YouTubeModule.runJob(
  388. "FILTER_MUSIC_VIDEOS",
  389. { videoIds: payload.videoIds, page: page + 1 },
  390. this
  391. )
  392. .then(result => resolve({ videoIds: videoIds.concat(result.videoIds) }))
  393. .catch(err => reject(err));
  394. })
  395. .catch(err => {
  396. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  397. return reject(new Error("Failed to find playlist from YouTube"));
  398. });
  399. });
  400. }
  401. API_GET_VIDEOS(payload) {
  402. return new Promise((resolve, reject) => {
  403. const { params } = payload;
  404. YouTubeModule.runJob(
  405. "API_CALL",
  406. {
  407. url: "https://www.googleapis.com/youtube/v3/videos",
  408. params: {
  409. key: config.get("apis.youtube.key"),
  410. ...params
  411. },
  412. quotaCost: 1
  413. },
  414. this
  415. )
  416. .then(response => {
  417. resolve(response);
  418. })
  419. .catch(err => {
  420. reject(err);
  421. });
  422. });
  423. }
  424. API_GET_PLAYLIST_ITEMS(payload) {
  425. return new Promise((resolve, reject) => {
  426. const { params } = payload;
  427. YouTubeModule.runJob(
  428. "API_CALL",
  429. {
  430. url: "https://www.googleapis.com/youtube/v3/playlistItems",
  431. params: {
  432. key: config.get("apis.youtube.key"),
  433. ...params
  434. },
  435. quotaCost: 1
  436. },
  437. this
  438. )
  439. .then(response => {
  440. resolve(response);
  441. })
  442. .catch(err => {
  443. reject(err);
  444. });
  445. });
  446. }
  447. API_SEARCH(payload) {
  448. return new Promise((resolve, reject) => {
  449. const { params } = payload;
  450. YouTubeModule.runJob(
  451. "API_CALL",
  452. {
  453. url: "https://www.googleapis.com/youtube/v3/search",
  454. params: {
  455. key: config.get("apis.youtube.key"),
  456. ...params
  457. },
  458. quotaCost: 100
  459. },
  460. this
  461. )
  462. .then(response => {
  463. resolve(response);
  464. })
  465. .catch(err => {
  466. reject(err);
  467. });
  468. });
  469. }
  470. API_CALL(payload) {
  471. return new Promise((resolve, reject) => {
  472. const { url, params, quotaCost } = payload;
  473. const quotaExceeded = quotaExceeded(YouTubeModule.apiCalls);
  474. if (quotaExceeded) reject(new Error("Quota has been exceeded. Please wait a while."));
  475. else {
  476. YouTubeModule.apiCalls.push({
  477. quotaCost,
  478. date: new Date()
  479. });
  480. YouTubeModule.axios
  481. .get(url, {
  482. params,
  483. timeout: YouTubeModule.requestTimeout
  484. })
  485. .then(response => {
  486. if (response.data.error) {
  487. reject(new Error(response.data.error));
  488. } else {
  489. resolve({ response });
  490. }
  491. })
  492. .catch(err => {
  493. reject(err);
  494. });
  495. }
  496. });
  497. }
  498. }
  499. export default new _YouTubeModule();