youtube.js 9.7 KB

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