youtube.js 8.4 KB

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