-
Notifications
You must be signed in to change notification settings - Fork 6
/
browser.js
87 lines (78 loc) · 2.47 KB
/
browser.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
import Emitter from 'events';
export default class extends Emitter {
constructor(mdns, mdnsType, serviceType = null) {
super();
this.mdnsType = mdnsType;
this.ready = false;
if (this.mdnsType === 'mdnsjs') {
this.browser = mdns.createBrowser(serviceType);
this.browser.on('ready', () => {
this.ready = true;
});
} else {
const sequence = [
mdns.rst.DNSServiceResolve(), // eslint-disable-line
'DNSServiceGetAddrInfo' in mdns.dns_sd ? mdns.rst.DNSServiceGetAddrInfo() : mdns.rst.getaddrinfo({ families: [0] }), // eslint-disable-line
mdns.rst.makeAddressesUnique(),
];
try {
this.browser = mdns.createBrowser(serviceType, { resolverSequence: sequence });
this.browser.on('error', (e) => { console.error(e); }); // eslint-disable-line no-console
this.ready = true;
} catch (e) {
console.error(e); // eslint-disable-line no-console
}
}
}
get ready() {
return this._ready || false;
}
set ready(newReady) {
this._ready = newReady;
if (newReady) {
this.emit('ready');
}
}
browse() {
if (!this.ready) {
return this.once('ready', this.browse.bind(this));
}
if (this.mdnsType === 'mdnsjs') {
this.browser.discover();
this.browser.on('update', this.serviceUp.bind(this));
} else if (this.mdnsType === 'mdns') {
this.browser.on('serviceUp', this.serviceUp.bind(this));
this.browser.on('serviceDown', this.serviceDown.bind(this));
this.browser.start();
}
}
serviceUp(service) {
this.emit('serviceUp', this._normalizeService(service));
}
serviceDown(service) {
this.emit('serviceDown', this._normalizeService(service));
}
stop() {
this.browser.stop();
}
_normalizeService(service) {
const normalized = {
addresses: service.addresses,
fullname: service.fullname,
interfaceIndex: service.interfaceIndex,
networkInterface: service.networkInterface,
port: service.port,
};
normalized.name = service.name || (service.fullname && service.fullname.substring(0, service.fullname.indexOf('.')));
normalized.txtRecord = service.txtRecord || (() => {
const records = {};
(service.txt || []).forEach((item) => {
const key = item.substring(0, item.indexOf('='));
const value = item.substring(item.indexOf('=') + 1);
records[key] = value;
});
return records;
})();
return normalized;
}
}