transport.js
2.6 KB
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
const MODULE_NAME = 'TRANSPORT';
const SLEEP_BEFORE_TERMINATE_ON_ERROR_MS = 5 * 1000;
const bot = require('simple-xmpp');
const config = require('komodo-sdk/config');
const logger = require('komodo-sdk/logger');
const messagingService = require('komodo-center-messaging-client-lib');
let isReady;
bot.on('online', (data) => {
logger.info(`XMPP transport connected, JID: ${data.jid.user}`);
bot.getRoster();
setTimeout(
() => {
isReady = true;
logger.verbose('Transport is ready');
if (messagingService.onOnline) {
messagingService.onOnline({
me: config.username,
});
}
},
config.warming_up_ms || (30 * 1000),
);
});
bot.on('chat', (partner, msg) => {
if (!msg || !msg.trim()) {
return;
}
if (partner === config.username.replace(/\/.*$/, '')) {
return;
}
if (!isReady) {
logger.warn('Warming up is not finished yet, ignoring message', { me: config.username, partner, msg });
return;
}
logger.info('Incoming message via XMPP transport', { me: config.username, partner, msg });
if (messagingService && messagingService.onIncomingMessage) {
messagingService.onIncomingMessage(
{
me: config.username,
partner,
msg: msg.trim(),
},
);
}
});
bot.on('error', (err) => {
logger.warn(`${MODULE_NAME} F2E53C12: Error detected.`, {
eCode: err.code,
eMessage: err.message,
});
if (!config.do_not_terminate_on_error) {
logger.warn(`${MODULE_NAME} BA6C0C55: Terminating on error`, {
millisecondSleepBeforeTerminate: SLEEP_BEFORE_TERMINATE_ON_ERROR_MS,
});
setTimeout(() => {
process.exit(1);
}, SLEEP_BEFORE_TERMINATE_ON_ERROR_MS);
}
});
function send(partner, msg) {
logger.verbose('Sending message via XMPP transport', {
transport: 'xmpp', me: config.username, partner, msg,
});
bot.send(partner, msg);
}
bot.on('subscribe', (from) => {
logger.verbose(`Incoming subscribe request from ${from}`);
bot.acceptSubscription(from);
bot.subscribe(from);
});
function ping() {
if (isReady) bot.send(config.username, 'PING!');
}
function init() {
messagingService.setTransport(exports);
bot.connect({
jid: config.username,
password: config.password,
host: config.xmpp_host,
});
setInterval(
ping,
config.ping_interval_ms || 60000,
);
}
init();
exports.init = init;
exports.send = send;