spotify.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. const CoreClass = require("../core.js");
  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. class SpotifyModule extends CoreClass {
  12. constructor() {
  13. super("spotify");
  14. }
  15. initialize() {
  16. return new Promise((resolve, reject) => {
  17. this.cache = this.moduleManager.modules["cache"];
  18. this.utils = this.moduleManager.modules["utils"];
  19. const client = config.get("apis.spotify.client");
  20. const secret = config.get("apis.spotify.secret");
  21. const OAuth2 = require("oauth").OAuth2;
  22. this.SpotifyOauth = new OAuth2(
  23. client,
  24. secret,
  25. "https://accounts.spotify.com/",
  26. null,
  27. "api/token",
  28. null
  29. );
  30. async.waterfall(
  31. [
  32. (next) => {
  33. this.setStage(2);
  34. this.cache
  35. .runJob("HGET", { table: "api", key: "spotify" })
  36. .then((data) => next(null, data))
  37. .catch(next);
  38. },
  39. (data, next) => {
  40. this.setStage(3);
  41. if (data) apiResults = data;
  42. next();
  43. },
  44. ],
  45. async (err) => {
  46. if (err) {
  47. err = await this.utils.runJob("GET_ERROR", {
  48. error: err,
  49. });
  50. reject(new Error(err));
  51. } else {
  52. resolve();
  53. }
  54. }
  55. );
  56. });
  57. }
  58. GET_TOKEN(payload) {
  59. return new Promise((resolve, reject) => {
  60. if (Date.now() > apiResults.expires_at) {
  61. this.runJob("REQUEST_TOKEN").then(() => {
  62. resolve(apiResults.access_token);
  63. });
  64. } else resolve(apiResults.access_token);
  65. });
  66. }
  67. REQUEST_TOKEN(payload) {
  68. //cb
  69. return new Promise((resolve, reject) => {
  70. async.waterfall(
  71. [
  72. (next) => {
  73. this.log(
  74. "INFO",
  75. "SPOTIFY_REQUEST_TOKEN",
  76. "Requesting new Spotify token."
  77. );
  78. this.SpotifyOauth.getOAuthAccessToken(
  79. "",
  80. { grant_type: "client_credentials" },
  81. next
  82. );
  83. },
  84. (access_token, refresh_token, results, next) => {
  85. apiResults = results;
  86. apiResults.expires_at =
  87. Date.now() + results.expires_in * 1000;
  88. this.cache
  89. .runJob("HSET", {
  90. table: "api",
  91. key: "spotify",
  92. value: apiResults,
  93. stringifyJson: true,
  94. })
  95. .finally(() => next());
  96. },
  97. ],
  98. () => {
  99. resolve();
  100. }
  101. );
  102. });
  103. }
  104. }
  105. module.exports = new SpotifyModule();