youtube.js 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. if (!payload.musicOnly) return next(true, { songs });
  133. return YouTubeModule.runJob(
  134. "FILTER_MUSIC_VIDEOS_YOUTUBE",
  135. {
  136. videoIds: songs.slice()
  137. },
  138. this
  139. )
  140. .then(filteredSongs => {
  141. next(null, { filteredSongs, songs });
  142. })
  143. .catch(next);
  144. }
  145. ],
  146. (err, response) => {
  147. if (err && err !== true) {
  148. YouTubeModule.log("ERROR", "GET_PLAYLIST", "Some error has occurred.", err.message);
  149. reject(new Error("Some error has occurred."));
  150. } else {
  151. resolve(response);
  152. }
  153. }
  154. );
  155. });
  156. }
  157. /**
  158. * Returns a a page from a YouTube playlist. Is used internally by GET_PLAYLIST.
  159. *
  160. * @param {object} payload - object that contains the payload
  161. * @param {boolean} payload.playlistId - the playlist id to get videos from
  162. * @param {boolean} payload.nextPageToken - the nextPageToken to use
  163. * @param {string} payload.url - the url of the YouTube playlist
  164. * @returns {Promise} - returns promise (reject, resolve)
  165. */
  166. GET_PLAYLIST_PAGE(payload) {
  167. // payload includes: playlistId, nextPageToken
  168. return new Promise((resolve, reject) => {
  169. const nextPageToken = payload.nextPageToken ? `pageToken=${payload.nextPageToken}` : "";
  170. const videosPerPage = 50;
  171. const youtubeParams = [
  172. "part=contentDetails",
  173. `playlistId=${encodeURIComponent(payload.playlistId)}`,
  174. `maxResults=${videosPerPage}`,
  175. `key=${config.get("apis.youtube.key")}`,
  176. nextPageToken
  177. ].join("&");
  178. request(`https://www.googleapis.com/youtube/v3/playlistItems?${youtubeParams}`, async (err, res, body) => {
  179. if (err) {
  180. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${err.message}`);
  181. return reject(new Error("An error has occured. Please try again later."));
  182. }
  183. body = JSON.parse(body);
  184. if (body.error) {
  185. YouTubeModule.log("ERROR", "GET_PLAYLIST_PAGE", `${body.error.message}`);
  186. return reject(new Error("An error has occured. Please try again later."));
  187. }
  188. const songs = body.items;
  189. if (body.nextPageToken) return resolve({ nextPageToken: body.nextPageToken, songs });
  190. return resolve({ songs });
  191. });
  192. });
  193. }
  194. /**
  195. * Filters a list of YouTube videos so that they only contains videos with music. Is used internally by GET_PLAYLIST
  196. *
  197. * @param {object} payload - object that contains the payload
  198. * @param {Array} payload.videoIds - an array of YouTube videoIds to filter through
  199. * @param {Array} payload.page - the current page/set of video's to get, starting at 0. If left null, 0 is assumed. Will recurse.
  200. * @returns {Promise} - returns promise (reject, resolve)
  201. */
  202. FILTER_MUSIC_VIDEOS(payload) {
  203. return new Promise((resolve, reject) => {
  204. const page = payload.page ? payload.page : 0;
  205. const videosPerPage = 50; // 50 is the max I believe
  206. const localVideoIds = payload.videoIds.splice(page * 50, videosPerPage);
  207. if (localVideoIds.length === 0) {
  208. return resolve({ videoIds: [] });
  209. }
  210. const youtubeParams = [
  211. "part=topicDetails",
  212. `id=${encodeURIComponent(localVideoIds.join(","))}`,
  213. `maxResults=${videosPerPage}`,
  214. `key=${config.get("apis.youtube.key")}`
  215. ].join("&");
  216. return request(`https://www.googleapis.com/youtube/v3/videos?${youtubeParams}`, (err, res, body) => {
  217. if (err) {
  218. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${err.message}`);
  219. return reject(new Error("Failed to find playlist from YouTube"));
  220. }
  221. body = JSON.parse(body);
  222. if (body.error) {
  223. YouTubeModule.log("ERROR", "FILTER_MUSIC_VIDEOS", `${body.error.message}`);
  224. return reject(new Error("An error has occured. Please try again later."));
  225. }
  226. const songIds = [];
  227. body.items.forEach(item => {
  228. const songId = item.id;
  229. if (!item.topicDetails) return;
  230. if (item.topicDetails.relevantTopicIds.indexOf("/m/04rlf") !== -1) {
  231. songIds.push(songId);
  232. }
  233. });
  234. return YouTubeModule.runJob("FILTER_MUSIC_VIDEOS", { videoIds: payload.videoIds, page: page + 1 })
  235. .then(result => {
  236. resolve({ songIds: songIds.concat(result.songIds) });
  237. })
  238. .catch(err => {
  239. reject(err);
  240. });
  241. });
  242. });
  243. }
  244. }
  245. export default new _YouTubeModule();