-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
428 lines (383 loc) · 12.7 KB
/
node_helper.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
var NodeHelper = require("node_helper");
var ping = require("ping");
const { Freebox } = require("./components/freebox.js");
FB = (...args) => { /* do nothing */ };
module.exports = NodeHelper.create({
start () {
console.log("[Freebox] Starting...");
this.freebox = null;
this.pingValue = null;
this.interval = null;
this.cache = {};
this.update = null;
this.FreeboxVersion = null;
this.init = false;
},
async Freebox (config) {
this.Freebox_OS(config,this.config.showClientRate || this.config.showClientCnxType).then(
(res) => {
if (Object.keys(this.cache).length === 0) this.makeCache(res);
else {
this.makeResult(res);
this.updateInterval();
}
},
(err) => {
console.error(`[Freebox] ${err}`);
this.updateInterval();
}
);
},
scan () {
if (this.config.showPing) this.Ping();
this.Freebox(this.config.freebox);
},
/** scan main loop **/
updateInterval () {
clearInterval(this.update);
this.counterUpdate = this.config.updateDelay;
this.update = setInterval( ()=> {
this.counterUpdate -= 1000;
if (this.counterUpdate <= 0) {
clearInterval(this.update);
this.scan();
}
}, 1000);
},
socketNotificationReceived (notification, payload) {
switch(notification) {
case "INIT":
this.config = payload;
if (this.config.debug) FB = (...args) => { console.log("[Freebox]", ...args); };
console.log("[Freebox] Version:", require("./package.json").version, "rev:", require("./package.json").rev);
this.scan();
console.log("[Freebox] Started!");
break;
case "SCAN":
this.updateInterval();
break;
case "CACHE":
this.cache = {};
this.scan();
this.updateInterval();
break;
}
},
sendInfo (noti, payload) {
if (this.config.verbose) FB(`Send notification: ${noti}`, payload);
this.sendSocketNotification(noti, payload);
},
makeCache (res) {
this.cache = {};
if (this.config.debug) this.sendSocketNotification("debug", res);
if (Object.keys(res.Client).length > 0) {
for (let [item, client] of Object.entries(res.Client)) {
this.cache[client.l2ident.id] = {
name: client.primary_name ? client.primary_name : "(Appareil sans nom)",
type: client.host_type,
show: (!this.config.showFree && client.vendor_name.toLowerCase() === "freebox sas") ? false : this.config.showClient
};
}
}
this.cache = this.sortBy(this.cache, this.config.sortBy);
this.sendInfo("INITIALIZED", this.cache);
this.makeResult(res);
},
sortBy (data, sort) {
var result = {};
/** sort by type or by name **/
if (sort === "type" || sort === "name") {
FB("Sort cache by" , sort);
var arr = [];
for (var mac in data) {
if (data.hasOwnProperty(mac)) {
var obj = {};
obj[mac] = data[mac];
obj.Sort = data[mac][sort].toLowerCase();
arr.push(obj);
}
}
arr.sort((a, b)=> {
var at = a.Sort;
var bt = b.Sort;
return at > bt ? 1 : ( at < bt ? -1 : 0 );
});
for (var i=0, l=arr.length; i<l; i++) {
var obj = arr[i];
delete obj.Sort;
for (var mac in obj) {
if (obj.hasOwnProperty(mac)) {
var id = mac;
}
}
result[mac] = obj[id];
}
} else if (sort === "mac") {
/** sort by MAC **/
FB("Sort cache by", sort);
var mac = Object.keys(data);
mac.sort();
mac.forEach((macSort)=> {
result[macSort] = data[macSort];
});
} else {
/** other return the same **/
FB("Cache not sorted");
result = data;
}
return result;
},
makeResult (res) {
res.Clients = [];
var device = {};
res.Client.forEach((client)=> {
/** Array of client with used value in object **/
device = {
mac: client.l2ident.id,
name: client.primary_name ? client.primary_name : "(Appareil sans nom)",
ip: null,
type: client.host_type,
vendor: client.vendor_name,
debitDown: null,
debitUp:null,
active: client.active,
repeater: false,
access_type: null,
signal: null,
signal_percent: null,
signal_bar: null,
standard: null,
eth: null
};
let ip = client?.l3connectivities?.find((cnx) => cnx.af === "ipv4" && cnx.active);
device.ip = ip ? ip.addr : null;
if (client.access_point?.connectivity_type === "wifi") {
if (client.access_point?.wifi_information.band === "2d4g") device.band = "2d4g";
if (client.access_point?.wifi_information.band === "5g") device.band = "5g";
if (client.access_point?.wifi_information.band === "6g") device.band = "6g";
if (client.access_point?.wifi_information.band === "60g") device.band = "60g";
if (client.access_point?.wifi_information.signal) {
device.signal = client.access_point.wifi_information.signal;
device.signal_percent = this.wifiPercent(device.signal);
device.signal_bar = this.wifiBar(device.signal_percent);
}
if (client.access_point?.tx_rate) device.debitDown = this.convert(client.access_point.tx_rate*8,0,1); // Warn debit en bytes! (base 8)
else device.debitDown = "0 Ko/s";
if (client.access_point?.rx_rate) device.debitUp = this.convert(client.access_point.rx_rate*8,0,1); // Warn debit en bytes! (base 8)
else device.debitUp = "0 Ko/s";
if (client.access_point?.wifi_information?.standard) device.standard = client.access_point.wifi_information.standard;
}
if (this.config.showClientRate || this.config.showClientCnxType) {
res.EthCnx.forEach((info)=> {
if (info.mac_list) {
if (!info.mac_list.length) return; // return an object ???
var macList = info.mac_list.map((mac_list)=>{return mac_list.mac;});
macList.forEach((mac) => {
if (client.l2ident.id === mac) {
if (client.access_point?.connectivity_type === "wifi" && client.access_point?.type === "repeater") device.repeater = true;
else if (res[info.id] && res[info.id].tx_bytes_rate) {
if (this.config.showEthClientRate) {
device.debitDown = this.convert(res[info.id].tx_bytes_rate,0,1);
device.debitUp = this.convert(res[info.id].rx_bytes_rate,0,1);
}
device.access_type = "ethernet";
device.eth = info.id;
}
else {
/* try again next time */
}
}
});
}
});
}
// consider virtual machine is connected without access point and with only 1 names length !
// -> with only 1 names length -> prevent fake VM detect on disconnect (don't find other solution...)
if (!client.access_point && client.active && client.names?.length === 1) device.access_type = "VM";
res.Clients.push(device);
});
/** delete all Freebox result **/
delete res.Client;
delete res[1];
delete res[2];
delete res[3];
delete res[4];
delete res[5];
delete res[6];
delete res.EthCnx;
res.Ping = this.config.showPing ? this.pingValue : null;
this.sendInfo("RESULT", res);
},
Ping () {
ping.promise.probe(this.config.pingAdress,
{
timeout: 2,
extra: ["-4"]
})
.then((res)=> {
if (res.alive) this.pingValue = `${res.time} ms`;
else this.pingValue = "Erreur !";
});
},
/** Freebox OS API CALL **/
async Freebox_OS (config,clientRate) {
FB("Start Query Freebox Server:");
var rate;
var output;
const freebox = new Freebox(config);
await freebox.login();
if (!this.init) {
FB("Quering Freebox Model...");
const FreeboxVersion = await freebox.request({
method: "GET",
url: "api_version/"
});
this.FreeboxVersion = this.ModelSearh(FreeboxVersion.data.box_model_name);
FB("Found:", this.FreeboxVersion);
this.init = true;
}
FB("Quering Client...");
const clients = await freebox.request({
method: "GET",
url: "lan/browser/pub/"
});
FB("Quering ALL Ethernet Cnx...");
var ethCnx = await freebox.request({
method: "GET",
url:"switch/status/"
});
if (clientRate) {
FB("Quering Ethernet on port 1...");
var eth1 = await freebox.request({
method: "GET",
url:"switch/port/1/stats"
});
FB("Quering Ethernet on port 2...");
var eth2 = await freebox.request({
method: "GET",
url:"switch/port/2/stats"
});
FB("Quering Ethernet on port 3...");
var eth3 = await freebox.request({
method: "GET",
url:"switch/port/3/stats"
});
FB("Quering Ethernet on port 4...");
var eth4 = await freebox.request({
method: "GET",
url:"switch/port/4/stats"
});
if (this.config.checkFreePlug) {
FB("Quering Freeplug...");
var eth5 = await freebox.request({
method: "GET",
url:"switch/port/5/stats"
});
}
if (this.config.checkSFP) {
FB("Quering SFP...");
var eth6 = await freebox.request({
method: "GET",
url:"switch/port/9999/stats"
});
}
}
FB("Quering Connexion...");
const cnx = await freebox.request({
method: "GET",
url: "connection/"
});
FB("Done!");
bandwidthUp = this.convert(cnx.data.result.bandwidth_up,1,2);
bandwidthDown = this.convert(cnx.data.result.bandwidth_down,1,2);
debitDown = this.convert(cnx.data.result.rate_down,0,2);
debitUp = this.convert(cnx.data.result.rate_up,0,2);
type = (cnx.data.result.media === "xdsl") ? "xDSL" : ((cnx.data.result.media === "ftth") ? "FTTH" : "Inconnu");
degroup = (cnx.data.result.type === "rfc2684") ? true : false;
output = {
Model: this.FreeboxVersion,
Type: type,
Degroup: degroup,
BandwidthDown: bandwidthDown,
BandwidthUp: bandwidthUp,
DebitDown: debitDown,
DebitUp: debitUp,
IP: cnx.data.result.ipv4,
Client: clients.data.result ? clients.data.result : [],
EthCnx: clientRate && ethCnx.data.result ? ethCnx.data.result : [],
1: clientRate && eth1.data.result ? eth1.data.result : [],
2: clientRate && eth2.data.result ? eth2.data.result : [],
3: clientRate && eth3.data.result ? eth3.data.result : [],
4: clientRate && eth4.data.result ? eth4.data.result : [],
5: clientRate && this.config.checkFreePlug && eth5.data.result ? eth5.data.result : [],
6: clientRate && this.config.checkSFP && eth6.data.result ? eth6.data.result : []
};
await freebox.logout();
return output;
},
convert (data,type=0,FixTo=0) {
// type 0: octet / type:1 bytes
var value = Number(data);
if (value>1000000000) {
value=Number((value/1000000000).toFixed(FixTo));
if (type === 0) value = `${value} Go/s`;
if (type === 1) value = `${value} Gb/s`;
return value;
}
if (value>1000000) {
value=Number((value/1000000).toFixed(FixTo));
if (type === 0) value = `${value} Mo/s`;
if (type === 1) value = `${value} Mb/s`;
return value;
}
value=Number((value/1000).toFixed(FixTo));
if (type === 0) value = `${value} Ko/s`;
if (type === 1) value = `${value} Kb/s`;
return value;
},
/** Signal wifi en % **/
wifiPercent (dB) {
var quality = 2 * (dB + 100);
if (dB <= -80)
quality = 0;
else if (dB >= -50)
quality = 100;
return quality;
},
/** nbre de barre wifi selon % quality) **/
wifiBar (percent) {
return parseInt(((percent*5)/100).toFixed(0));
},
ModelSearh (model) {
try {
const freebox = model.split(" ");
var version = freebox[1];
const rev = freebox[2];
switch (version) {
case "v9":
version = "Ultra";
break;
case "v8":
version = "Pop";
break;
case "v7":
version = "Delta";
break;
case "Server":
case "v6":
version = "Révolution";
break;
default:
console.warn("[Freebox] Freebox Version not found !");
console.warn("[Freebox] Please contact developer with this freebox model:", model);
break;
}
let FreeboxName = `Freebox ${version} ${rev}`;
return FreeboxName;
} catch (e) {
console.warn("[Freebox] Error Freebox model formating!");
console.warn("[Freebox] Please contact developer with this freebox model:", model);
return model;
}
}
});