youtube.js 9.0 KB

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