-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
536 lines (448 loc) · 18.8 KB
/
app.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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
"use strict";
if (!process.env.DEBUG) {
process.env.DEBUG = '*,-debug:*,-xmpp:*';
}
const Discord = require('./lib/RemDiscord.js'),
Xmpp = require('./lib/RamXmpp.js'),
debug = require('debug'),
LogInfo = debug('info'),
LogDebug = debug('debug:app'),
LogError = debug('error:app'),
LogDebugJabber = debug('debug:jabber'),
LogErrorJabber = debug('error:jabber'),
{ SYNC, load: loadConfig } = require('./lib/Configuration'),
config = loadConfig(`./config/${process.env.NODE_ENV || 'development'}.cjson`),
{
roomByJid: roomConfigByJid,
roomByChannel: roomConfigByChannel
} = config
;
new App().run();
function App() {
const
remDiscord = new Discord(config.discord.token),
discord = remDiscord.getClient(),
IgnoredNicks = new Map(),
reconnectTimeoutSec = 10,
ramXmpp = new Xmpp(config.jabber.userJid, config.jabber.userPass),
jabber = ramXmpp.getClient()
;
let
conferenceSendPresenceInterval,
jabberConnectedUsers = new Map(),
lastErrorStanza = null,
lastErrorCountMessage = null,
errorStanzasCount = null,
isConnecting = false,
extractArgs = function (text, limit=1) {
return text.split(/\s+/, limit).filter((v) => v)
}
;
this.run = () => {
let jabberInitiated = false;
discord.on('ready', () => {
LogInfo('Connected to discord as ' + discord.user.username + " - (" + discord.user.id + ")");
if (config.discord.activityMessage) {
discord.user.setActivity(config.discord.activityMessage)
.then(presence => LogDebug('Activity set', config.discord.activityMessage))
.catch(remDiscord.logError);
}
if (!jabberInitiated) {
jabberInitiated = true;
this.registerXMPPListeners();
ramXmpp.connect();
}
});
discord.on('disconnect', (closeEvent) => {
remDiscord.logError(closeEvent);
LogInfo(`Trying to reconnect to Discord after ${reconnectTimeoutSec} sec`);
setTimeout(remDiscord.connect, reconnectTimeoutSec * 1000)
});
// debug all Discord events
discord.on('debug', remDiscord.logDebug);
discord.on('message', (message) => {
if (message.webhookID // preventing duplicates, since we use webhook to send messages from jabber
|| message.author.id === discord.user.id
// || !message.author.bot
) {
return;
}
let commandName = '',
text = message.content
;
const isCommand = text.startsWith(config.prefix);
if (isCommand) {
commandName = message.content.slice(config.prefix.length).split(/\s+/,1).pop().toLowerCase();
text = message.content.slice(config.prefix.length + commandName.length + 1);
}
if ('ping' === commandName) {
message.channel.send('pong');
}
else if ('users' === commandName) {
let reply = 'Did not receive information about the presence';
let ignored = [...IgnoredNicks.keys()].join(', ');
if (roomConfigByChannel.has(message.channel.id)) {
const jid = roomConfigByChannel.get(message.channel.id).roomJid;
if (jabberConnectedUsers.has(jid)) {
reply = '**Online:** ' + this.escapeMarkdown([...jabberConnectedUsers.get(jid).keys()].join(', '));
}
}
else {
reply = 'This room is not associated with any jabber conference ¯\\_(ツ)_/¯';
}
if (ignored) {
reply += '\n**Ignored:** ' + this.escapeMarkdown(ignored);
}
remDiscord.send(message.channel.id, reply);
}
else if ('rooms' === commandName) {
let reply = 'Room list:';
for (const channelId of roomConfigByChannel.keys()) {
let channel = discord.channels.cache.get(channelId),
sync = roomConfigByChannel.get(channelId).sync
;
reply += `\n\`"${channel.guild.name}" #${channel.name} (${channelId}) ←→ ${roomConfigByChannel.get(channelId).roomJid} (sync: ${sync ? sync : SYNC.BOTH})\``;
}
remDiscord.send(message.channel.id, reply);
}
else if ('say' === commandName) {
if (message.author.id !== config.discord.adminId) {
remDiscord.send(message.channel.id, 'You cannot use this command.');
return;
}
const match = text.match(/^\s*([^\s]+)\s+(.*)/);
let reply = 'Can\'t recognize the command! Syntax: `<room> <message>`.',
replyToRoom = message.channel.id
;
if (match) {
const room = match[1],
msg = match[2]
;
if (!msg) {
reply += ' Looks like empty message content.';
}
// to discord
else if (room.match(/\d+/) && roomConfigByChannel.has(room)) {
replyToRoom = room;
reply = msg;
}
// to jabber
else if (roomConfigByJid.has(room)) {
ramXmpp.send(room, msg);
return;
}
else {
reply += ` Room not found. Try \`${config.prefix}rooms\` for room list.`;
}
}
remDiscord.send(replyToRoom, reply);
}
else if ('ignore' === commandName || 'unignore' === commandName || 'dont_ignore' === commandName) {
const nickname = extractArgs(text).pop(),
ignore = 'ignore' === commandName,
prefix = ignore ? '' : 'no longer'
;
if (!nickname) {
return;
}
if (ignore) {
IgnoredNicks.set(nickname, true)
}
else {
IgnoredNicks.delete(nickname)
}
remDiscord.send(
message.channel.id,
this.escapeStringTemplate`*${nickname}*${prefix} ignored.`
);
}
else if (roomConfigByChannel.has(message.channel.id)) {
if (roomConfigByChannel.get(message.channel.id).sync === SYNC.TO_DISCORD) {
LogDebug('Sync: ' + SYNC.TO_DISCORD + '. Skip message');
return;
}
const jid = roomConfigByChannel.get(message.channel.id).roomJid;
remDiscord.fixMessage('<@!' + message.author.id + '>', message).then((userNick) => {
if ('@null' === userNick || '@undefined' === userNick) {
userNick = '@' + message.author.username;
}
userNick = this.getNicknameWMask(jid, userNick);
const attachments = remDiscord.getAttachmentsLinks(message);
remDiscord.fixMessage(message.content, message).then((msg) => {
ramXmpp.send(jid,
userNick
+ msg
+ attachments
);
});
}).catch(LogError);
}
});
discord.on('error', (error) => {
remDiscord.logError({clientStatus: discord.status, message: error.message})
});
remDiscord.connect()
.catch((e) => {
LogError(e);
process.kill(process.pid, 'SIGTERM');
})
;
};
this.registerXMPPListeners = () => {
jabber.on('online', function () {
LogInfo('Connected to jabber as ' + config.jabber.userJid);
for (const roomJid of roomConfigByJid.keys()) {
LogInfo('Connecting to conf %s as %s', roomJid, roomConfigByJid.get(roomJid).nick);
ramXmpp.join(roomJid, roomConfigByJid.get(roomJid).nick);
}
// TODO: handle disconnect events by status codes (http://xmpp.org/extensions/xep-0045.html#registrar-statuscodes)
conferenceSendPresenceInterval = setInterval(function () {
for (const roomJid of roomConfigByJid.keys()) {
LogInfo('Reconnecting to conf %s as %s', roomJid, roomConfigByJid.get(roomJid).nick);
ramXmpp.join(roomJid, roomConfigByJid.get(roomJid).nick);
}
}, (config.jabber.reconnectIntervalSec || 600) * 1000);
});
jabber.on('offline', function () {
clearInterval(conferenceSendPresenceInterval);
if (isConnecting) {
LogInfo('Still connecting…');
return;
}
isConnecting = true;
LogInfo(`Trying to reconnect to Jabber after ${reconnectTimeoutSec} sec`);
setTimeout(function() {
jabber.connect();
isConnecting = false;
}, reconnectTimeoutSec * 1000)
});
jabber.on('error', function (e) {
const terminate = e === 'XMPP authentication failure';
LogErrorJabber(e);
if (config.discord.adminId) {
remDiscord.sendDM(
config.discord.adminId,
'**[Jabber error]** `' + e + '`'
)
.then(() => {
if (terminate) {
process.kill(process.pid, 'SIGTERM');
}
})
.catch((error) => {
LogError(error);
if (terminate) {
process.kill(process.pid, 'SIGTERM');
}
});
}
else if (terminate) {
process.kill(process.pid, 'SIGTERM');
}
});
ramXmpp.on('stanza:error', (stanza, from_jid) => {
let channelId = this.getChannelByJid(from_jid);
let errorChannel = false;
if (roomConfigByJid.has(from_jid)) {
errorChannel = roomConfigByJid.get(from_jid).stanzaErrorsChannelId;
}
if (errorChannel) {
channelId = errorChannel;
}
const error_count_text = 'Error thrown times: ';
// If the same as the previous error then just update message counter
if (lastErrorStanza && lastErrorStanza.toString() === stanza.toString()) {
++errorStanzasCount;
/** @see https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=edit */
lastErrorCountMessage
.edit(error_count_text + errorStanzasCount)
.catch(LogError);
return;
}
errorStanzasCount = 1;
remDiscord.send(
channelId,
'**[stanza:error]** ```' + stanza + '```'
).then(() => {
lastErrorStanza = stanza;
remDiscord
.send(
channelId,
error_count_text + errorStanzasCount
)
.then(
/**
* @param {Object|Message} message
* @see https://discord.js.org/#/docs/main/stable/class/Message */
message => {
lastErrorCountMessage = message;
}
)
;
}
).catch(LogError);
});
ramXmpp.on('presence:connect', (stanza, from_jid, from_nick) => {
if (!jabberConnectedUsers.has(from_jid)) {
jabberConnectedUsers.set(from_jid, new Map);
}
if (!jabberConnectedUsers.get(from_jid).has(from_nick)) {
jabberConnectedUsers.get(from_jid).set(from_nick, true);
if (!this.needShowPresence(from_jid)) {
return;
}
remDiscord.send(
this.getChannelByJid(from_jid),
`*\`${from_nick}\` joins the room.*`
).catch(LogError)
}
});
ramXmpp.on('presence:disconnect', (stanza, from_jid, from_nick, Status) => {
if (jabberConnectedUsers.has(from_jid)) {
jabberConnectedUsers.get(from_jid).delete(from_nick);
}
if (!this.needShowPresence(from_jid)) {
return;
}
if (!Status || '303' !== Status.getAttr('code')) {
remDiscord.send(
this.getChannelByJid(from_jid),
`*\`${from_nick}\` leaves the room.*`
).catch(LogError)
}
});
ramXmpp.on('presence:disconnect:kick', (stanza, from_jid, from_nick, Actor, Reason) => {
if (!this.needShowPresence(from_jid)) {
return;
}
const byNick = Actor ? Actor.getAttr('nick') : '',
reason = Reason ? Reason.getText() : '<reason not specified>'
;
remDiscord.send(
this.getChannelByJid(from_jid),
this.escapeStringTemplate`*${from_nick} kicked (${byNick}: ${reason}).*`
).catch(LogError)
});
ramXmpp.on('presence:disconnect:ban', (stanza, from_jid, from_nick, Actor, Reason) => {
if (!this.needShowPresence(from_jid)) {
return;
}
const byNick = Actor ? Actor.getAttr('nick') : '',
reason = Reason ? Reason.getText() : '<reason not specified>'
;
remDiscord.send(
this.getChannelByJid(from_jid),
this.escapeStringTemplate`*${from_nick} banned (${byNick}: ${reason}).*`
).catch(LogError)
});
ramXmpp.on('presence:rename', (stanza, from_jid, from_nick, new_nick) => {
jabberConnectedUsers.get(from_jid).delete(from_nick);
jabberConnectedUsers.get(from_jid).set(new_nick, true);
let reply = `*\`${from_nick}\` renamed to \`${new_nick}\`.*`;
if (IgnoredNicks.has(from_nick)) {
IgnoredNicks.delete(from_nick);
IgnoredNicks.set(new_nick, true);
reply += `\n*\`${new_nick}\` ignored.*`
}
if (!this.needShowPresence(from_jid)) {
return;
}
remDiscord.send(
this.getChannelByJid(from_jid),
reply
).catch(LogError)
});
ramXmpp.on('message:groupchat:subject', (stanza, from_jid, from_nick, Subject, has_delay) => {
const channelId = this.getChannelByJid(from_jid);
if (!remDiscord.canEditChannel(channelId)) {
const channel = remDiscord.getClient().channels.cache.get(channelId);
LogInfo('MANAGE_CHANNELS permission is required to set topic in "', channel ? channel.name : channelId, '" channel');
return;
}
const topic = Subject.getText();
LogInfo('Trying to set Discord topic: ', topic);
remDiscord.editChannel(channelId, topic + '\n\n' + from_jid, from_nick);
});
ramXmpp.on('message:groupchat', (stanza, from_jid, from_nick, Body, has_delay) => {
if (has_delay) {
return;
}
if (roomConfigByJid.get(from_jid).sync === SYNC.TO_JABBER) {
LogDebug('Sync: '+ SYNC.TO_JABBER +'. Skip message');
return;
}
// Reset latest error on receive normal message
lastErrorStanza = null;
if (from_nick === roomConfigByJid.get(from_jid).nick) {
return;
}
if (IgnoredNicks.has(from_nick)) {
LogDebug('Ignore msg from ' + from_nick);
return;
}
if (!Body) {
return;
}
const toChannel = this.getChannelByJid(from_jid);
remDiscord.sendAs(
from_nick,
toChannel,
this.escapeMarkdown(Body.getText())
).catch((error) => {
LogError(error);
return remDiscord.send(toChannel, this.escapeStringTemplate`**${from_nick}**: ${Body.getText()}`);
});
});
ramXmpp.on('message:chat', (stanza, from_jid, from_nick, Body) => {
if (!Body) {
return;
}
if (config.discord.adminId) {
remDiscord.sendDM(
config.discord.adminId,
this.escapeStringTemplate`**${stanza.from}:** ${Body.getText()}`
).catch(LogError);
}
});
ramXmpp.on('message:captcha', (stanza, from_jid, from_nick, Body) => {
if (!Body) {
return;
}
if (config.discord.adminId) {
remDiscord.sendDM(
config.discord.adminId,
this.escapeStringTemplate`**${stanza.from}:** ${Body.getText()}`
).catch(LogError);
}
});
};
this.getChannelByJid = (conferenceJID) => {
return roomConfigByJid.get(conferenceJID).roomChannelId;
};
this.needShowPresence = (conferenceJID) => {
return roomConfigByJid.get(conferenceJID).showPresence
};
this.getNicknameWMask = function (roomJid, fromNick) {
const mask = roomConfigByJid.get(roomJid).fromNickMask;
if (typeof mask === "string") {
return mask.replace('%nickname%', fromNick);
}
else {
return fromNick;
}
};
this.escapeMarkdown = (text) => {
// return original text if it has any URI
if (text.match(/[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,}/i)) {
return text;
}
return text.replace(/([*`~_\\])/g, '\\$1')
};
this.escapeStringTemplate = (strings, ...keys) => {
let result = [strings[0]];
for (let i = 0; i < keys.length; ++i) {
result.push(this.escapeMarkdown(keys[i]), strings[i + 1])
}
return result.join('');
}
}