spotify.js 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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) => {
  37. next(null, data);
  38. })
  39. .catch(next);
  40. },
  41. (data, next) => {
  42. this.setStage(3);
  43. if (data) apiResults = data;
  44. next();
  45. },
  46. ],
  47. async (err) => {
  48. if (err) {
  49. err = await this.utils.runJob("GET_ERROR", {
  50. error: err,
  51. });
  52. reject(new Error(err));
  53. } else {
  54. resolve();
  55. }
  56. }
  57. );
  58. });
  59. }
  60. GET_TOKEN(payload) {
  61. return new Promise((resolve, reject) => {
  62. if (Date.now() > apiResults.expires_at) {
  63. this.runJob("REQUEST_TOKEN").then(() => {
  64. resolve(apiResults.access_token);
  65. });
  66. } else resolve(apiResults.access_token);
  67. });
  68. }
  69. REQUEST_TOKEN(payload) {
  70. //cb
  71. return new Promise((resolve, reject) => {
  72. async.waterfall(
  73. [
  74. (next) => {
  75. this.log(
  76. "INFO",
  77. "SPOTIFY_REQUEST_TOKEN",
  78. "Requesting new Spotify token."
  79. );
  80. this.SpotifyOauth.getOAuthAccessToken(
  81. "",
  82. { grant_type: "client_credentials" },
  83. next
  84. );
  85. },
  86. (access_token, refresh_token, results, next) => {
  87. apiResults = results;
  88. apiResults.expires_at =
  89. Date.now() + results.expires_in * 1000;
  90. this.cache
  91. .runJob("HSET", {
  92. table: "api",
  93. key: "spotify",
  94. value: apiResults,
  95. stringifyJson: true,
  96. })
  97. .finally(() => {
  98. next();
  99. });
  100. },
  101. ],
  102. () => {
  103. resolve();
  104. }
  105. );
  106. });
  107. }
  108. }
  109. module.exports = new SpotifyModule();