spotify.js 2.0 KB

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