spotify.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.setStage(1);
  19. this.cache = this.moduleManager.modules["cache"];
  20. this.utils = this.moduleManager.modules["utils"];
  21. const client = config.get("apis.spotify.client");
  22. const secret = config.get("apis.spotify.secret");
  23. const OAuth2 = require('oauth').OAuth2;
  24. this.SpotifyOauth = new OAuth2(
  25. client,
  26. secret,
  27. 'https://accounts.spotify.com/',
  28. null,
  29. 'api/token',
  30. null);
  31. async.waterfall([
  32. (next) => {
  33. this.setStage(2);
  34. this.cache.hget("api", "spotify", next, true);
  35. },
  36. (data, next) => {
  37. this.setStage(3);
  38. if (data) apiResults = data;
  39. next();
  40. }
  41. ], async (err) => {
  42. if (err) {
  43. err = await this.utils.getError(err);
  44. reject(err);
  45. } else {
  46. resolve();
  47. }
  48. });
  49. });
  50. }
  51. async getToken() {
  52. try { await this._validateHook(); } catch { return; }
  53. return new Promise((resolve, reject) => {
  54. if (Date.now() > apiResults.expires_at) {
  55. this.requestToken(() => {
  56. resolve(apiResults.access_token);
  57. });
  58. } else resolve(apiResults.access_token);
  59. });
  60. }
  61. async requestToken(cb) {
  62. try { await this._validateHook(); } catch { return; }
  63. async.waterfall([
  64. (next) => {
  65. this.logger.info("SPOTIFY_REQUEST_TOKEN", "Requesting new Spotify token.");
  66. this.SpotifyOauth.getOAuthAccessToken(
  67. '',
  68. { 'grant_type': 'client_credentials' },
  69. next
  70. );
  71. },
  72. (access_token, refresh_token, results, next) => {
  73. apiResults = results;
  74. apiResults.expires_at = Date.now() + (results.expires_in * 1000);
  75. this.cache.hset("api", "spotify", apiResults, next, true);
  76. }
  77. ], () => {
  78. cb();
  79. });
  80. }
  81. }