mockChannelManager.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var DEFAULT_PREFIX = 'POMELO:CHANNEL';
  2. var utils = require('../../lib/util/utils');
  3. var MockManager = function(app, opts) {
  4. this.app = app;
  5. this.opts = opts || {};
  6. this.prefix = opts.prefix || DEFAULT_PREFIX;
  7. };
  8. module.exports = MockManager;
  9. MockManager.prototype.start = function(cb) {
  10. this.usersMap = {};
  11. utils.invokeCallback(cb);
  12. };
  13. MockManager.prototype.stop = function(force, cb) {
  14. this.usersMap = null;
  15. utils.invokeCallback(cb);
  16. };
  17. MockManager.prototype.add = function(name, uid, sid, cb) {
  18. var key = genKey(this, name, sid);
  19. if(!this.usersMap[key]) {
  20. this.usersMap[key] = [];
  21. }
  22. this.usersMap[key].push(uid);
  23. utils.invokeCallback(cb);
  24. };
  25. MockManager.prototype.leave = function(name, uid, sid, cb) {
  26. var key = genKey(this, name, sid);
  27. var res = deleteFrom(uid, this.usersMap[key]);
  28. if(this.usersMap[key] && this.usersMap[key].length === 0) {
  29. delete this.usersMap[sid];
  30. }
  31. utils.invokeCallback(cb);
  32. };
  33. MockManager.prototype.getMembersBySid = function(name, sid, cb) {
  34. var key = genKey(this, name, sid);
  35. if(!this.usersMap[key])
  36. this.usersMap[key] = [];
  37. utils.invokeCallback(cb, null, this.usersMap[key]);
  38. };
  39. MockManager.prototype.destroyChannel = function(name, cb) {
  40. var servers = this.app.getServers();
  41. var server, removes = [];
  42. for(var sid in servers) {
  43. server = servers[sid];
  44. if(this.app.isFrontend(server)) {
  45. removes.push(genKey(this, name, sid));
  46. }
  47. }
  48. if(removes.length === 0) {
  49. utils.invokeCallback(cb);
  50. return;
  51. }
  52. for(var i = 0; i<removes.length; i++) {
  53. delete this.usersMap[removes[i]];
  54. }
  55. utils.invokeCallback(cb);
  56. };
  57. var genKey = function(self, name, sid) {
  58. return self.prefix + ':' + name + ':' + sid;
  59. };
  60. var deleteFrom = function(uid, group) {
  61. if(!group) {
  62. return true;
  63. }
  64. for(var i=0, l=group.length; i<l; i++) {
  65. if(group[i] === uid) {
  66. group.splice(i, 1);
  67. return true;
  68. }
  69. }
  70. return false;
  71. };