-
Notifications
You must be signed in to change notification settings - Fork 0
/
node_helper.js
101 lines (88 loc) · 2.98 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
var self = this;
var NodeHelper = require("node_helper");
var bonjour = require('bonjour')();
var config = {
serviceTypes:[],
};
var cachedServices = [];
const isEqual = (obj1, obj2) => JSON.stringify(obj1) === JSON.stringify(obj2);
/**
* Update services on the network defined in the module config.
*/
const updateServices = () => {
config.serviceTypes.forEach(type => {
console.log("Updating Service [" + type + "]");
updateService(type);
});
};
function isServicesEqual(service1, service2) {
if(!isEqual(service1.fqdn, service2.fqdn))
return false;
if(!isEqual(service1.port, service2.port))
return false;
if(!isEqual(service1.protocol, service2.protocol))
return false;
if(!isEqual(service1.type, service2.type))
return false;
return true;
}
const updateService = (serviceType) => {
bonjour.find({ type: serviceType }, function (service) {
// Check if we have a duplicate
var matches = cachedServices.filter(value => isServicesEqual(value, service));
if(matches.length > 0) {
// replace existing service to get the latest
cachedServices = cachedServices.filter(service1 => !isServicesEqual(service, service1));
}
// Add entry
cachedServices.push(service);
if (matches.length === 0) {
self.sendSocketNotification("SERVICE_UPDATE", serviceType);
}
});
bonjour.find({ type: serviceType, protocol: "udp" }, function (service) {
// Check if we have a duplicate
var matches = cachedServices.filter(value => isServicesEqual(value, service));
if(matches.length > 0) {
// replace existing service to get the latest
cachedServices = cachedServices.filter(service1 => !isServicesEqual(service, service1));
}
// Add entry
cachedServices.push(service);
if (matches.length === 0) {
self.sendSocketNotification("SERVICE_UPDATE", serviceType);
}
});
};
module.exports = NodeHelper.create({
// Subclass start method.
start: function() {
self = this;
},
// Subclass socketNotificationReceived received.
socketNotificationReceived: function(notification, payload) {
switch (notification) {
case "CONFIG": {
console.log("Configuration updated");
config = payload;
break;
}
case "SERVICE_GET": {
self.sendSocketNotification("SERVICE_LIST", cachedServices);
break;
}
case "SERVICE_UPDATE": {
// browse for all http services
updateServices((!payload || payload === "*") ? "" : payload);
break;
}
case "SERVICE_UPDATE_SPECIFIC": {
// browse for all http services
updateService(payload);
break;
}
default: {
}
}
},
});