-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathclientWs.js
97 lines (81 loc) · 2.35 KB
/
clientWs.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
const { Server } = require('socket.io');
const TransactionSubscription = require('./clientWs/transactionSubscription')
class ClientWs {
constructor (config, logger, cb) {
if (!config || !config.enabled) {
return false;
}
const port = config.portWS;
const io = new Server(port, {
allowEIO3: true,
cors: config.cors
});
this.describes = {};
this.logger = logger;
io.sockets.on('connection', (socket) => {
try {
const describe = new TransactionSubscription(socket);
socket.on('address', (address) => {
const addresses = Array.isArray(address) ? address : [address];
const subscribed = describe.subscribeToAddresses(...addresses)
if (subscribed) {
this.describes[socket.id] = describe;
}
});
socket.on('types', (type) => {
const types = Array.isArray(type) ? type : [type];
const subscribed = describe.subscribeToTypes(...types)
if (subscribed) {
this.describes[socket.id] = describe;
}
});
socket.on('assetChatTypes', (type) => {
const types = Array.isArray(type) ? type : [type];
const subscribed = describe.subscribeToAssetChatTypes(...types)
if (subscribed) {
this.describes[socket.id] = describe;
}
})
socket.on('disconnect', () => {
delete this.describes[socket.id];
});
} catch (e) {
logger.debug('Error Connection socket: ' + e);
}
});
if (cb) {
return setImmediate(cb, null, this);
}
}
emit (t) {
if (lastTransactionsIds[t.id]) {
return;
}
lastTransactionsIds[t.id] = getUTime();
try {
const subs = findSubs(t, Object.values(this.describes));
subs.forEach((s) => {
s.socket.emit('newTrans', t);
});
} catch (e) {
this.logger.debug('Socket error emit ' + e);
}
}
}
const lastTransactionsIds = {};
setInterval(() => {
for (let id in lastTransactionsIds) {
if (getUTime() - lastTransactionsIds[id] >= 60) {
delete lastTransactionsIds[id];
}
}
}, 60 * 1000);
function getUTime () {
return new Date().getTime() / 1000;
}
function findSubs (transaction, subs) {
return subs.filter((sub) =>
sub.impliesTransaction(transaction),
);
}
module.exports = ClientWs;