spotify.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. import config from "config";
  2. import async from "async";
  3. import oauth from "oauth";
  4. import CoreClass from "../core";
  5. const { OAuth2 } = oauth;
  6. let apiResults = {
  7. access_token: "",
  8. token_type: "",
  9. expires_in: 0,
  10. expires_at: 0,
  11. scope: ""
  12. };
  13. class SpotifyModule extends CoreClass {
  14. constructor() {
  15. super("spotify");
  16. }
  17. initialize() {
  18. return new Promise((resolve, reject) => {
  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. this.SpotifyOauth = new OAuth2(client, secret, "https://accounts.spotify.com/", null, "api/token", null);
  24. async.waterfall(
  25. [
  26. next => {
  27. this.setStage(2);
  28. this.cache
  29. .runJob("HGET", { table: "api", key: "spotify" })
  30. .then(data => {
  31. next(null, data);
  32. })
  33. .catch(next);
  34. },
  35. (data, next) => {
  36. this.setStage(3);
  37. if (data) apiResults = data;
  38. next();
  39. }
  40. ],
  41. async err => {
  42. if (err) {
  43. err = await this.utils.runJob("GET_ERROR", {
  44. error: err
  45. });
  46. reject(new Error(err));
  47. } else {
  48. resolve();
  49. }
  50. }
  51. );
  52. });
  53. }
  54. GET_TOKEN() {
  55. return new Promise(resolve => {
  56. if (Date.now() > apiResults.expires_at) {
  57. this.runJob("REQUEST_TOKEN").then(() => {
  58. resolve(apiResults.access_token);
  59. });
  60. } else resolve(apiResults.access_token);
  61. });
  62. }
  63. REQUEST_TOKEN() {
  64. return new Promise(resolve => {
  65. async.waterfall(
  66. [
  67. next => {
  68. this.log("INFO", "SPOTIFY_REQUEST_TOKEN", "Requesting new Spotify token.");
  69. this.SpotifyOauth.getOAuthAccessToken("", { grant_type: "client_credentials" }, next);
  70. },
  71. (accessToken, refreshToken, results, next) => {
  72. apiResults = results;
  73. apiResults.expires_at = Date.now() + results.expires_in * 1000;
  74. this.cache
  75. .runJob("HSET", {
  76. table: "api",
  77. key: "spotify",
  78. value: apiResults,
  79. stringifyJson: true
  80. })
  81. .finally(() => next());
  82. }
  83. ],
  84. () => resolve()
  85. );
  86. });
  87. }
  88. }
  89. export default new SpotifyModule();