2* @fileoverview Meshcentral.js
3* @author Ylian Saint-Hilaire
7var MeshServerCreateControl = function (domain, authCookie) {
12 obj.authCookie = authCookie;
15 obj.xxStateChange = function (newstate, errCode) {
16 if (obj.State == newstate) return;
17 var previousState = obj.State;
19 if (obj.onStateChanged) obj.onStateChanged(obj, obj.State, previousState, errCode);
22 obj.Start = function () {
23 if (obj.connectstate != 0) return;
25 var url = window.location.protocol.replace('http', 'ws') + '//' + window.location.host + domain + 'control.ashx' + (urlargs.key ? ('?key=' + urlargs.key) : '');
26 if (obj.authCookie && (obj.authCookie != '')) { url += '?moreargs=1' }
27 obj.socket = new WebSocket(url);
28 obj.socket.onopen = function (e) { obj.connectstate = 1; if (obj.authCookie && (obj.authCookie != '')) { obj.send({ 'action': 'urlargs', 'args': { 'auth': obj.authCookie } }); } }
29 obj.socket.onmessage = obj.xxOnMessage;
30 obj.socket.onclose = function(e) { obj.Stop(e.code); }
31 obj.xxStateChange(1, 0);
32 if (obj.pingTimer != null) { clearInterval(obj.pingTimer); }
33 obj.pingTimer = setInterval(function () { obj.send({ action: 'ping' }); }, 29000); // Ping the server every 29 seconds, stops corporate proxies from disconnecting.
36 obj.Stop = function (errCode) {
38 if (obj.socket) { obj.socket.close(); delete obj.socket; }
39 if (obj.pingTimer != null) { clearInterval(obj.pingTimer); obj.pingTimer = null; }
40 obj.xxStateChange(0, errCode);
43 obj.xxOnMessage = function (e) {
44 if (obj.State == 1) { obj.xxStateChange(2); }
45 //console.log('xxOnMessage', e.data);
47 try { message = JSON.parse(e.data); } catch (e) { return; }
48 if ((typeof message != 'object') || (message.action == 'pong')) { return; }
49 if (message.action == 'ping') { obj.send({ action: 'pong' }); }
50 if (message.action == 'close') { if (message.msg) { console.log(message.msg); } obj.Stop(message.cause); return; }
51 if (obj.trace == 1) { console.log('RECV', message); }
52 else if (obj.trace == 2) { console.log('RECV', JSON.stringify(message)); }
53 if (obj.onMessage) obj.onMessage(obj, message);
56 obj.send = function (x) {
57 if (obj.socket != null && obj.connectstate == 1) {
58 if (x.action != 'ping') {
59 if (obj.trace == 1) { console.log('SEND', x); }
60 else if (obj.trace == 2) { console.log('SEND', JSON.stringify(x)); }
62 obj.socket.send(JSON.stringify(x));