import { app , dialog } from "electron" ; import { createServer , Server } from "http" ; import socketIo from "socket.io" ; import { trayManager } from "../" ; import { error , success } from "../util/debug" ; import { clearActivity , getDiscordUser , rpcClients , setActivity } from "./discordManager" ; import { openFileDialog } from "./presenceDevManager" ; import { update as updateSettings } from "./settingsManager" ; export let io ; export let socket ; export let server ; export let connected = false ; export function init ( ) { return new Promise < void > ( resolve => { server = createServer ( ) ; io = new socketIo . Server ( server , { serveClient : false , allowEIO3 : true , allowRequest : ( req , callback ) => { const noOriginHeader = req . headers . origin === undefined ; callback ( null , noOriginHeader ) ; } } ) ; server . listen ( 3020 , ( ) => { resolve ( ) ; success ( "Opened socket" ) ; } ) ; server . on ( "error" , socketError ) ; io . on ( "connection" , socketConnection ) ; } ) ; } function socketConnection ( cSocket ) { success ( "Socket connection" ) ; socket = cSocket ; getDiscordUser ( ) . then ( user => socket . emit ( "discordUser" , user ) ) . catch ( _ => socket . emit ( "discordUser" , null ) ) ; socket . on ( "setActivity" , setActivity ) ; socket . on ( "clearActivity" , clearActivity ) ; socket . on ( "settingUpdate" , updateSettings ) ; socket . on ( "selectLocalPresence" , openFileDialog ) ; socket . on ( "getVersion" , ( ) => socket . emit ( "receiveVersion" , app . getVersion ( ) . replace ( /[\D]/g , "" ) ) ) ; socket . once ( "disconnect" , ( ) => { connected = false ; trayManager . update ( ) ; error ( "Socket disconnection." ) ; rpcClients . forEach ( c => c . destroy ( ) ) ; } ) ; connected = true ; trayManager . update ( ) ; } function socketError ( e ) { error ( e . message ) ; if ( e . code === "EADDRINUSE" ) { app . focus ( ) ; dialog . showErrorBox ( "Oh noes! Port error..." , `${ app . name } could not bind to port ${ e . port }.\nIs ${ app . name } running already?` ) ; app . quit ( ) ; } }