2017-08-28 12:27:45 -04:00
/ * *
* @ fileoverview Meshcentral . js
* @ author Ylian Saint - Hilaire
* @ version v0 . 0.1
* /
var MeshServerCreateControl = function ( domain ) {
var obj = { } ;
obj . State = 0 ;
obj . connectstate = 0 ;
2018-07-13 22:18:43 -04:00
obj . pingTimer = null ;
2017-08-28 12:27:45 -04:00
obj . xxStateChange = function ( newstate ) {
if ( obj . State == newstate ) return ;
obj . State = newstate ;
if ( obj . onStateChanged ) obj . onStateChanged ( obj , obj . State ) ;
}
obj . Start = function ( ) {
obj . connectstate = 0 ;
obj . socket = new WebSocket ( window . location . protocol . replace ( "http" , "ws" ) + "//" + window . location . host + domain + "control.ashx" ) ;
obj . socket . onopen = function ( ) { obj . connectstate = 1 ; obj . xxStateChange ( 2 ) ; }
obj . socket . onmessage = obj . xxOnMessage ;
obj . socket . onclose = function ( ) { obj . Stop ( ) ; }
obj . xxStateChange ( 1 ) ;
2018-07-13 22:18:43 -04:00
if ( obj . pingTimer != null ) { clearInterval ( obj . pingTimer ) ; }
obj . pingTimer = setInterval ( function ( ) { obj . send ( { action : 'ping' } ) ; } , 29000 ) ; // Ping the server every 29 seconds, stops corporate proxies from disconnecting.
2017-08-28 12:27:45 -04:00
}
obj . Stop = function ( ) {
obj . connectstate = 0 ;
if ( obj . socket ) { obj . socket . close ( ) ; delete obj . socket ; }
2018-07-13 22:18:43 -04:00
if ( obj . pingTimer != null ) { clearInterval ( obj . pingTimer ) ; obj . pingTimer = null ; }
2017-08-28 12:27:45 -04:00
obj . xxStateChange ( 0 ) ;
}
obj . xxOnMessage = function ( e ) {
// console.log('xxOnMessage', e.data);
var message ;
try { message = JSON . parse ( e . data ) ; } catch ( e ) { return ; }
2018-07-13 22:18:43 -04:00
if ( message . action == 'pong' ) { return ; }
2017-08-28 12:27:45 -04:00
if ( obj . onMessage ) obj . onMessage ( obj , message ) ;
} ;
2018-02-11 20:13:26 -05:00
obj . send = function ( x ) { if ( obj . socket != null && obj . connectstate == 1 ) { obj . socket . send ( JSON . stringify ( x ) ) ; } }
2017-08-28 12:27:45 -04:00
return obj ;
}