diff --git a/adaptor-ym.js b/adaptor-ym.js index 9c90793..23ab15b 100644 --- a/adaptor-ym.js +++ b/adaptor-ym.js @@ -2,15 +2,19 @@ var YM = require('yahoomessenger'); 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(); @@ -49,19 +53,40 @@ function init(_username, _password, _logger, _callbacks) { YM.on('pm', onPM); YM.on('offlinePM', onPM); - /* - setTimeout( - YM.newInstance, - 3000 - ) - */ YM.newInstance(); } -function sendMessage(destination, msg) { - logger.verbose('Sending message', {from: username, destination: destination, msg: msg}); - YM.sendPM(destination, msg); +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; + } + + 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 3 secs'); + + isOnline = false; + setTimeout( + YM.newInstance, + 3000 + ); + } } exports.init = init; exports.sendMessage = sendMessage; +exports.isOnline = isOnline;