-
Notifications
You must be signed in to change notification settings - Fork 75
/
index.js
127 lines (118 loc) · 3.35 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
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
const tls = require('tls');
const EventEmitter = require('events');
const decrypt = require('../../utils/decrypt');
const HOST = 'mtalk.google.com';
const PORT = 5228;
const RETRY_MAX_TEMPO = 15; // maximum time before retrying to open the socket (in seconds)
const ON_NOTIFICATION_RECEIVED = 'ON_NOTIFICATION_RECEIVED';
const emitter = new EventEmitter();
let timer;
module.exports = {
ON_NOTIFICATION_RECEIVED,
connect,
emitter,
};
async function connect(
payload,
RequestType,
preBuffer,
NotificationSchema,
keys,
persistentIds,
retryCount = 0
) {
// Retry on disconnect
const retry = connect.bind(
this,
payload,
RequestType,
preBuffer,
NotificationSchema,
keys,
persistentIds,
retryCount + 1
);
const socket = await connectSocket(retry, retryCount);
timer = process.hrtime();
console.info('MCS client connected');
// Payload to send to login with MCS server
const buffer = toProtoBuf(payload, RequestType);
socket.write(
Buffer.concat([preBuffer, buffer], preBuffer.length + buffer.length)
);
// Listen for incoming messages
return listen(socket, NotificationSchema, keys, persistentIds);
}
function connectSocket(retry, retryCount) {
return new Promise(resolve => {
const socket = new tls.TLSSocket();
socket.setKeepAlive(true);
socket.on('close', () => {
const diff = process.hrtime(timer);
const minutes = Math.round((diff[0] + diff[1] / 1e9) / 60);
const retryTempo = Math.min(retryCount, RETRY_MAX_TEMPO);
console.warn(`MCS socket closed after ${minutes} minutes`);
console.warn(`Will try to reconnect in ${retryTempo} seconds`);
setTimeout(() => retry(), retryTempo * 1000);
});
socket.on('error', error => {
if (error.code === 'ECONNRESET') {
return console.warn('Connection to MCS server lost');
}
console.error('Error while communicating with MCS server');
console.error(error);
});
socket.connect(
{
host : HOST,
port : PORT,
},
() => {
// eslint-disable-next-line no-param-reassign
retryCount = 0; // Reset retry count on successful connection
resolve(socket);
}
);
});
}
function listen(socket, NotificationSchema, keys, persistentIds) {
socket.on('data', buffer =>
onMessageReceived(buffer, NotificationSchema, keys, persistentIds)
);
}
function toProtoBuf(payload, Type) {
const errMsg = Type.verify(payload);
if (errMsg) throw Error(errMsg);
const message = Type.create(payload);
return Type.encode(message).finish();
}
function onMessageReceived(buffer, NotificationSchema, keys, persistentIds) {
try {
const object = NotificationSchema.toObject(
NotificationSchema.decode(buffer),
{
longs : String,
enums : String,
bytes : Buffer,
}
);
// Already received
if (persistentIds.includes(object.persistentId)) {
return;
}
const message = decrypt(object, keys);
if (message) {
// Maintain persistentIds updated with the very last received value
persistentIds.push(object.persistentId);
// Send notification
emitter.emit(ON_NOTIFICATION_RECEIVED, {
notification : message,
// Need to be saved by the client
persistentId : object.persistentId,
});
}
} catch (e) {
// Not a notification
return;
}
}