UNPKG

jkeveren-spotify-api

Version:

Promise based Spotify API wrapper that automatically refreshes access tokens

189 lines 9.81 kB
"use strict"; var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = (this && this.__generator) || function (thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; exports.__esModule = true; exports.SpotifyRequestError = exports.SpotifyClient = void 0; var SpotifyUser_1 = require("./SpotifyUser"); var http_1 = __importDefault(require("http")); var https_1 = __importDefault(require("https")); var path_1 = __importDefault(require("path")); var protocolMap = { "http:": http_1["default"], "https:": https_1["default"] }; var SpotifyClient = /** @class */ (function () { function SpotifyClient(config) { this.config = config; // set up default requester this._internalMakeRequest = defaultInternalMakeRequest; } // https://developer.spotify.com/documentation/general/guides/authorization/code-flow/#request-user-authorization SpotifyClient.prototype.getAuthorizationURL = function (redirectURL, scopes, state, showDialog) { var u = new URL(this.config.authBaseURL + "/authorize"); u.searchParams.set("client_id", this.config.clientId); u.searchParams.set("response_type", "code"); u.searchParams.set("redirect_uri", redirectURL); u.searchParams.set("state", state); u.searchParams.set("scope", scopes.join(" ")); u.searchParams.set("show_dialog", showDialog.toString()); return u; }; // Creates a user with tokens // https://developer.spotify.com/documentation/general/guides/authorization/code-flow/#request-access-token SpotifyClient.prototype.getUser = function (code, redirectURL) { return __awaiter(this, void 0, void 0, function () { var url, options, body, response, user, d; return __generator(this, function (_a) { switch (_a.label) { case 0: url = new URL(this.config.authBaseURL); url.pathname = path_1["default"].resolve(url.pathname, "api/token"); options = { method: "POST", headers: { authorization: "Basic " + Buffer.from(this.config.clientId + ":" + this.config.clientSecret).toString("base64"), "content-type": "application/x-www-form-urlencoded" } }; body = new URLSearchParams({ grant_type: "authorization_code", code: code, redirect_uri: redirectURL }).toString(); return [4 /*yield*/, this._internalMakeRequest(url, options, body)]; case 1: response = _a.sent(); if (response.statusCode != 200) { throw new SpotifyRequestError("Failed to get tokens for user", url.href, response); } user = new SpotifyUser_1.SpotifyUser(); user.client = this; user.accessToken = response.body.access_token; user.refreshToken = response.body.refresh_token; user.grantedScopes = response.body.scope.split(" "); d = new Date(); d.setSeconds(d.getSeconds() + response.body.expires_in); user.accessTokenExpiryDate = d; return [2 /*return*/, user]; } }); }); }; return SpotifyClient; }()); exports.SpotifyClient = SpotifyClient; var SpotifyRequestError = /** @class */ (function (_super) { __extends(SpotifyRequestError, _super); function SpotifyRequestError(message, requestURL, response) { var _this = this; message += " (statusCode: ".concat(response.statusCode, ")"); _this = _super.call(this, message) || this; _this.requestURL = requestURL; _this.response = response; return _this; } return SpotifyRequestError; }(Error)); exports.SpotifyRequestError = SpotifyRequestError; function defaultInternalMakeRequest(url, options, requestBody) { return __awaiter(this, void 0, void 0, function () { var httpModule, response, responseBody, spotifyResponse, contentType; return __generator(this, function (_a) { switch (_a.label) { case 0: httpModule = protocolMap[url.protocol]; return [4 /*yield*/, new Promise(function (resolve, reject) { var request = httpModule.request(url, options, resolve); request.on("error", reject); request.end(requestBody); })]; case 1: response = _a.sent(); return [4 /*yield*/, new Promise(function (resolve, reject) { var body = ""; response.on("readable", function () { var chunk; while (true) { chunk = response.read(); if (chunk != null) { body += chunk; } else { break; } } }); response.on("end", function () { resolve(body); }); response.on("error", reject); })]; case 2: responseBody = _a.sent(); spotifyResponse = { statusCode: response.statusCode, body: responseBody, incomingMessage: response }; contentType = response.headers["content-type"]; if (contentType !== undefined && response.headers["content-type"].indexOf("application/json") === 0) { spotifyResponse.body = JSON.parse(spotifyResponse.body); } return [2 /*return*/, spotifyResponse]; } }); }); } //# sourceMappingURL=SpotifyClient.js.map