youtube.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import async from "async";
  2. import config from "config";
  3. import axios from "axios";
  4. import CoreClass from "../core";
  5. class RateLimitter {
  6. /**
  7. * Constructor
  8. *
  9. * @param {number} timeBetween - The time between each allowed YouTube request
  10. */
  11. constructor(timeBetween) {
  12. this.dateStarted = Date.now();
  13. this.timeBetween = timeBetween;
  14. }
  15. /**
  16. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  17. *
  18. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  19. */
  20. continue() {
  21. return new Promise(resolve => {
  22. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  23. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  24. });
  25. }
  26. /**
  27. * Restart the rate limit timer
  28. */
  29. restart() {
  30. this.dateStarted = Date.now();
  31. }
  32. }
  33. let YouTubeModule;
  34. class _YouTubeModule extends CoreClass {
  35. // eslint-disable-next-line require-jsdoc
  36. constructor() {
  37. super("youtube", {
  38. concurrency: 1,
  39. priorities: {
  40. GET_PLAYLIST: 11
  41. }
  42. });
  43. YouTubeModule = this;
  44. }
  45. /**
  46. * Initialises the activities module
  47. *
  48. * @returns {Promise} - returns promise (reject, resolve)
  49. */
  50. initialize() {
  51. return new Promise(resolve => {
  52. this.rateLimiter = new RateLimitter(config.get("apis.youtube.rateLimit"));
  53. this.requestTimeout = config.get("apis.youtube.requestTimeout");
  54. resolve();
  55. });
  56. }
  57. /**
  58. * Fetches a list of songs from Youtube's API
  59. *
  60. * @param {object} payload - object that contains the payload
  61. * @param {string} payload.query - the query we'll pass to youtubes api
  62. * @param {string} payload.pageToken - (optional) if this exists, will search search youtube for a specific page reference
  63. * @returns {Promise} - returns promise (reject, resolve)
  64. */
  65. SEARCH(payload) {
  66. const params = {
  67. part: "snippet",
  68. q: payload.query,
  69. key: config.get("apis.youtube.key"),
  70. type: "video",
  71. maxResults: 10
  72. };
  73. if (payload.pageToken) params.pageToken = payload.pageToken;
  74. return new Promise((resolve, reject) =>
  75. YouTubeModule.rateLimiter.continue().then(() => {
  76. YouTubeModule.rateLimiter.restart();
  77. axios
  78. .get("https://www.googleapis.com/youtube/v3/search", { params })
  79. .then(res => {
  80. if (res.data.err) {
  81. YouTubeModule.log("ERROR", "SEARCH", `${res.data.error.message}`);
  82. return reject(new Error("An error has occured. Please try again later."));
  83. }
  84. return resolve(res.data);
  85. })
  86. .catch(err => {
  87. YouTubeModule.log("ERROR", "SEARCH", `${err.message}`);
  88. return reject(new Error("An error has occured. Please try again later."));
  89. });
  90. })
  91. );
  92. }
  93. /**
  94. * Gets the details of a song using the YouTube API
  95. *
  96. * @param {object} payload - object that contains the payload
  97. * @param {string} payload.songId - the YouTube API id of the song
  98. * @returns {Promise} - returns promise (reject, resolve)
  99. */
  100. GET_SONG(payload) {
  101. return new Promise((resolve, reject) => {
  102. const params = {
  103. part: "snippet,contentDetails,statistics,status",
  104. id: payload.songId,
  105. key: config.get("apis.youtube.key")
  106. };
  107. if (payload.pageToken) params.pageToken = payload.pageToken;
  108. YouTubeModule.rateLimiter.continue().then(() => {
  109. YouTubeModule.rateLimiter.restart();
  110. axios
  111. .get("https://www.googleapis.com/youtube/v3/videos", {
  112. params,
  113. timeout: YouTubeModule.requestTimeout
  114. })
  115. .then(res => {
  116. if (res.data.error) {
  117. YouTubeModule.log("ERROR", "GET_SONG", `${res.data.error.message}`);
  118. return reject(new Error("An error has occured. Please try again later."));
  119. }
  120. if (res.data.items[0] === undefined)
  121. return reject(
  122. new Error("The specified video does not exist or cannot be publicly accessed.")
  123. );
  124. // TODO Clean up duration converter
  125. let dur = res.data.items[0].contentDetails.duration;
  126. dur = dur.replace("PT", "");
  127. let duration = 0;
  128. dur = dur.replace(/([\d]*)H/, (v, v2) => {
  129. v2 = Number(v2);
  130. duration = v2 * 60 * 60;
  131. return "";
  132. });
  133. dur = dur.replace(/([\d]*)M/, (v, v2) => {
  134. v2 = Number(v2);
  135. duration += v2 * 60;
  136. return "";
  137. });
  138. // eslint-disable-next-line no-unused-vars
  139. dur = dur.replace(/([\d]*)S/, (v, v2) => {
  140. v2 = Number(v2);
  141. duration += v2;
  142. return "";
  143. });
  144. const song = {
  145. songId: res.data.items[0].id,
  146. title: res.data.items[0].snippet.title,
  147. thumbnail: res.data.items[0].snippet.thumbnails.default.url,
  148. duration
  149. };
  150. return resolve({ song });
  151. })
  152. .catch(err => {
  153. YouTubeModule.log("ERROR", "GET_SONG", `${err.message}`);
  154. return reject(new Error("An error has occured. Please try again later."));
  155. });
  156. });
  157. });
  158. }
  159. /**
  160. * Returns an array of songs taken from a YouTube playlist
  161. *
  162. * @param {object} payload - object that contains the payload
  163. * @param {boolean} payload.musicOnly - whether to return music videos or all videos in the playlist
  164. * @param {string} payload.url - the url of the YouTube playlist
  165. * @returns {Promise} - returns promise (reject, resolve)
  166. */
  167. GET_PLAYLIST(payload) {
  168. return new Promise((resolve, reject) => {
  169. const name = "list".replace(/[\\[]/, "\\[").replace(/[\]]/, "\\]");
  170. const regex = new RegExp(`[\\?&]${name}=([^&#]*)`);
  171. const splitQuery = regex.exec(payload.url);
  172. if (!splitQuery) {
  173. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  174. return reject(new Error("Invalid playlist URL."));
  175. }
  176. const playlistId = splitQuery[1];
  177. return async.waterfall(
  178. [
  179. next => {
  180. let songs = [];
  181. let nextPageToken = "";
  182. async.whilst(
  183. next => {
  184. YouTubeModule.log(
  185. "INFO",
  186. `Getting playlist progress for job (${this.toString()}): ${
  187. songs.length
  188. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  189. );
  190. next(null, nextPageToken !== undefined);
  191. },
  192. next => {
  193. // Add 250ms delay between each job request
  194. setTimeout(() => {
  195. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  196. .then(response => {
  197. songs = songs.concat(response.songs);
  198. nextPageToken = response.nextPageToken;
  199. next();
  200. })
  201. .catch(err => next(err));
  202. }, 250);
  203. },
  204. err => next(err, songs)
  205. );
  206. },
  207. (songs, next) =>
  208. next(
  209. null,
  210. songs.map(song => song.contentDetails.videoId)
  211. ),
  212. (songs, next) => {
  213. if (!payload.musicOnly) return next(true, { songs });
  214. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  215. .then(filteredSongs => next(null, { filteredSongs, songs }))
  216. .catch(next);
  217. }
  218. ],
  219. (err, response) => {
  220. if (err && err !== true) {
  221. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  222. reject(new Error("Some error has occurred."));
  223. } else {
  224. resolve({ songs: response.filteredSongs ? response.filteredSongs.songIds : response.songs });
  225. }
  226. }
  227. );
  228. });
  229. }
  230. /**
  231. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST.
  232. *
  233. * @param {object} payload - object that contains the payload
  234. * @param {boolean} payload.playlistId - the playlist id to get videos from
  235. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  236. * @param {string} payload.url - the url of the YouTube playlist
  237. * @returns {Promise} - returns promise (reject, resolve)
  238. */
  239. GET_PLAYLIST_PAGE(payload) {
  240. return new Promise((resolve, reject) => {
  241. const params = {
  242. part: "contentDetails",
  243. playlistId: payload.playlistId,
  244. key: config.get("apis.youtube.key"),
  245. maxResults: 50
  246. };
  247. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  248. YouTubeModule.rateLimiter.continue().then(() => {
  249. YouTubeModule.rateLimiter.restart();
  250. axios
  251. .get("https://www.googleapis.com/youtube/v3/playlistItems", {
  252. params,
  253. timeout: YouTubeModule.requestTimeout
  254. })
  255. .then(res => {
  256. if (res.data.err) {
  257. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${res.data.error.message}`);
  258. return reject(new Error("An error has occured. Please try again later."));
  259. }
  260. const songs = res.data.items;
  261. if (res.data.nextPageToken) return resolve({ nextPageToken: res.data.nextPageToken, songs });
  262. return resolve({ songs });
  263. })
  264. .catch(err => {
  265. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  266. return reject(new Error("An error has occured. Please try again later."));
  267. });
  268. });
  269. });
  270. }
  271. /**
  272. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  273. *
  274. * @param {object} payload - object that contains the payload
  275. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  276. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  277. * @returns {Promise} - returns promise (reject, resolve)
  278. */
  279. FILTER_MUSIC_VIDEOS(payload) {
  280. return new Promise((resolve, reject) => {
  281. const page = payload.page ? payload.page : 0;
  282. const videosPerPage = 50;
  283. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  284. if (localVideoIds.length === 0) {
  285. return resolve({ videoIds: [] });
  286. }
  287. const params = {
  288. part: "topicDetails",
  289. id: localVideoIds.join(","),
  290. key: config.get("apis.youtube.key"),
  291. maxResults: videosPerPage
  292. };
  293. return YouTubeModule.rateLimiter.continue().then(() => {
  294. YouTubeModule.rateLimiter.restart();
  295. axios
  296. .get("https://www.googleapis.com/youtube/v3/videos", {
  297. params,
  298. timeout: YouTubeModule.requestTimeout
  299. })
  300. .then(res => {
  301. if (res.data.err) {
  302. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${res.data.error.message}`);
  303. return reject(new Error("An error has occured. Please try again later."));
  304. }
  305. const songIds = [];
  306. res.data.items.forEach(item => {
  307. const songId = item.id;
  308. if (!item.topicDetails) return;
  309. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  310. songIds.push(songId);
  311. });
  312. return YouTubeModule.runJob(
  313. "FILTER_MUSIC_VIDEOS",
  314. { videoIds: payload.videoIds, page: page + 1 },
  315. this
  316. )
  317. .then(result => resolve({ songIds: songIds.concat(result.songIds) }))
  318. .catch(err => reject(err));
  319. })
  320. .catch(err => {
  321. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  322. return reject(new Error("Failed to find playlist from YouTube"));
  323. });
  324. });
  325. });
  326. }
  327. }
  328. export default new _YouTubeModule();