youtube.js 10 KB

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