all files / dist/satellites/ connection.js

77.67% Statements 160/206
59.26% Branches 80/135
74.29% Functions 26/35
76.72% Lines 145/189
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          12×         106×                                                                                                                                                                                                                                                                                                                                       88×   88×   88×   88× 88×     88×     88×                                           88×   88× 60×     28×       88×   88× 176×     176×     88× 176×             176×       88×                     88× 704× 84×   704× 532×       88×                         28×                                                                       88× 88×         62×     62×     62×         62× 28×           62×   62× 58×     58× 58×         62×     62×                                                         315×   315×     315× 315×   315×         315×       315×   296×   296× 293×             290×       289×     288×   287×                 287× 66×   66× 66× 66×     221× 92× 92× 92× 92×     129×                   122× 117×                         117× 117×                         19× 19×                                                                              
'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 _nodeUuid = require('node-uuid');
 
var _nodeUuid2 = _interopRequireDefault(_nodeUuid);
 
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"); } }
 
/**
 * Create a clean connection.
 *
 * @param connection  Connection object.
 * @returns {{}}      New clean connection object.
 */
var cleanConnection = function cleanConnection(connection) {
  var clean = {};
 
  for (var i in connection) {
    if (i !== 'rawConnection') {
      clean[i] = connection[i];
    }
  }
 
  return clean;
};
 
var Connections = function () {
 
  /**
   * Create a new class instance.
   *
   * @param api   API object reference.
   */
 
 
  /**
   * Array with the allowed verbs.
   *
   * @type {string[]}
   */
 
 
  /**
   * Hash with all registered middleware.
   *
   * @type {{}}
   */
 
  function Connections(api) {
    _classCallCheck(this, Connections);
 
    this.middleware = {};
    this.globalMiddleware = [];
    this.allowedVerbs = ['quit', 'exit', 'paramAdd', 'paramDelete', 'paramView', 'paramsView', 'paramsDelete', 'roomAdd', 'roomLeave', 'roomView', 'detailsView', 'say'];
    this.connections = {};
    this.api = api;
  }
 
  /**
   * Add a new middleware.
   *
   * @param data  Middleware to be added.
   */
 
 
  /**
   * Hash with the active connections.
   *
   * @type {{}}
   */
 
 
  /**
   * Array with global middleware.
   *
   * @type {Array}
   */
 
 
  /**
   * API reference object.
   */
 
 
  _createClass(Connections, [{
    key: 'addMiddleware',
    value: function addMiddleware(data) {
      var self = this;
 
      // middleware require a name
      Iif (!data.name) {
        throw new Error('middleware.name is required');
      }
 
      // if there is no defined priority use the default
      Eif (!data.priority) {
        data.priority = self.api.config.general.defaultMiddlewarePriority;
      }
 
      // ensure the priority is a number
      data.priority = Number(data.priority);
 
      // save the new middleware
      self.middleware[data.name] = data;
 
      // push the new middleware to the global list
      self.globalMiddleware.push(data.name);
 
      // sort the global middleware array
      self.globalMiddleware.sort(function (a, b) {
        if (self.middleware[a].priority > self.middleware[b].priority) {
          return 1;
        }
 
        return -1;
      });
    }
  }, {
    key: 'apply',
    value: function apply(connectionId, method, args, callback) {
      var self = this;
 
      if (args === undefined && callback === undefined && typeof method === 'function') {
        callback = method;
        args = null;
        method = null;
      }
 
      self.api.redis.doCluster('api.connections.applyCatch', [connectionId, method, args], connectionId, callback);
    }
  }, {
    key: 'applyCatch',
    value: function applyCatch(connectionId, method, args, callback) {
      var self = this;
 
      var connection = self.api.connections.connections[connectionId];
      if (method && args) {
        if (method === 'sendMessage' || method === 'sendFile') {
          connection[method](args);
        } else {
          connection[method].apply(connection, args);
        }
      }
 
      if (typeof callback === 'function') {
        process.nextTick(function () {
          callback(cleanConnection(connection));
        });
      }
    }
  }]);
 
  return Connections;
}();
 
/**
 * Class who represents an active connection.
 */
 
 
var Connection = function () {
 
  /**
   * Create a new connection object.
   *
   * The data object needs to have the follow properties:
   *  - type
   *  - remotePort
   *  - remoteIP
   *  - rawConnection
   *
   * @param api Stellar API reference
   * @param data hash map
   */
 
 
  /**
   * Api reference.
   */
 
 
  /**
   * Unique client identifier.
   */
 
 
  /**
   * Timestamp of the connection.
   */
 
  function Connection(api, data) {
    _classCallCheck(this, Connection);
 
    this.rooms = [];
 
    var self = this;
 
    self.api = api;
    self._setup(data);
 
    // save this connection on the connection manager
    api.connections.connections[self.id] = self;
 
    // execute the middleware
    self.api.connections.globalMiddleware.forEach(function (middlewareName) {
      if (typeof self.api.connections.middleware[middlewareName].create === 'function') {
        self.api.connections.middleware[middlewareName].create(self);
      }
    });
  }
 
  /**
   * Initialize the connection object.
   *
   * @param data
   * @private
   */
 
 
  /**
   * Rooms which the client belongs.
   *
   * @type {Array}
   */
 
 
  _createClass(Connection, [{
    key: '_setup',
    value: function _setup(data) {
      var self = this;
 
      if (data.id) {
        self.id = data.id;
      } else {
        // generate an unique ID for this connection
        self.id = self._generateID();
      }
 
      // set the connection timestamp
      self.connectedAt = new Date().getTime();
 
      ['type', 'rawConnection'].forEach(function (req) {
        Iif (data[req] === null || data[req] === undefined) {
          throw new Error(req + ' is required to create a new connection object');
        }
        self[req] = data[req];
      });
 
      ['remotePort', 'remoteIP'].forEach(function (req) {
        Iif (data[req] === null || data[req] === undefined) {
          if (self.api.config.general.enforceConnectionProperties === true) {
            throw new Error(req + ' is required to create a new connection object');
          } else {
            data[req] = 0; // could be a random uuid as well?
          }
        }
        self[req] = data[req];
      });
 
      // set connection defaults
      var connectionDefaults = {
        error: null,
        params: {},
        rooms: [],
        fingerprint: null,
        pendingActions: 0,
        totalActions: 0,
        messageCount: 0,
        canChat: false
      };
 
      for (var i in connectionDefaults) {
        if (self[i] === undefined && data[i] !== undefined) {
          self[i] = data[i];
        }
        if (self[i] === undefined) {
          self[i] = connectionDefaults[i];
        }
      }
 
      self.api.i18n.invokeConnectionLocale(self);
    }
 
    /**
     * Generate an unique identifier for this connection.
     *
     * @returns {*}
     * @private
     */
 
  }, {
    key: '_generateID',
    value: function _generateID() {
      return _nodeUuid2.default.v4();
    }
 
    /**
     * Send a message to this connection.
     *
     * @param message
     */
 
  }, {
    key: 'sendMessage',
    value: function sendMessage(message) {
      throw new Error('I should be replaced with a connection-specific method [' + message + ']');
    }
 
    /**
     * Send a file to this connection.
     *
     * @param path
     */
 
  }, {
    key: 'sendFile',
    value: function sendFile(path) {
      throw new Error('I should be replaced with a connection-specific method [' + path + ']');
    }
 
    /**
     * Localize a message.
     *
     * @param message   Message to be localized.
     */
 
  }, {
    key: 'localize',
    value: function localize(message) {
      var self = this;
      return self.api.i18n.localize(message, self);
    }
  }, {
    key: 'destroy',
    value: function destroy(callback) {
      var self = this;
 
      // set connection as destroyed
      self.destroyed = true;
 
      // execute the destroy middleware
      self.api.connections.globalMiddleware.forEach(function (middlewareName) {
        Eif (typeof self.api.connections.middleware[middlewareName].destroy === 'function') {
          self.api.connections.middleware[middlewareName].destroy(self);
        }
      });
 
      // remove the connection from all rooms
      if (self.canChat === true) {
        self.rooms.forEach(function (room) {
          return self.api.chatRoom.removeMember(self.id, room);
        });
      }
 
      // get server instance
      var server = self.api.servers.servers[self.type];
 
      if (server) {
        if (server.attributes.logExits === true) {
          server.log('connection closed', 'info', { to: self.remoteIP });
        }
 
        Eif (typeof server.goodbye === 'function') {
          server.goodbye(self);
        }
      }
 
      // remove this connection from the connections array
      delete self.api.connections.connections[self.id];
 
      // execute the callback function
      if (typeof callback === 'function') {
        callback();
      }
    }
 
    /**
     * Set a new connection attribute.
     *
     * @param key
     * @param value
     */
 
  }, {
    key: 'set',
    value: function set(key, value) {
      var self = this;
      self[key] = value;
    }
 
    /**
     * Execute the right operation for the given verb.
     *
     * @param verb      Verb to be executed.
     * @param words     Words are optional.
     * @param callback  Callback function.
     */
 
  }, {
    key: 'verbs',
    value: function verbs(verb, words, callback) {
      var self = this;
 
      var key = void 0,
          value = void 0,
          room = void 0;
      var server = self.api.servers.servers[self.type];
      var allowedVerbs = server.attributes.verbs;
 
      Iif (typeof words === 'function' && !callback) {
        callback = words;
        words = [];
      }
 
      Iif (!(words instanceof Array)) {
        words = [words];
      }
 
      if (server && allowedVerbs.indexOf(verb) >= 0) {
        // log verb message
        server.log('verb', 'debug', { verb: verb, to: self.remoteIP, params: JSON.stringify(words) });
 
        if (verb === 'quit' || verb === 'exit') {
          server.goodbye(self);
        } else if (verb === 'paramAdd') {
          key = words[0];
          value = words[1];
 
          Eif (words[0] && words[0].indexOf('=') >= 0) {
            var parts = words[0].split('=');
            key = parts[0];
            value = parts[1];
          }
 
          self.params[key] = value;
 
          // execute the callback function
          Eif (typeof callback === 'function') {
            callback(null, null);
          }
        } else if (verb === 'paramDelete') {
          key = words[0];
          delete self.params[key];
 
          // execute the callback function
          Eif (typeof callback === 'function') {
            callback(null, null);
          }
        } else if (verb === 'paramView') {
          key = words[0];
 
          Eif (typeof callback === 'function') {
            callback(null, self.params[key]);
          }
        } else if (verb === 'paramsView') {
          Eif (typeof callback === 'function') {
            callback(null, self.params);
          }
        } else Iif (verb === 'paramsDelete') {
          // delete all params
          for (var i in self.params) {
            delete self.params[i];
          }
 
          if (typeof callback === 'function') {
            callback(null, null);
          }
        } else if (verb === 'roomAdd') {
          room = words[0];
 
          self.api.chatRoom.addMember(self.id, room, function (error, didHappen) {
            Eif (typeof callback === 'function') {
              callback(error, didHappen);
            }
          });
        } else if (verb === 'roomLeave') {
          room = words[0];
          self.api.chatRoom.removeMember(self.id, room, function (error, didHappen) {
            Eif (typeof callback === 'function') {
              callback(error, didHappen);
            }
          });
        } else if (verb === 'roomView') {
          // get requested room name
          room = words[0];
 
          Eif (self.rooms.indexOf(room) > -1) {
            self.api.chatRoom.roomStatus(room, function (error, roomStatus) {
              Eif (typeof callback === 'function') {
                callback(error, roomStatus);
              }
            });
          } else {
            if (typeof callback === 'function') {
              callback('not member of room ' + room);
            }
          }
        } else if (verb === 'detailsView') {
          var details = {
            id: self.id,
            fingerprint: self.fingerprint,
            remoteIP: self.remoteIP,
            remotePort: self.remotePort,
            params: self.params,
            connectedAt: self.connectedAt,
            rooms: self.rooms,
            totalActions: self.totalActions,
            pendingActions: self.pendingActions
          };
 
          // execute the callback function
          Eif (typeof callback === 'function') {
            callback(null, details);
          }
        } else Eif (verb === 'say') {
          // get the room name
          room = words.shift();
 
          // broadcast the message on the requested room
          self.api.chatRoom.broadcast(self, room, words.join(' '), function (error) {
            Eif (typeof callback === 'function') {
              callback(error);
            }
          });
        } else {
          if (typeof callback === 'function') {
            callback(self.api.config.errors.verbNotFound(self, verb), null);
          }
        }
      } else {
        Eif (typeof callback === 'function') {
          callback(self.api.config.errors.verbNotAllowed(self, verb), null);
        }
      }
    }
  }]);
 
  return Connection;
}();
 
var _class = function () {
  function _class() {
    _classCallCheck(this, _class);
 
    this.loadPriority = 400;
  }
 
  /**
   * Satellite load priority.
   *
   * @type {number}
   */
 
 
  _createClass(_class, [{
    key: 'load',
 
 
    /**
     * Satellite load function.
     *
     * @param api   API reference object.
     * @param next  Callback function.
     */
    value: function load(api, next) {
      // put Connections instance available to all platform
      api.connections = new Connections(api);
 
      // put the connection Class available to all platform
      api.connection = Connection;
 
      // finish the loading process
      next();
    }
  }]);
 
  return _class;
}();
 
exports.default = _class;
//# sourceMappingURL=connection.js.map