forked from MrHilgert/csgo-log-receiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
87 lines (56 loc) · 1.94 KB
/
index.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
const dgram = require('dgram');
const EventEmmiter = require('events').EventEmitter;
const PacketParser = require('./PacketParser');
const Errors = require('./Errors');
class Server extends EventEmmiter {
constructor(opts) {
super();
this.opts = opts || {};
this.servers = {};
(this.opts.sources || []).forEach((source) => this.registerSource(source));
this.opts.port = this.opts.port || 9871;
this.opts.host = this.opts.host || '0.0.0.0';
this.parser = new PacketParser(this);
this.createSocket();
}
getSource(serverInfo) {
if (typeof (serverInfo) === "string") return this.__getSource(serverInfo);
return this.__getSource(this.stringifyServerId(serverInfo));
}
__getSource(serverId) {
if (!serverId) return undefined;
return this.servers[serverId];
}
registerSource(serverInfo) {
let serverId = this.stringifyServerId(serverInfo);
if (!serverId) return false;
this.servers[serverId] = serverInfo;
return true;
}
stringifyServerId(serverInfo) {
if (!serverInfo.address || !serverInfo.port) return undefined;
return `${serverInfo.address}:${serverInfo.port}`;
}
createSocket() {
this.socket = dgram.createSocket('udp4', this.handler.bind(this));
this.socket.bind(this.opts.port, this.opts.host);
}
closeSocket(cb) {
if(!this.socket) return;
this.socket.close(cb);
}
handler(message, senderInfo) {
if (!this.getSource(senderInfo)) return;
let parsedMessage = this.parser.parse(message, senderInfo);
if (parsedMessage.error)
return this.emit('err', {
server: senderInfo,
error: parsedMessage.error
});
this.emit('log', {
server: senderInfo,
message: parsedMessage
});
}
};
module.exports = Server;