youtube.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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.youtubeId - 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.youtubeId,
  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. youtubeId: 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 regex = new RegExp(`[\\?&]list=([^&#]*)`);
  170. const splitQuery = regex.exec(payload.url);
  171. if (!splitQuery) {
  172. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Invalid YouTube playlist URL query.");
  173. return reject(new Error("Invalid playlist URL."));
  174. }
  175. const playlistId = splitQuery[1];
  176. return async.waterfall(
  177. [
  178. next => {
  179. let songs = [];
  180. let nextPageToken = "";
  181. async.whilst(
  182. next => {
  183. YouTubeModule.log(
  184. "INFO",
  185. `Getting playlist progress for job (${this.toString()}): ${
  186. songs.length
  187. } songs gotten so far. Is there a next page: ${nextPageToken !== undefined}.`
  188. );
  189. next(null, nextPageToken !== undefined);
  190. },
  191. next => {
  192. // Add 250ms delay between each job request
  193. setTimeout(() => {
  194. YouTubeModule.runJob("GET_PLAYLIST_PAGE", { playlistId, nextPageToken }, this)
  195. .then(response => {
  196. songs = songs.concat(response.songs);
  197. nextPageToken = response.nextPageToken;
  198. next();
  199. })
  200. .catch(err => next(err));
  201. }, 250);
  202. },
  203. err => next(err, songs)
  204. );
  205. },
  206. (songs, next) =>
  207. next(
  208. null,
  209. songs.map(song => song.contentDetails.videoId)
  210. ),
  211. (songs, next) => {
  212. if (!payload.musicOnly) return next(true, { songs });
  213. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: songs.slice() }, this)
  214. .then(filteredSongs => next(null, { filteredSongs, songs }))
  215. .catch(next);
  216. }
  217. ],
  218. (err, response) => {
  219. if (err && err !== true) {
  220. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  221. reject(new Error(err.message));
  222. } else {
  223. resolve({ songs: response.filteredSongs ? response.filteredSongs.youtubeIds : response.songs });
  224. }
  225. }
  226. );
  227. });
  228. }
  229. /**
  230. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST.
  231. *
  232. * @param {object} payload - object that contains the payload
  233. * @param {boolean} payload.playlistId - the playlist id to get videos from
  234. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  235. * @param {string} payload.url - the url of the YouTube playlist
  236. * @returns {Promise} - returns promise (reject, resolve)
  237. */
  238. GET_PLAYLIST_PAGE(payload) {
  239. return new Promise((resolve, reject) => {
  240. const params = {
  241. part: "contentDetails",
  242. playlistId: payload.playlistId,
  243. key: config.get("apis.youtube.key"),
  244. maxResults: 50
  245. };
  246. if (payload.nextPageToken) params.pageToken = payload.nextPageToken;
  247. YouTubeModule.rateLimiter.continue().then(() => {
  248. YouTubeModule.rateLimiter.restart();
  249. axios
  250. .get("https://www.googleapis.com/youtube/v3/playlistItems", {
  251. params,
  252. timeout: YouTubeModule.requestTimeout
  253. })
  254. .then(res => {
  255. if (res.data.err) {
  256. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${res.data.error.message}`);
  257. return reject(new Error("An error has occured. Please try again later."));
  258. }
  259. const songs = res.data.items;
  260. if (res.data.nextPageToken) return resolve({ nextPageToken: res.data.nextPageToken, songs });
  261. return resolve({ songs });
  262. })
  263. .catch(err => {
  264. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  265. if (err.message === "Request failed with status code 404") {
  266. return reject(new Error("Playlist not found. Is the playlist public/unlisted?"));
  267. }
  268. return reject(new Error("An error has occured. Please try again later."));
  269. });
  270. });
  271. });
  272. }
  273. /**
  274. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  275. *
  276. * @param {object} payload - object that contains the payload
  277. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  278. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  279. * @returns {Promise} - returns promise (reject, resolve)
  280. */
  281. FILTER_MUSIC_VIDEOS(payload) {
  282. return new Promise((resolve, reject) => {
  283. const page = payload.page ? payload.page : 0;
  284. const videosPerPage = 50;
  285. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  286. if (localVideoIds.length === 0) {
  287. return resolve({ videoIds: [] });
  288. }
  289. const params = {
  290. part: "topicDetails",
  291. id: localVideoIds.join(","),
  292. key: config.get("apis.youtube.key"),
  293. maxResults: videosPerPage
  294. };
  295. return YouTubeModule.rateLimiter.continue().then(() => {
  296. YouTubeModule.rateLimiter.restart();
  297. axios
  298. .get("https://www.googleapis.com/youtube/v3/videos", {
  299. params,
  300. timeout: YouTubeModule.requestTimeout
  301. })
  302. .then(res => {
  303. if (res.data.err) {
  304. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${res.data.error.message}`);
  305. return reject(new Error("An error has occured. Please try again later."));
  306. }
  307. const youtubeIds = [];
  308. res.data.items.forEach(item => {
  309. const youtubeId = item.id;
  310. if (!item.topicDetails) return;
  311. if (item.topicDetails.topicCategories.indexOf("https://en.wikipedia.org/wiki/Music") !== -1)
  312. youtubeIds.push(youtubeId);
  313. });
  314. return YouTubeModule.runJob(
  315. "FILTER_MUSIC_VIDEOS",
  316. { videoIds: payload.videoIds, page: page + 1 },
  317. this
  318. )
  319. .then(result => resolve({ youtubeIds: youtubeIds.concat(result.youtubeIds) }))
  320. .catch(err => reject(err));
  321. })
  322. .catch(err => {
  323. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  324. return reject(new Error("Failed to find playlist from YouTube"));
  325. });
  326. });
  327. });
  328. }
  329. }
  330. export default new _YouTubeModule();