* add /twitch/status/:user badge * update comments * use a proper schema for the Twitch API calls * use a token to make Twitch api calls * fix handling of rate-limit error and bad token error * [twitch] get a token as soon as creating a Twitch service * [twitch] start both requests to users and stream before awaiting * [twitch] set a timeout to replace the token before it expires * [twitch] use authHelper * [twitch] skip tests when no credentials * [twitch] add one more status test * twitch: do not check whether a user exists
112 lines
2.9 KiB
JavaScript
112 lines
2.9 KiB
JavaScript
'use strict'
|
|
|
|
const Joi = require('@hapi/joi')
|
|
const { BaseJsonService } = require('..')
|
|
|
|
const tokenSchema = Joi.object({
|
|
access_token: Joi.string().required(),
|
|
refresh_token: Joi.string(),
|
|
expires_in: Joi.number(),
|
|
scope: Joi.array(),
|
|
token_type: Joi.string(),
|
|
})
|
|
|
|
function sleep(ms) {
|
|
return new Promise(resolve => setTimeout(resolve, ms))
|
|
}
|
|
|
|
// Abstract class for Twitch badges
|
|
module.exports = class TwitchBase extends BaseJsonService {
|
|
static get auth() {
|
|
return {
|
|
userKey: 'twitch_client_id',
|
|
passKey: 'twitch_client_secret',
|
|
isRequired: true,
|
|
}
|
|
}
|
|
|
|
constructor(...args) {
|
|
super(...args)
|
|
if (!TwitchBase.__twitchToken) {
|
|
TwitchBase.__twitchToken = this._getNewToken()
|
|
}
|
|
}
|
|
|
|
async _twitchToken() {
|
|
return TwitchBase.__twitchToken
|
|
}
|
|
|
|
async _getNewToken() {
|
|
const tokenRes = await super._requestJson({
|
|
schema: tokenSchema,
|
|
url: `https://id.twitch.tv/oauth2/token`,
|
|
options: {
|
|
method: 'POST',
|
|
qs: {
|
|
client_id: this.authHelper.user,
|
|
client_secret: this.authHelper.pass,
|
|
grant_type: 'client_credentials',
|
|
},
|
|
},
|
|
})
|
|
|
|
// replace the token when we are 80% near the expire time
|
|
// 2147483647 is the max 32-bit value that is accepted by setTimeout(), it's about 24.9 days
|
|
const replaceTokenMs = Math.min(
|
|
tokenRes.expires_in * 1000 * 0.8,
|
|
2147483647
|
|
)
|
|
const timeout = setTimeout(() => {
|
|
TwitchBase.__twitchToken = this._getNewToken()
|
|
}, replaceTokenMs)
|
|
|
|
// do not block program exit
|
|
timeout.unref()
|
|
|
|
return tokenRes.access_token
|
|
}
|
|
|
|
async _requestJson(request) {
|
|
// assign Client-ID and Authorization headers to request.options.headers if they are not set
|
|
request = {
|
|
...request,
|
|
options: {
|
|
...request.options,
|
|
headers: {
|
|
'Client-ID': this.authHelper.user,
|
|
Authorization: `Bearer ${await this._twitchToken()}`,
|
|
...(request.options && request.options.headers),
|
|
},
|
|
},
|
|
}
|
|
|
|
for (let i = 0; i < 3; i++) {
|
|
// 3 trials
|
|
try {
|
|
return await super._requestJson(request)
|
|
} catch (err) {
|
|
// if the token expire or is revoked
|
|
// https://dev.twitch.tv/docs/authentication/#refresh-in-response-to-server-rejection-for-bad-authentication
|
|
if (err.name === 'InvalidResponse' && err.response.statusCode === 401) {
|
|
TwitchBase.__twitchToken = this._getNewToken()
|
|
continue
|
|
}
|
|
|
|
// if API limit is exceeded
|
|
// https://dev.twitch.tv/docs/api/guide/#rate-limits
|
|
if (err.name === 'InvalidResponse' && err.response.statusCode === 429) {
|
|
const resetTimestamp = err.response.headers['ratelimit-reset']
|
|
await sleep(Math.abs(resetTimestamp - Date.now()) + 100)
|
|
continue
|
|
}
|
|
|
|
// cannot recover
|
|
throw err
|
|
}
|
|
}
|
|
|
|
// one last time
|
|
return super._requestJson(request)
|
|
}
|
|
}
|