spotify.js 15 KB

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