spotify.js 15 KB

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