spotify.js 1.7 KB

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