var UserStore = require('../persistence/users'); var dispatcher = require('../util/dispatcher'); var ChatService = function(app) { this.app = app; this.uidMap = {}; this.nameMap = {}; this.channelMap = {}; }; module.exports = ChatService; /** * Add player into a channel * * @param {String} uid user id * @param {String} cid channel id * @return {Number} see code.js */ ChatService.prototype.addToChannel = function(uid, cid, cb){ var me = this; UserStore.getByAttr('id', uid, false, function(e, user){ if(e){ return cb(e); } var sid = getSidByUid(uid, me.app); if(!sid){ return cb('invalid-connector-server'); } if(checkDuplicate(me, uid, cid)){ return cb(); } var channel = me.app.get('channelService').getChannel(cid, true); if(!channel){ return cb('invalid-channel'); } channel.add(uid, sid); addRecord(me, uid, user.username, sid, cid); cb(); }); }; /** * Add player record * * @param {String} uid user id */ ChatService.prototype.add = function(uid, cb){ var me = this; UserStore.getByAttr('id', uid, false, function(e, user){ if(e){ return cb(e); } var sid = getSidByUid(uid, me.app); if(!sid){ return cb('invalid-connector-server'); } addRecord(me, uid, user.username, sid); cb(); }); }; /** * User leaves the channel * * @param {String} uid user id * @param {String} cid channel id */ ChatService.prototype.leave = function(uid, cid) { var record = this.uidMap[uid]; var channel = this.app.get('channelService').getChannel(cid, true); if(channel && record) { channel.leave(uid, record.sid); } removeRecord(this, uid, cid); }; /** * Disconnect user from all channels in chat service. * This operation would remove the user from all channels and * clear all the records of the user. * * @param {String} uid user id */ ChatService.prototype.disconnect = function(uid){ var cids = this.channelMap[uid]; var record = this.uidMap[uid]; if(cids && record){ // remove user from channels var channel; for(var name in cids){ channel = this.app.get('channelService').getChannel(name); if(channel){ channel.leave(uid, record.sid); } } } clearRecords(this, uid); }; /** * Get friend list * @param {string} uid user id * @param {Function} cb callback function */ ChatService.prototype.getFriendList = function(uid, cb){ var me = this; UserStore.getByAttr('id', uid, { getFullEntity : true }, function(e, user){ if(e){ return cb(e); } user.friends = user.friends || []; for(var i=0;i