xmpp.js 1.66 KB
const xmpp = require("simple-xmpp");
const strftime = require("strftime");

const config = require("./config");
const logger = require("./logger");

const core = require("./core");
const messageTail = require("./message-tail");

logger.verbose("Initializing xmpp bot");
logger.info("Connecting to xmpp server", {jabber_id: config.jabber_id});

function onOnline(data) {
    logger.info("XMPP connected", {data: data});
    xmpp.getRoster();
    core.onOnline();
}
xmpp.on("online", onOnline);

function onError(err) {
    logger.warn('XMPP error', {err: err});
    setTimeout(function() {
        process.exit(1);
    }, 5000)
}
xmpp.on("error", onError);

function onSubscribe(from) {
    logger.info('Receive subscription request from ' + from);
    xmpp.acceptSubscription(from);

    logger.info('Subscribe back ' + from);
    xmpp.subscribe(from);
}
xmpp.on('subscribe', onSubscribe);

function onChat(from, msg) {
    logger.info('Incoming XMPP message', {from: from, msg: msg});

    messageTail.add({
        ts: strftime('%F %T'),
        direction: 'in',
        partner: from,
        msg: msg
    });

    core.onMessage(from, msg);
}
xmpp.on('chat', onChat);

function connect() {
    xmpp.connect({
        jid: config.jabber_id,
        password: config.jabber_password
    });
}
connect();

function sendMessage(to, msg) {
    logger.info("Sending XMPP message", {to: to, msg: msg});

    messageTail.add({
        ts: strftime('%F %T'),
        direction: 'out',
        partner: to,
        msg: msg
    });

    try {
        xmpp.send(to, msg);
    }
    catch(e) {
        logger.warn('Exception on sending XMPP message', {err: e});
    }
}

exports.sendMessage = sendMessage;