import io = require ( "socket.io-client" ) ; import { Result , emptySuccess , error } from "nodecg-io-core" ; import { StreamElementsEvent } from "./StreamElementsEvent" ; import { EventEmitter } from "events" ; export class StreamElementsServiceClient extends EventEmitter { private socket : SocketIOClient . Socket ; constructor ( private jwtToken , private handleTestEvents ) { super ( ) ; } private createSocket ( ) { this . socket = io ( "https://realtime.streamelements.com" , { transports : [ "websocket" ] } ) ; this . onConnect ( ( ) => { this . socket . emit ( "authenticate" , { method : "jwt" , token : this . jwtToken } ) ; } ) ; this . registerEvents ( ) ; } private registerEvents ( ) { this . onEvent ( ( data ) => { if ( data . type === "subscriber" ) { if ( data . data . gifted ) { this . emit ( "gift" , data ) ; } } this . emit ( data . type , data ) ; } ) ; if ( this . handleTestEvents ) { this . onTestEvent ( ( data ) => { if ( data . listener ) { this . emit ( "test" , data ) ; } } ) ; } } async connect ( ) { return new Promise ( ( resolve , _reject ) => { this . createSocket ( ) ; this . onConnect ( resolve ) ; } ) ; } async testConnection ( ) { return new Promise ( ( resolve , _reject ) => { this . createSocket ( ) ; this . onAuthenticated ( ( ) => { this . close ( ) ; resolve ( emptySuccess ( ) ) ; } ) ; this . onConnectionError ( ( err ) => { resolve ( error ( err ) ) ; } ) ; this . onUnauthorized ( ( err ) => { resolve ( error ( err ) ) ; } ) ; } ) ; } close ( ) { this . socket . close ( ) ; } private onConnect ( handler ) { this . socket . on ( "connect" , handler ) ; } private onAuthenticated ( handler ) { this . socket . on ( "authenticated" , handler ) ; } private onUnauthorized ( handler ) { this . socket . on ( "unauthorized" , ( err ) => { handler ( err . message ) ; } ) ; } private onConnectionError ( handler ) { this . socket . on ( "connect_error" , handler ) ; } private onEvent ( handler ) { this . socket . on ( "event" , ( data ) => { if ( data ) { handler ( data ) ; } } ) ; } private onTestEvent ( handler ) { this . socket . on ( "event:test" , ( data ) => { if ( data ) { handler ( data ) ; } } ) ; } public onSubscriber ( handler ) { this . on ( "subscriber" , handler ) ; } public onTip ( handler ) { this . on ( "tip" , handler ) ; } public onCheer ( handler ) { this . on ( "cheer" , handler ) ; } public onGift ( handler ) { this . on ( "gift" , handler ) ; } public onFollow ( handler ) { this . on ( "follow" , handler ) ; } public onRaid ( handler ) { this . on ( "raid" , handler ) ; } public onHost ( handler ) { this . on ( "host" , handler ) ; } public onTest ( handler ) { this . on ( "test" , handler ) ; } }