myteams-api
Version:
An MyTeams Module to use discord.js and Twitch API easily
170 lines • 6.24 kB
JavaScript
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TwitchHelper = void 0;
const events_1 = require("events");
const Error_1 = require("../Utils/Error");
const node_fetch_1 = __importDefault(require("node-fetch"));
const util_1 = require("../Types/util");
class TwitchHelper extends events_1.EventEmitter {
client_secret;
client_id;
user;
access_token;
refresh_token;
scopes;
redirect_uri;
base;
refresh_attempts;
ready;
constructor(config) {
super();
this.client_secret = config.client_secret;
this.client_id = config.client_id;
this.access_token = config.access_token;
this.refresh_token = config.refresh_token;
this.scopes = config.scopes;
this.redirect_uri = config.redirect_uri;
this.base = "https://api.twitch.tv/helix";
this.refresh_attempts = 0;
this.ready = false;
this._init();
}
async _init() {
if (this.access_token) {
const currentUser = await this.getCurrentUser();
this.user = currentUser;
}
}
async _get(endpoint) {
if (!this.access_token) {
const accessToken = await this._getAppAccessToken();
if (!accessToken)
throw new Error_1.MyTeamsError("App access token could not be fetched. Please make sure your `client_id` and `client_secret` are correct.");
this.access_token = accessToken;
}
const url = this.base + endpoint;
const options = {
method: "GET",
headers: {
"Client-ID": this.client_id,
Authorization: `Bearer ${this.access_token}`,
},
};
const response = await node_fetch_1.default(url, options);
if (response.status === 401) {
await this._refresh();
return this._get(endpoint);
}
const result = await response.json();
return result;
}
async _getAppAccessToken() {
const data = {
client_id: this.client_id,
client_secret: this.client_secret,
grant_type: "client_credentials",
scope: this.scopes?.join(" "),
};
const endpoint = "https://id.twitch.tv/oauth2/token";
const response = await node_fetch_1.default(endpoint, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
},
});
const result = await response.text();
try {
const data = JSON.parse(result);
return data.access_token;
}
catch (err) {
throw new Error_1.MyTeamsError(`Error getting app access token. Expected twitch to return JSON object but got: ${result}`);
}
}
async _refresh() {
const valid = await this._validate();
if (valid)
return;
if (!this.refresh_token)
throw new Error_1.MyTeamsError("Refresh token is not set.");
const refreshData = {
client_id: this.client_id,
client_secret: this.client_secret,
grant_type: "refresh_token",
refresh_token: encodeURIComponent(this.refresh_token),
};
const url = "https://id.twitch.tv/oauth2/token";
const options = {
method: "POST",
body: JSON.stringify(refreshData),
headers: {
"Content-Type": "application/json",
},
};
const response = await node_fetch_1.default(url, options);
const result = await response.json();
const accessToken = result.access_token;
const refreshToken = result.refresh_token;
this.access_token = accessToken || this.access_token;
this.refresh_token = refreshToken || this.refresh_token;
if (this._isListeningFor("refresh"))
this.emit("refresh", result);
if (!accessToken)
this.refresh_attempts++;
}
async _validate() {
const url = "https://id.twitch.tv/oauth2/validate";
const options = {
headers: {
Authorization: `OAuth ${this.access_token}`,
},
};
const response = await node_fetch_1.default(url, options);
const result = await response.json();
const message = result.message;
const valid = response.status === 200;
if (message === "missing authorization token")
throw new Error_1.MyTeamsError(message);
return valid;
}
_isListeningFor(event) {
return this.eventNames().includes(event);
}
async getCurrentUser() {
const endpoint = "/users";
const result = await this._get(endpoint);
if (!result) {
throw new Error_1.MyTeamsError("Failed to get current user. This could be because you haven't provided an access_token connected to a user.");
}
const user = result.data[0];
return user;
}
async getStreams(options) {
let query = '?';
const endpoint = '/streams';
if (!options)
return this._get(endpoint);
const { channel, channels } = options;
if (channel) {
const key = util_1.isNumber(channel) ? "user_id" : "user_login";
query += `${key}=${channel}&`;
}
if (channels)
query += util_1.parseMixedParam({
values: channels,
stringKey: "user_login",
numericKey: "user_id"
});
query += "&";
query += util_1.parseOptions(options);
const response = await this._get(endpoint + query);
response.data.map(util_1.addThumbnailMethod);
return response;
}
}
exports.TwitchHelper = TwitchHelper;
//# sourceMappingURL=TwitchHelper.js.map