From 18e732c088a40dbada7b4a4b07f64e50995d1101 Mon Sep 17 00:00:00 2001 From: Adhidarma Hadiwinoto <me@adhisimon.org> Date: Fri, 29 Jul 2016 09:23:37 +0700 Subject: [PATCH] relogin on send error --- adaptor-ym.js | 45 +++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) 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; -- 1.9.0