channelRemote.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Remote channel service for frontend server.
  3. * Receive push request from backend servers and push it to clients.
  4. */
  5. var utils = require('../../../util/utils');
  6. var logger = require('pomelo-logger').getLogger('pomelo', __filename);
  7. module.exports = function(app) {
  8. return new Remote(app);
  9. };
  10. var Remote = function(app) {
  11. this.app = app;
  12. };
  13. /**
  14. * Push message to client by uids.
  15. *
  16. * @param {String} route route string of message
  17. * @param {Object} msg message
  18. * @param {Array} uids userstate ids that would receive the message
  19. * @param {Object} opts push options
  20. * @param {Function} cb callback function
  21. */
  22. Remote.prototype.pushMessage = function(route, msg, uids, opts, cb) {
  23. if(!msg){
  24. logger.error('Can not send empty message! route : %j, compressed msg : %j',
  25. route, msg);
  26. utils.invokeCallback(cb, new Error('can not send empty message.'));
  27. return;
  28. }
  29. var connector = this.app.components.__connector__;
  30. var sessionService = this.app.get('sessionService');
  31. var fails = [], sids = [], sessions, j, k;
  32. for(var i=0, l=uids.length; i<l; i++) {
  33. sessions = sessionService.getByUid(uids[i]);
  34. if(!sessions) {
  35. fails.push(uids[i]);
  36. } else {
  37. for(j=0, k=sessions.length; j<k; j++) {
  38. sids.push(sessions[j].id);
  39. }
  40. }
  41. }
  42. logger.debug('[%s] pushMessage uids: %j, msg: %j, sids: %j', this.app.serverId, uids, msg, sids);
  43. connector.send(null, route, msg, sids, opts, function(err) {
  44. utils.invokeCallback(cb, err, fails);
  45. });
  46. };
  47. /**
  48. * Broadcast to all the client connectd with current frontend server.
  49. *
  50. * @param {String} route route string
  51. * @param {Object} msg message
  52. * @param {Boolean} opts broadcast options.
  53. * @param {Function} cb callback function
  54. */
  55. Remote.prototype.broadcast = function(route, msg, opts, cb) {
  56. var connector = this.app.components.__connector__;
  57. connector.send(null, route, msg, null, opts, cb);
  58. };