transport.js 2.6 KB
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;