EverydayTech Platform - Developer Reference
Complete Source Code Documentation - All Applications
Loading...
Searching...
No Matches
meshcentral.js
Go to the documentation of this file.
1/**
2* @fileoverview Meshcentral.js
3* @author Ylian Saint-Hilaire
4* @version v0.0.1
5*/
6
7var MeshServerCreateControl = function (domain, authCookie) {
8 var obj = {};
9 obj.State = 0;
10 obj.connectstate = 0;
11 obj.pingTimer = null;
12 obj.authCookie = authCookie;
13 //obj.trace = false;
14
15 obj.xxStateChange = function (newstate, errCode) {
16 if (obj.State == newstate) return;
17 var previousState = obj.State;
18 obj.State = newstate;
19 if (obj.onStateChanged) obj.onStateChanged(obj, obj.State, previousState, errCode);
20 }
21
22 obj.Start = function () {
23 if (obj.connectstate != 0) return;
24 obj.connectstate = 0;
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.
34 }
35
36 obj.Stop = function (errCode) {
37 obj.connectstate = 0;
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);
41 }
42
43 obj.xxOnMessage = function (e) {
44 if (obj.State == 1) { obj.xxStateChange(2); }
45 //console.log('xxOnMessage', e.data);
46 var message;
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);
54 };
55
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)); }
61 }
62 obj.socket.send(JSON.stringify(x));
63 }
64 }
65
66 return obj;
67}