spotify.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. import mongoose from "mongoose";
  2. import async from "async";
  3. import config from "config";
  4. import * as rax from "retry-axios";
  5. import axios from "axios";
  6. import url from "url";
  7. import CoreClass from "../core";
  8. let SpotifyModule;
  9. let DBModule;
  10. let CacheModule;
  11. let MediaModule;
  12. const spotifyTrackObjectToMusareTrackObject = spotifyTrackObject => {
  13. return {
  14. trackId: spotifyTrackObject.id,
  15. name: spotifyTrackObject.name,
  16. albumId: spotifyTrackObject.album.id,
  17. albumTitle: spotifyTrackObject.album.title,
  18. albumImageUrl: spotifyTrackObject.album.images[0].url,
  19. artists: spotifyTrackObject.artists.map(artist => artist.name),
  20. artistIds: spotifyTrackObject.artists.map(artist => artist.id),
  21. duration: spotifyTrackObject.duration_ms / 1000,
  22. explicit: spotifyTrackObject.explicit,
  23. externalIds: spotifyTrackObject.external_ids,
  24. popularity: spotifyTrackObject.popularity
  25. };
  26. };
  27. class RateLimitter {
  28. /**
  29. * Constructor
  30. *
  31. * @param {number} timeBetween - The time between each allowed YouTube request
  32. */
  33. constructor(timeBetween) {
  34. this.dateStarted = Date.now();
  35. this.timeBetween = timeBetween;
  36. }
  37. /**
  38. * Returns a promise that resolves whenever the ratelimit of a YouTube request is done
  39. *
  40. * @returns {Promise} - promise that gets resolved when the rate limit allows it
  41. */
  42. continue() {
  43. return new Promise(resolve => {
  44. if (Date.now() - this.dateStarted >= this.timeBetween) resolve();
  45. else setTimeout(resolve, this.dateStarted + this.timeBetween - Date.now());
  46. });
  47. }
  48. /**
  49. * Restart the rate limit timer
  50. */
  51. restart() {
  52. this.dateStarted = Date.now();
  53. }
  54. }
  55. class _SpotifyModule extends CoreClass {
  56. // eslint-disable-next-line require-jsdoc
  57. constructor() {
  58. super("spotify");
  59. SpotifyModule = this;
  60. }
  61. /**
  62. * Initialises the spotify module
  63. *
  64. * @returns {Promise} - returns promise (reject, resolve)
  65. */
  66. async initialize() {
  67. DBModule = this.moduleManager.modules.db;
  68. CacheModule = this.moduleManager.modules.cache;
  69. MediaModule = this.moduleManager.modules.media;
  70. // this.youtubeApiRequestModel = this.YoutubeApiRequestModel = await DBModule.runJob("GET_MODEL", {
  71. // modelName: "youtubeApiRequest"
  72. // });
  73. this.spotifyTrackModel = this.SpotifyTrackModel = await DBModule.runJob("GET_MODEL", {
  74. modelName: "spotifyTrack"
  75. });
  76. return new Promise((resolve, reject) => {
  77. this.rateLimiter = new RateLimitter(config.get("apis.spotify.rateLimit"));
  78. this.requestTimeout = config.get("apis.spotify.requestTimeout");
  79. this.axios = axios.create();
  80. this.axios.defaults.raxConfig = {
  81. instance: this.axios,
  82. retry: config.get("apis.spotify.retryAmount"),
  83. noResponseRetries: config.get("apis.spotify.retryAmount")
  84. };
  85. rax.attach(this.axios);
  86. resolve();
  87. });
  88. }
  89. /**
  90. *
  91. * @returns
  92. */
  93. GET_API_TOKEN() {
  94. return new Promise((resolve, reject) => {
  95. CacheModule.runJob("GET", { key: "spotifyApiKey" }, this).then(spotifyApiKey => {
  96. if (spotifyApiKey) {
  97. resolve(spotifyApiKey);
  98. return;
  99. }
  100. this.log("INFO", `No Spotify API token stored in cache, requesting new token.`);
  101. const clientId = config.get("apis.spotify.clientId");
  102. const clientSecret = config.get("apis.spotify.clientSecret");
  103. const unencoded = `${clientId}:${clientSecret}`;
  104. const encoded = Buffer.from(unencoded).toString("base64");
  105. const params = new url.URLSearchParams({ grant_type: "client_credentials" });
  106. SpotifyModule.axios
  107. .post("https://accounts.spotify.com/api/token", params.toString(), {
  108. headers: {
  109. Authorization: `Basic ${encoded}`,
  110. "Content-Type": "application/x-www-form-urlencoded"
  111. }
  112. })
  113. .then(res => {
  114. const { access_token: accessToken, expires_in: expiresIn } = res.data;
  115. // TODO TTL can be later if stuck in queue
  116. CacheModule.runJob(
  117. "SET",
  118. { key: "spotifyApiKey", value: accessToken, ttl: expiresIn - 30 },
  119. this
  120. )
  121. .then(spotifyApiKey => {
  122. this.log(
  123. "SUCCESS",
  124. `Stored new Spotify API token in cache. Expires in ${expiresIn - 30}`
  125. );
  126. resolve(spotifyApiKey);
  127. })
  128. .catch(err => {
  129. this.log(
  130. "ERROR",
  131. `Failed to store new Spotify API token in cache.`,
  132. typeof err === "string" ? err : err.message
  133. );
  134. reject(err);
  135. });
  136. })
  137. .catch(err => {
  138. this.log(
  139. "ERROR",
  140. `Failed to get new Spotify API token.`,
  141. typeof err === "string" ? err : err.message
  142. );
  143. reject(err);
  144. });
  145. });
  146. });
  147. }
  148. /**
  149. * Perform Spotify API get track request
  150. *
  151. * @param {object} payload - object that contains the payload
  152. * @param {object} payload.params - request parameters
  153. * @returns {Promise} - returns promise (reject, resolve)
  154. */
  155. API_GET_TRACK(payload) {
  156. return new Promise((resolve, reject) => {
  157. const { trackId } = payload;
  158. SpotifyModule.runJob(
  159. "API_CALL",
  160. {
  161. url: `https://api.spotify.com/v1/tracks/${trackId}`
  162. },
  163. this
  164. )
  165. .then(response => {
  166. resolve(response);
  167. })
  168. .catch(err => {
  169. reject(err);
  170. });
  171. });
  172. }
  173. /**
  174. * Perform Spotify API get playlist request
  175. *
  176. * @param {object} payload - object that contains the payload
  177. * @param {object} payload.params - request parameters
  178. * @returns {Promise} - returns promise (reject, resolve)
  179. */
  180. API_GET_PLAYLIST(payload) {
  181. return new Promise((resolve, reject) => {
  182. const { playlistId, nextUrl } = payload;
  183. SpotifyModule.runJob(
  184. "API_CALL",
  185. {
  186. url: nextUrl || `https://api.spotify.com/v1/playlists/${playlistId}/tracks`
  187. },
  188. this
  189. )
  190. .then(response => {
  191. resolve(response);
  192. })
  193. .catch(err => {
  194. reject(err);
  195. });
  196. });
  197. }
  198. /**
  199. * Perform Spotify API call
  200. *
  201. * @param {object} payload - object that contains the payload
  202. * @param {object} payload.url - request url
  203. * @param {object} payload.params - request parameters
  204. * @param {object} payload.quotaCost - request quotaCost
  205. * @returns {Promise} - returns promise (reject, resolve)
  206. */
  207. API_CALL(payload) {
  208. return new Promise((resolve, reject) => {
  209. // const { url, params, quotaCost } = payload;
  210. const { url } = payload;
  211. SpotifyModule.runJob("GET_API_TOKEN", {}, this)
  212. .then(spotifyApiToken => {
  213. SpotifyModule.axios
  214. .get(url, {
  215. headers: {
  216. Authorization: `Bearer ${spotifyApiToken}`
  217. },
  218. timeout: SpotifyModule.requestTimeout
  219. })
  220. .then(response => {
  221. if (response.data.error) {
  222. reject(new Error(response.data.error));
  223. } else {
  224. resolve({ response });
  225. }
  226. })
  227. .catch(err => {
  228. reject(err);
  229. });
  230. })
  231. .catch(err => {
  232. this.log(
  233. "ERROR",
  234. `Spotify API call failed as an error occured whilst getting the API token`,
  235. typeof err === "string" ? err : err.message
  236. );
  237. resolve(err);
  238. });
  239. });
  240. }
  241. /**
  242. * Create Spotify track
  243. *
  244. * @param {object} payload - an object containing the payload
  245. * @param {string} payload.spotifyTracks - the spotifyTracks
  246. * @returns {Promise} - returns a promise (resolve, reject)
  247. */
  248. CREATE_TRACKS(payload) {
  249. return new Promise((resolve, reject) => {
  250. async.waterfall(
  251. [
  252. next => {
  253. const { spotifyTracks } = payload;
  254. if (!Array.isArray(spotifyTracks)) next("Invalid spotifyTracks type");
  255. else {
  256. const trackIds = spotifyTracks.map(spotifyTrack => spotifyTrack.trackId);
  257. SpotifyModule.spotifyTrackModel.find({ trackId: trackIds }, (err, existingTracks) => {
  258. if (err) return next(err);
  259. const existingTrackIds = existingTracks.map(existingTrack => existingTrack.trackId);
  260. const newSpotifyTracks = spotifyTracks.filter(
  261. spotifyTrack => existingTrackIds.indexOf(spotifyTrack.trackId) === -1
  262. );
  263. SpotifyModule.spotifyTrackModel.insertMany(newSpotifyTracks, next);
  264. });
  265. }
  266. },
  267. (spotifyTracks, next) => {
  268. const mediaSources = spotifyTracks.map(spotifyTrack => `spotify:${spotifyTrack.trackId}`);
  269. async.eachLimit(
  270. mediaSources,
  271. 2,
  272. (mediaSource, next) => {
  273. MediaModule.runJob("RECALCULATE_RATINGS", { mediaSource }, this)
  274. .then(() => next())
  275. .catch(next);
  276. },
  277. err => {
  278. if (err) next(err);
  279. else next(null, spotifyTracks);
  280. }
  281. );
  282. }
  283. ],
  284. (err, spotifyTracks) => {
  285. if (err) reject(new Error(err));
  286. else resolve({ spotifyTracks });
  287. }
  288. );
  289. });
  290. }
  291. /**
  292. * Get Spotify track
  293. *
  294. * @param {object} payload - an object containing the payload
  295. * @param {string} payload.identifier - the spotify track ObjectId or track id
  296. * @param {string} payload.createMissing - attempt to fetch and create track if not in db
  297. * @returns {Promise} - returns a promise (resolve, reject)
  298. */
  299. GET_TRACK(payload) {
  300. return new Promise((resolve, reject) => {
  301. async.waterfall(
  302. [
  303. next => {
  304. const query = mongoose.isObjectIdOrHexString(payload.identifier)
  305. ? { _id: payload.identifier }
  306. : { trackId: payload.identifier };
  307. return SpotifyModule.spotifyTrackModel.findOne(query, next);
  308. },
  309. (track, next) => {
  310. if (track) return next(null, track, false);
  311. if (mongoose.isObjectIdOrHexString(payload.identifier) || !payload.createMissing)
  312. return next("Spotify track not found.");
  313. return SpotifyModule.runJob("API_GET_TRACK", { trackId: payload.identifier }, this)
  314. .then(({ response }) => {
  315. const { data } = response;
  316. if (!data || !data.id)
  317. return next("The specified track does not exist or cannot be publicly accessed.");
  318. const spotifyTrack = spotifyTrackObjectToMusareTrackObject(data);
  319. return next(null, false, spotifyTrack);
  320. })
  321. .catch(next);
  322. },
  323. (track, spotifyTrack, next) => {
  324. if (track) return next(null, track, true);
  325. return SpotifyModule.runJob("CREATE_TRACKS", { spotifyTracks: [spotifyTrack] }, this)
  326. .then(res => {
  327. if (res.spotifyTracks.length === 1) next(null, res.spotifyTracks[0], false);
  328. else next("Spotify track not found.");
  329. })
  330. .catch(next);
  331. }
  332. ],
  333. (err, track, existing) => {
  334. if (err) reject(new Error(err));
  335. else resolve({ track, existing });
  336. }
  337. );
  338. });
  339. }
  340. /**
  341. * Returns an array of songs taken from a Spotify playlist
  342. *
  343. * @param {object} payload - object that contains the payload
  344. * @param {string} payload.url - the id of the Spotify playlist
  345. * @returns {Promise} - returns promise (reject, resolve)
  346. */
  347. GET_PLAYLIST(payload) {
  348. return new Promise((resolve, reject) => {
  349. const spotifyPlaylistUrlRegex = /.+open\.spotify\.com\/playlist\/(?<playlistId>[A-Za-z0-9]+)/;
  350. const match = spotifyPlaylistUrlRegex.exec(payload.url);
  351. if (!match || !match.groups) {
  352. SpotifyModule.log("ERROR", "GET_PLAYLIST", "Invalid Spotify playlist URL query.");
  353. reject(new Error("Invalid playlist URL."));
  354. return;
  355. }
  356. const { playlistId } = match.groups;
  357. async.waterfall(
  358. [
  359. next => {
  360. let spotifyTracks = [];
  361. let total = -1;
  362. let nextUrl = "";
  363. async.whilst(
  364. next => {
  365. SpotifyModule.log(
  366. "INFO",
  367. `Getting playlist progress for job (${this.toString()}): ${
  368. spotifyTracks.length
  369. } tracks gotten so far. Total tracks: ${total}.`
  370. );
  371. next(null, nextUrl !== null);
  372. },
  373. next => {
  374. // Add 250ms delay between each job request
  375. setTimeout(() => {
  376. SpotifyModule.runJob("API_GET_PLAYLIST", { playlistId, nextUrl }, this)
  377. .then(({ response }) => {
  378. const { data } = response;
  379. if (!data)
  380. return next("The provided URL does not exist or cannot be accessed.");
  381. total = data.total;
  382. nextUrl = data.next;
  383. const { items } = data;
  384. const trackObjects = items.map(item => item.track);
  385. const newSpotifyTracks = trackObjects.map(trackObject =>
  386. spotifyTrackObjectToMusareTrackObject(trackObject)
  387. );
  388. spotifyTracks = spotifyTracks.concat(newSpotifyTracks);
  389. next();
  390. })
  391. .catch(err => next(err));
  392. }, 1000);
  393. },
  394. err => {
  395. if (err) next(err);
  396. else {
  397. return SpotifyModule.runJob("CREATE_TRACKS", { spotifyTracks }, this)
  398. .then(() => {
  399. next(
  400. null,
  401. spotifyTracks.map(spotifyTrack => spotifyTrack.trackId)
  402. );
  403. })
  404. .catch(next);
  405. }
  406. }
  407. );
  408. }
  409. ],
  410. (err, soundcloudTrackIds) => {
  411. if (err && err !== true) {
  412. SpotifyModule.log(
  413. "ERROR",
  414. "GET_PLAYLIST",
  415. "Some error has occurred.",
  416. typeof err === "string" ? err : err.message
  417. );
  418. reject(new Error(typeof err === "string" ? err : err.message));
  419. } else {
  420. resolve({ songs: soundcloudTrackIds });
  421. }
  422. }
  423. );
  424. // kind;
  425. });
  426. }
  427. // /**
  428. // * @param {object} payload - object that contains the payload
  429. // * @param {string} payload.url - the url of the SoundCloud resource
  430. // */
  431. // API_RESOLVE(payload) {
  432. // return new Promise((resolve, reject) => {
  433. // const { url } = payload;
  434. // SoundCloudModule.runJob(
  435. // "API_CALL",
  436. // {
  437. // url: `https://api-v2.soundcloud.com/resolve?url=${encodeURIComponent(url)}`
  438. // },
  439. // this
  440. // )
  441. // .then(response => {
  442. // resolve(response);
  443. // })
  444. // .catch(err => {
  445. // reject(err);
  446. // });
  447. // });
  448. // }
  449. }
  450. export default new _SpotifyModule();