spotify.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. const coreClass = require("../core");
  2. const config = require('config'),
  3. async = require('async');
  4. let apiResults = {
  5. access_token: "",
  6. token_type: "",
  7. expires_in: 0,
  8. expires_at: 0,
  9. scope: "",
  10. };
  11. module.exports = class extends coreClass {
  12. constructor(name, moduleManager) {
  13. super(name, moduleManager);
  14. this.dependsOn = ["cache"];
  15. }
  16. initialize() {
  17. return new Promise((resolve, reject) => {
  18. this.cache = this.moduleManager.modules["cache"];
  19. const client = config.get("apis.spotify.client");
  20. const secret = config.get("apis.spotify.secret");
  21. const OAuth2 = require('oauth').OAuth2;
  22. const SpotifyOauth = new OAuth2(
  23. client,
  24. secret,
  25. 'https://accounts.spotify.com/',
  26. null,
  27. 'api/token',
  28. null);
  29. async.waterfall([
  30. (next) => {
  31. this.cache.hget("api", "spotify", next, true);
  32. },
  33. (data, next) => {
  34. if (data) apiResults = data;
  35. next();
  36. }
  37. ], async (err) => {
  38. if (err) {
  39. err = await this.utils.getError(err);
  40. reject(err);
  41. } else {
  42. resolve();
  43. }
  44. });
  45. });
  46. }
  47. async getToken() {
  48. try { await this._validateHook(); } catch { return; }
  49. return new Promise((resolve, reject) => {
  50. if (Date.now() > apiResults.expires_at) {
  51. this.requestToken(() => {
  52. resolve(apiResults.access_token);
  53. });
  54. } else resolve(apiResults.access_token);
  55. });
  56. }
  57. async requestToken(cb) {
  58. try { await this._validateHook(); } catch { return; }
  59. async.waterfall([
  60. (next) => {
  61. this.logger.info("SPOTIFY_REQUEST_TOKEN", "Requesting new Spotify token.");
  62. this.SpotifyOauth.getOAuthAccessToken(
  63. '',
  64. { 'grant_type': 'client_credentials' },
  65. next
  66. );
  67. },
  68. (access_token, refresh_token, results, next) => {
  69. apiResults = results;
  70. apiResults.expires_at = Date.now() + (results.expires_in * 1000);
  71. this.cache.hset("api", "spotify", apiResults, next, true);
  72. }
  73. ], () => {
  74. cb();
  75. });
  76. }
  77. }