UNPKG

twitch-toolkit

Version:

A set of tools to integrate with Twitch API, Twitch Chat and Twitch WebHooks.

347 lines (305 loc) 16.8 kB
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <title>twitchWebhook.js - Documentation</title> <script src="scripts/prettify/prettify.js"></script> <script src="scripts/prettify/lang-css.js"></script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css"> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <input type="checkbox" id="nav-trigger" class="nav-trigger" /> <label for="nav-trigger" class="navicon-button x"> <div class="navicon"></div> </label> <label for="nav-trigger" class="overlay"></label> <nav> <li class="nav-link nav-home-link"><a href="index.html">Home</a></li><li class="nav-heading">Classes</li><li class="nav-heading"><span class="nav-item-type type-class">C</span><span class="nav-item-name"><a href="TwitchApi.html">TwitchApi</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getAccessToken">getAccessToken</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getGames">getGames</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getStreams">getStreams</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getStreamsMetadata">getStreamsMetadata</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getUsers">getUsers</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getUsersFollows">getUsersFollows</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#getVideos">getVideos</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#isLive">isLive</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#updateUser">updateUser</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchApi.html#validateAccessToken">validateAccessToken</a></span></li><li class="nav-heading"><span class="nav-item-type type-class">C</span><span class="nav-item-name"><a href="TwitchChatEmitter.html">TwitchChatEmitter</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchChatEmitter.html#connect">connect</a></span></li><li class="nav-heading"><span class="nav-item-type type-class">C</span><span class="nav-item-name"><a href="TwitchPubSub.html">TwitchPubSub</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchPubSub.html#connect">connect</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchPubSub.html#disconnect">disconnect</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchPubSub.html#reconnect">reconnect</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchPubSub.html#subscribe">subscribe</a></span></li><li class="nav-heading"><span class="nav-item-type type-class">C</span><span class="nav-item-name"><a href="TwitchWebhook.html">TwitchWebhook</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchWebhook.html#destroy">destroy</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchWebhook.html#handleRequest">handleRequest</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchWebhook.html#subscribe">subscribe</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchWebhook.html#topicStreamUpDownSubscribe">topicStreamUpDownSubscribe</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchWebhook.html#topicUserFollowsSubscribe">topicUserFollowsSubscribe</a></span></li><li class="nav-item"><span class="nav-item-type type-function">F</span><span class="nav-item-name"><a href="TwitchWebhook.html#unsubscribe">unsubscribe</a></span></li><li class="nav-heading">Events</li><li class="nav-heading"><span class="nav-item-type type-event">E</span><span class="nav-item-name"><a href="TwitchChatEmitter.html#event:Chat:chat_parsed">Chat:chat_parsed</a></span></li><li class="nav-heading"><span class="nav-item-type type-event">E</span><span class="nav-item-name"><a href="TwitchWebhook.html#event:Webhook:stream_up_down">Webhook:stream_up_down</a></span></li><li class="nav-heading"><span class="nav-item-type type-event">E</span><span class="nav-item-name"><a href="TwitchWebhook.html#event:Webhook:user_follows">Webhook:user_follows</a></span></li> </nav> <div id="main"> <h1 class="page-title">twitchWebhook.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>'use strict'; const request = require('request-promise'); const util = require('util'); const eventemitter = require('eventemitter3'); const _ = require('./helpers'); const logger = require('./logger').getLogger(); const API_BASE_URL = 'https://api.twitch.tv/helix'; /** * @class TwitchWebhook * The Twitch Webhooks implementation, as described in https://dev.twitch.tv/docs/api/webhooks-guide/ . * The Webhook requires a public endpoint on the running express server/application to receive the data from the hub. Without this, its impossible to make this work. * * @param {object} config The config object. * @param {string} config.clientId The client ID of the user to be passed to the Hub (un)subscribe requests. This is required. * @param {string} config.callbackUrl The callback URL that will receive the Hub requests. These requests should be forwarded to the handleRequest method to properly handle these data. This is required. * @param {object} config.logger The logger object. */ function TwitchWebhook(config) { eventemitter.call(this); this.config = config; this.logger = config.logger || logger; this.secret = _.uuidv4(); this.subscribersMap = new Map(); } /** * Notifies when a follows event occurs. The response mimics the Get Users Follows endpoint. (https://dev.twitch.tv/docs/api/reference/#get-users-follows) * * @param {number} fromId The ID of the user who starts following someone. * @param {number} toId The ID of the user who has a new follower. * @return {string} The subscription ID, used to identify the active topic. * @fires TwitchWebhook#Webhook:user_follows */ TwitchWebhook.prototype.topicUserFollowsSubscribe = async function( fromId, toId ) { /** * Stream User Follows Event * @event TwitchWebhook#Webhook:user_follows * @param {object} data The data object received from the Hub. * @param {string} id The subscription ID. */ try { let topic = API_BASE_URL + '/users/follows?first=1'; if (fromId) { topic += '&amp;from_id=' + fromId; } else if (toId) { topic += '&amp;to_id=' + toId; } return await this.subscribe(topic, 'user_follows'); } catch (err) { throw err; } }; /** * Notifies when a stream goes online or offline. The response mimics the Get Streams endpoint. (https://dev.twitch.tv/docs/api/reference/#get-streams) * * @param {number} streamUserId The ID of the user whose stream is monitored. * @return {string} The subscription ID, used to identify the active topic. * @fires TwitchWebhook#Webhook:stream_up_down */ TwitchWebhook.prototype.topicStreamUpDownSubscribe = async function( streamUserId ) { /** * Stream Up/Down Event * @event TwitchWebhook#Webhook:stream_up_down * @param {object} data The data object received from the Hub. * @param {string} id The subscription ID. */ try { let topic = API_BASE_URL + '/streams?user_id=' + streamUserId; return await this.subscribe(topic, 'stream_up_down'); } catch (err) { throw err; } }; /** * Subscribe to a specific topic that will fires an event when new data is received from the hub. * The event handler will receive the data object and the subscription ID. * @param {string} topic The topic name/URL. * @param {string} eventName The event name that will be fired when new data is received. * @returns {Promise} The subscription promise that will be resolved when it receives the response. It will return the connection ID. */ TwitchWebhook.prototype.subscribe = async function(topic, eventName) { return new Promise(async (resolve, reject) => { try { this.logger.debug('Subscribing Webhook with topic: ' + topic); let item = { id: _.uuidv4(), topic: topic, eventName: eventName, subscribedAt: new Date(), secret: _.generateRandomKey(), promise: { resolve, reject } }; await request({ url: API_BASE_URL + '/webhooks/hub', method: 'POST', headers: { 'Client-ID': this.config.clientId, 'Content-Type': 'application/json' }, form: { 'hub.callback': this.config.callbackUrl + '?item.id=' + item.id, 'hub.mode': 'subscribe', 'hub.topic': topic, 'hub.lease_seconds': 864000, 'hub.secret': item.secret }, json: true }); this.subscribersMap.set(item.id, item); } catch (err) { reject(err); } }); }; /** * This method will handle the request data and validate the subscriptions or properly emit the events with the received data. * @param {string} method The http method * @param {string[]} headers The headers array * @param {string[]} qs The request query string array. Used for GET and POST * @param {string[]} body The POST body. Used just for post. * @returns {object} The response result object with the status and data to be sent in the response. */ TwitchWebhook.prototype.handleRequest = function(method, headers, qs, body) { this.logger.debug('Handling new Webhook request'); if (!method) throw new Error('Missing method parameter'); if (!headers) throw new Error('Missing headers parameter'); if (!qs) throw new Error('Missing qs Parameter'); if (method.toUpperCase() === 'GET') { return handleGetRequest.call(this, qs); } else if (method.toUpperCase() === 'POST') { return handlePostRequest.call(this, headers, body); } else { throw new Error('Invalid method ' + method); } }; /** * Unsubscribe from a topic by its ID. * @param {string} id The subscription ID. * @returns {Promise} The subscription promise that will be resolved when it receives the response. */ TwitchWebhook.prototype.unsubscribe = async function(id) { return new Promise(async (resolve, reject) => { try { this.logger.debug( 'Requesting Webhook unsubscription with id: ' + id ); if (this.subscribersMap.get(id)) { let item = this.subscribersMap.get(id); await request({ url: API_BASE_URL + '/webhooks/hub', method: 'POST', headers: { 'Client-ID': this.config.clientId, 'Content-Type': 'application/json' }, form: { 'hub.callback': this.config.callbackUrl + '?item.id=' + item.id, 'hub.mode': 'unsubscribe', 'hub.topic': item.topic, 'hub.secret': item.secret }, json: true }); item.promise = { resolve, reject }; } else { reject(new Error(`Unable to find subscription with id ${id}`)); } } catch (err) { reject(err); } }); }; /** * Destroy the Webhook, unsubscribing every active subscription. */ TwitchWebhook.prototype.destroy = async function() { try { this.logger.info('Destroying TwitchWebhook...'); for (let key of this.subscribersMap.keys()) { await this.unsubscribe(key); } this.subscribersMap = new Map(); this.logger.info('TwitchWebhook destroyed.'); } catch (err) { throw err; } }; function handleGetRequest(qs) { if (!qs['item.id']) { throw new Error('Missing item.id parameter.'); } else if (!this.subscribersMap.has(qs['item.id'])) { throw new Error(`Subscription with id ${qs['item.id']} missing. `); } let result = null; let error = null; if (qs['hub.mode'] === 'denied') { error = new Error( `Hub subscription denied. Reason: ${qs['hub.reason']}` ); result = { status: 200 }; } else if (!qs['hub.challenge']) { error = new Error('Missing the hub.challenge parameter'); result = { status: 410 }; } else { logger.debug( `Processing hub.mode: ${qs['hub.mode']} get request for id ${ qs['item.id'] }. Sending hub.challenge.` ); result = { status: 200, data: qs['hub.challenge'] }; } if ( this.subscribersMap.has(qs['item.id']) &amp;&amp; this.subscribersMap.get(qs['item.id']).promise ) { let subscription = this.subscribersMap.get(qs['item.id']); if (error) { subscription.promise.reject(error); } else { subscription.promise.resolve(qs['item.id']); } delete subscription.promise; } //Twitch, can for some reason send a denied after the challenge verification. This make sures the error //is properly handled and the subscription is removed from the map. if (error || qs['hub.mode'] === 'unsubscribe') { this.subscribersMap.delete(qs['item.id']); logger.error(error); } return result; } function handlePostRequest(headers, body) { if (!body) throw new Error('Missing body Parameter'); let id = body['item.id']; let signature = headers['x-hub-signature']; if (id &amp;&amp; this.subscribersMap.has(id)) { let item = this.subscribersMap.get(id); if ( _.validateHMACSignature( signature, 'sha256', item.secret, JSON.stringify(body) ) ) { this.emit(item.eventName, body.data, id); return { status: 200 }; } else { return { status: 403 }; } } else { return { status: 410 }; } } util.inherits(TwitchWebhook, eventemitter); module.exports = TwitchWebhook; </code></pre> </article> </section> </div> <br class="clear"> <footer> Generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Mon Nov 12 2018 18:32:59 GMT-0200 (E. South America Daylight Time) using the Minami theme. </footer> <script>prettyPrint();</script> <script src="scripts/linenumber.js"></script> </body> </html>