adaptor-ym.js 2.4 KB
var YM;

var username;
var password;
var callbacks;

var isOnline = false;
var msSleepBeforeResendOnFail = 10000;

function onReady() {
    logger.info('Going to login to YM as ' + username);
    YM.login(username, password);
}

function onOnline(data) {
    isOnline = true;

    logger.info('YM login successful', {data: data});
    if (callbacks.onOnline) {
        callbacks.onOnline();
    }
}

function onLoginError(data) {
    logger.warn('YM login error', {data: data});
}

function onFriendsList(data) {
    logger.verbose('Got list of friendlist', {data: data});
}

function onPM(data) {
    if (data.sender == username) {
        return;
    }

    logger.verbose('Got a message', {data: data})
    if (callbacks.onPM) {
        callbacks.onPM(data.sender, data.message);
    }
}

function onPing(data) {
    logger.verbose('Got ping', {data: data});
}

function init(_username, _password, _logger, _callbacks) {
    username = _username;
    password = _password;
    logger = _logger;
    callbacks = _callbacks;

    delete YM;
    YM = require('yahoomessenger');

    YM.on('ready', onReady);
    YM.on('loginSuccessful', onOnline);
    YM.on('loginError', onLoginError);
    YM.on('friendsList', onFriendsList);
    YM.on('pm', onPM);
    YM.on('offlinePM', onPM);

    YM.newInstance();
}

function sendMessage(destination, msg, requestId) {
    if (!isOnline) {
        logger.info('We are not online right now, resending in ' + msSleepBeforeResendOnFail + 'ms', {destination: destination, msg: msg, requestId: requestId});

        setTimeout(
            sendMessage,
            msSleepBeforeResendOnFail,
            destination,
            msg,
            requestId
        )
        return;
    }

    if (destination != username) {
        logger.verbose('Sending message', {from: username, destination: destination, msg: msg, requestId: requestId});
    }
    
    try {
        YM.sendPM(destination, msg);
    }
    catch(e) {
        logger.warn(__filename + ': Exception on sending message: ' + e, {e: e, destination: destination, msg: msg, requestId: requestId});
        logger.info('Trying to relogin to YM in 5 secs');

        setTimeout(
            init,
            5000,
            username, password, logger, callbacks
        );
    }
}

function logout(){
    isOnline = false;
    try {
        YM.logout();
    } catch(e) {}
}

exports.init = init;
exports.sendMessage = sendMessage;
exports.isOnline = isOnline;