all files / dist/satellites/ chatRooms.js

76.79% Statements 172/224
56.67% Branches 68/120
81.48% Functions 44/54
75.85% Lines 157/207
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756          17×             18×                                                                                                                                                                         94×     94×           94×   94× 89×       94×                         94×     94×   94×                   94×                         94×     94× 94× 94×                                           94×     94×     94× 282×                                                               18×     18×   18× 16×     16×                                                                                                                           123×     123× 123×   123× 121×       123× 123×                                                                       15× 15× 15×                                             66×     66×           66×     66× 17× 17×   17×       49× 49×             49×   49×         49×   49× 49× 49× 49×                                   92×       92×         92×     92× 43× 43×   43×       49×   49×               49×   49×         49×   49×     49× 49×       49× 49×                                       49×   49×                                   188×                                                 332×   332× 332×     332× 234×       332×   646×     646× 551×       95× 95×           89×         332× 332× 95×     95×         332×                             15×                                 282×     282×         282× 142×       140× 140× 140×                                                                                                               94×       18× 18×                      
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Eif (protoProps) defineProperties(Constructor.prototype, protoProps); Iif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _async = require('async');
 
var _async2 = _interopRequireDefault(_async);
 
var _utils = require('../utils');
 
var _utils2 = _interopRequireDefault(_utils);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
var ChatRooms = function () {
 
  /**
   * Constructor.
   *
   * @param api API reference.
   */
 
 
  /**
   * List of globals middleware.
   *
   * @type {Array}
   */
 
 
  /**
   * API reference.
   *
   * @type {null}
   */
 
  function ChatRooms(api) {
    _classCallCheck(this, ChatRooms);
 
    this.api = null;
    this.keys = {
      rooms: 'stellar:chatRoom:rooms',
      members: 'stellar:chatRoom:members'
    };
    this.globalMiddleware = [];
    this.middleware = {};
    this.api = api;
  }
 
  /**
   * Add a new middleware to the chat room manager.
   *
   * @param data  Middleware object.
   */
 
 
  /**
   * List of all middleware.
   *
   * @type {{}}
   */
 
 
  /**
   * Keys to use to save rooms and members on redis server.
   *
   * @type {{rooms: string, members: string}}
   */
 
 
  _createClass(ChatRooms, [{
    key: 'addMiddleware',
    value: function addMiddleware(data) {
      var self = this;
 
      // middleware must have a name
      Iif (!data.name) {
        throw new Error('middleware.name is required');
      }
 
      // if the middleware don't have a priority set a default value
      Eif (!data.priority) {
        data.priority = self.api.config.general.defaultMiddlewarePriority;
      }
 
      // ensure the priority is a number
      data.priority = Number(data.priority);
 
      // save the middleware object
      self.middleware[data.name] = data;
 
      // push the middleware name to the globalMiddleware
      self.globalMiddleware.push(data.name);
 
      // sort the globalMiddleware by priority
      self.globalMiddleware.sort(function (a, b) {
        Iif (self.middleware[a].priority > self.middleware[b].priority) {
          return 1;
        } else {
          return -1;
        }
      });
    }
 
    /**
     * Broadcast a message in a room.
     *
     * @param connection  Source connection.
     * @param room        Room here the message need to be broadcast.
     * @param message     Message to broadcast.
     * @param callback    Callback function.
     */
 
  }, {
    key: 'broadcast',
    value: function broadcast(connection, room, message, callback) {
      var self = this;
 
      // check if the room are present
      Iif (!room || room.length === 0 || message === null || message.length === 0) {
        if (typeof callback === 'function') {
          process.nextTick(function () {
            return callback(self.api.config.errors.connectionRoomAndMessage(connection));
          });
        }
      } else Eif (connection.rooms === undefined || connection.rooms.indexOf(room) > -1) {
        // set id zero for default if there no one present
        if (connection.id === undefined) {
          connection.id = 0;
        }
 
        // create a new payload
        var payload = {
          messageType: 'chat',
          serverToken: self.api.config.general.serverToken,
          serverId: self.api.id,
          message: message,
          sentAt: new Date().getTime(),
          connection: {
            id: connection.id,
            room: room
          }
        };
 
        // generate the message payload
        var messagePayload = self._generateMessagePayload(payload);
 
        // handle callbacks
        self._handleCallbacks(connection, messagePayload.room, 'onSayReceive', messagePayload, function (error, newPayload) {
          // if an error occurs execute the callback and send the error with him
          Iif (error) {
            if (typeof callback === 'function') {
              process.nextTick(function () {
                callback(error);
              });
            }
            return;
          }
 
          // create the payload to send
          var payloadToSend = {
            messageType: 'chat',
            serverToken: self.api.config.general.serverToken,
            serverId: self.api.id,
            message: newPayload.message,
            sentAt: newPayload.sentAt,
            connection: {
              id: newPayload.from,
              room: newPayload.room
            }
          };
 
          // send the payload to redis
          self.api.redis.publish(payloadToSend);
 
          // execute the callback
          Eif (typeof callback === 'function') {
            process.nextTick(function () {
              callback(null);
            });
          }
        });
      } else {
        if (typeof callback === 'function') {
          process.nextTick(function () {
            callback(self.api.config.errors.connectionNotInRoom(connection, room));
          });
        }
      }
    }
 
    /**
     * Process an incoming message.
     *
     * @param message Incoming message to be processed.
     */
 
  }, {
    key: 'incomingMessage',
    value: function incomingMessage(message) {
      var self = this;
 
      // generate the message payload
      var messagePayload = self._generateMessagePayload(message);
 
      // iterate all connection
      for (var i in self.api.connections.connections) {
        self._incomingMessagePerConnection(self.api.connections.connections[i], messagePayload);
      }
    }
 
    /**
     * List rooms.
     *
     * @param callback
     */
 
  }, {
    key: 'list',
    value: function list(callback) {
      var self = this;
 
      self.api.redis.clients.client.smembers(self.api.chatRoom.keys.rooms, function (error, rooms) {
        if (typeof callback === 'function') {
          callback(error, rooms);
        }
      });
    }
 
    /**
     * Create a new room.
     *
     * @param room      Name of the room to be created.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'add',
    value: function add(room, callback) {
      var self = this;
 
      // check if the room already exists
      self.exists(room, function (err, found) {
        // if the room already exists return an error
        if (found === true) {
          Iif (typeof callback === 'function') {
            callback(self.api.config.errors.connectionRoomExists(room), null);
          }
          return;
        }
 
        // create a new room
        self.api.redis.clients.client.sadd(self.keys.rooms, room, function (err, count) {
          Iif (typeof callback === 'function') {
            callback(err, count);
          }
        });
      });
    }
 
    /**
     * Destroy a room.
     *
     * @param room      Room to be destroyed.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'destroy',
    value: function destroy(room, callback) {
      var self = this;
 
      // check if the room exists
      self.exists(room, function (error, found) {
        // return an error if the room not exists
        if (found === false) {
          if (typeof callback === 'function') {
            callback(self.api.config.errors.connectionRoomNotExist(room), null);
          }
          return;
        }
 
        // broadcast the room destruction
        self.broadcast({}, room, self.api.config.errors.connectionRoomHasBeenDeleted(room), function () {
          // get all room members
          self.api.redis.clients.client.hgetall(self.keys.members + room, function (error, memberHash) {
            // remove each member from the room
            for (var id in memberHash) {
              self.removeMember(id, room);
            }
 
            // delete de room on redis server
            self.api.redis.clients.client.srem(self.keys.rooms, room, function () {
              if (typeof callback === 'function') {
                callback();
              }
            });
          });
        });
      });
    }
 
    /**
     * Check if the given room exists.
     *
     * @param room      Name of the room.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'exists',
    value: function exists(room, callback) {
      var self = this;
 
      // make a call to the redis server to check if the room exists
      self.api.redis.clients.client.sismember(self.keys.rooms, room, function (err, bool) {
        var found = false;
 
        if (bool === 1 || bool === true) {
          found = true;
        }
 
        // execute the callback
        Eif (typeof callback === 'function') {
          callback(err, found);
        }
      });
    }
 
    /**
     * Get the status of a room.
     *
     * @param room      Name of the room to check.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'roomStatus',
    value: function roomStatus(room, callback) {
      var self = this;
 
      // we need a room to check their status
      Iif (room === undefined || room === null) {
        if (typeof callback === 'function') {
          callback(self.api.config.errors.connectionRoomRequired(), null);
        }
        return;
      }
 
      // check if the room exists
      self.exists(room, function (err, found) {
        // the room need exists
        Iif (found !== true) {
          if (typeof callback === 'function') {
            callback(self.api.config.errors.connectionRoomNotExist(room), null);
          }
          return;
        }
 
        // generate the key
        var key = self.keys.members + room;
 
        // get all channel members
        self.api.redis.clients.client.hgetall(key, function (error, members) {
          var cleanedMembers = {};
          var count = 0;
 
          // iterate all members and add them to the list of members
          for (var id in members) {
            var data = JSON.parse(members[id]);
            cleanedMembers[id] = self._sanitizeMemberDetails(data);
            count++;
          }
 
          // execute the callback
          callback(null, {
            room: room,
            members: cleanedMembers,
            membersCount: count
          });
        });
      });
    }
 
    /**
     * Add a new member to a room.
     *
     * @param connectionId  Connection ID.
     * @param room          Room name where the client must be added.
     * @param callback      Callback function.
     */
 
  }, {
    key: 'addMember',
    value: function addMember(connectionId, room, callback) {
      var self = this;
 
      // if the connection not exists create a new one in every stellar instance and return
      Iif (!self.api.connections.connections[connectionId]) {
        self.api.redis.doCluster('api.chatRoom.addMember', [connectionId, room], connectionId, callback);
        return;
      }
 
      // get connection object
      var connection = self.api.connections.connections[connectionId];
 
      // verifies that the connection is already within the room, if yes return now
      if (connection.rooms.indexOf(room) > -1) {
        Eif (typeof callback === 'function') {
          callback(self.api.config.errors.connectionAlreadyInRoom(connection, room), false);
        }
        return;
      }
 
      // check if the room exists
      self.exists(room, function (error, found) {
        Iif (found !== true) {
          if (typeof callback === 'function') {
            callback(self.api.config.errors.connectionRoomNotExist(room), false);
          }
          return;
        }
 
        self._handleCallbacks(connection, room, 'join', null, function (error) {
          // if exists an error, execute the callback and return
          Iif (error) {
            return callback(error, false);
          }
 
          // generate the member details
          var memberDetails = self._generateMemberDetails(connection);
 
          self.api.redis.clients.client.hset(self.keys.members + room, connection.id, JSON.stringify(memberDetails), function () {
            connection.rooms.push(room);
            Eif (typeof callback === 'function') {
              callback(null, true);
            }
          });
        });
      });
    }
 
    /**
     * Remove a client from a chat room.
     *
     * @param connectionId    Client connection object.
     * @param room            Room name.
     * @param callback        Callback.
     */
 
  }, {
    key: 'removeMember',
    value: function removeMember(connectionId, room, callback) {
      var self = this;
 
      // if the connection does not exists on the connections array perform a remove
      // member on the cluster
      Iif (self.api.connections.connections[connectionId] === undefined) {
        self.api.redis.doCluster('api.chatRoom.removeMember', [connectionId, room], connectionId, callback);
        return;
      }
 
      var connection = self.api.connections.connections[connectionId];
 
      // check if the client is connected with the room
      if (connection.rooms.indexOf(room) < 0) {
        Eif (typeof callback === 'function') {
          callback(self.api.config.errors.connectionNotInRoom(connection, room), false);
        }
        return;
      }
 
      // check if the room exists
      self.exists(room, function (error, found) {
        // if the room has not been found returned an error
        Iif (found === false) {
          if (typeof callback === 'function') {
            callback(self.api.config.errors.connectionRoomNotExist(room), false);
          }
          return;
        }
 
        // passes the response by the middleware
        self._handleCallbacks(connection, room, 'leave', null, function (error) {
          // execute the callback and return the error
          Iif (error) {
            return callback(error, false);
          }
 
          // remove the user
          self.api.redis.clients.client.hdel(self.keys.members + room, connection.id, function () {
            // get the room index
            var index = connection.rooms.indexOf(room);
 
            // remove room from the rooms array
            Eif (index > -1) {
              connection.rooms.splice(index, 1);
            }
 
            // execute the callback
            Eif (typeof callback === 'function') {
              callback(null, true);
            }
          });
        });
      });
    }
 
    // --------------------------------------------------------------------------------------------------------- [Private]
 
    /**
     * Generate a new object with member details.
     *
     * @param connection  Connection object.
     * @returns {{id: *, joinedAt: number, host: *}}
     * @private
     */
 
  }, {
    key: '_generateMemberDetails',
    value: function _generateMemberDetails(connection) {
      var self = this;
 
      return {
        id: connection.id,
        joinedAt: new Date().getTime(),
        host: self.api.id
      };
    }
 
    /**
     * Generate a new message payload.
     *
     * @param message   Base message.
     * @returns {{message: *, room: *, from: *, context: string, sendAt: *}}
     * @private
     */
 
  }, {
    key: '_generateMessagePayload',
    value: function _generateMessagePayload(message) {
      return {
        message: message.message,
        room: message.connection.room,
        from: message.connection.id,
        context: 'user',
        sentAt: message.sentAt
      };
    }
 
    /**
     * Handle the redis callbacks.
     *
     * This apply all global middleware for each callback response.
     *
     * @param connection        Connection object.
     * @param room              Room name.
     * @param direction         Message direction.
     * @param messagePayload    Message payload.
     * @param callback          Callback function.
     * @private
     */
 
  }, {
    key: '_handleCallbacks',
    value: function _handleCallbacks(connection, room, direction, messagePayload, callback) {
      var self = this;
 
      var jobs = [];
      var newMessagePayload = void 0;
 
      // if the message payload are defined create a clone
      if (messagePayload) {
        newMessagePayload = _utils2.default.objClone(messagePayload);
      }
 
      // apply global middleware
      self.globalMiddleware.forEach(function (name) {
        // get middleware object
        var m = self.middleware[name];
 
        // the middleware should be a function
        if (typeof m[direction] !== 'function') {
          return;
        }
 
        // push a new job to the queue
        jobs.push(function (callback) {
          if (messagePayload) {
            m[direction](connection, room, newMessagePayload, function (error, data) {
              if (data) {
                newMessagePayload = data;
              }
              callback(error, data);
            });
            return;
          }
 
          // execute the middleware without the payload
          m[direction](connection, room, callback);
        });
      });
 
      // execute all middleware
      _async2.default.series(jobs, function (error, data) {
        while (data.length > 0) {
          var thisData = data.shift();
 
          // change the new message object to the next middleware use it
          if (thisData) {
            newMessagePayload = thisData;
          }
        }
 
        // execute the next middleware
        callback(error, newMessagePayload);
      });
    }
 
    /**
     * Sanitize member details.
     *
     * @param memberData                  Member details to be sanitized.
     * @returns {{id: *, joinedAt: *}}    Sanitized
     * @private
     */
 
  }, {
    key: '_sanitizeMemberDetails',
    value: function _sanitizeMemberDetails(memberData) {
      return {
        id: memberData.id,
        joinedAt: memberData.joinedAt
      };
    }
 
    /**
     * Process a incoming connection for a connection object.
     *
     * @param connection      Connection object.
     * @param messagePayload  Message payload to be sent.
     * @private
     */
 
  }, {
    key: '_incomingMessagePerConnection',
    value: function _incomingMessagePerConnection(connection, messagePayload) {
      var self = this;
 
      // check if the connection can chat
      Iif (connection.canChat !== true) {
        return;
      }
 
      // check if the connection made part of the room
      if (connection.rooms.indexOf(messagePayload.room) < 0) {
        return;
      }
 
      // apply the middleware
      self._handleCallbacks(connection, messagePayload.room, 'say', messagePayload, function (err, newMessagePayload) {
        Eif (!err) {
          connection.sendMessage(newMessagePayload, 'say');
        }
      });
    }
  }]);
 
  return ChatRooms;
}();
 
/**
 * Initializer.
 */
 
 
var _class = function () {
  function _class() {
    _classCallCheck(this, _class);
 
    this.loadPriority = 520;
    this.startPriority = 200;
  }
 
  /**
   * Initializer load priority.
   *
   * @type {number}
   */
 
 
  /**
   * Initializer start priority.
   *
   * @type {number}
   */
 
 
  _createClass(_class, [{
    key: 'load',
 
 
    /**
     * Initializer loading function.
     *
     * @param api   API reference.
     * @param next  Callback.
     */
    value: function load(api, next) {
      // put the chat room interface available to all system
      api.chatRoom = new ChatRooms(api);
 
      // end the initializer loading
      next();
    }
 
    /**
     * Initializer starting function.
     *
     * @param api   API reference.
     * @param next  Callback.
     */
 
  }, {
    key: 'start',
    value: function start(api, next) {
      // subscribe new chat messages on the redis server
      api.redis.subscriptionHandlers['chat'] = function (message) {
        api.chatRoom.incomingMessage(message);
      };
 
      // check if we need to create some starting chat rooms
      Eif (api.config.general.startingChatRooms) {
        for (var room in api.config.general.startingChatRooms) {
          api.log('ensuring the existence of the chatRoom: ' + room);
          api.chatRoom.add(room);
        }
      }
 
      // end the initializer starting
      next();
    }
  }]);
 
  return _class;
}();
 
exports.default = _class;
//# sourceMappingURL=chatRooms.js.map