spotify.js 2.1 KB

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