Front end of the Slack clone application.

client.js 2.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var util = require('util'),
  2. net = require('net'),
  3. tls = require('tls'),
  4. url = require('url'),
  5. driver = require('websocket-driver'),
  6. API = require('./api'),
  7. Event = require('./api/event');
  8. var DEFAULT_PORTS = {'http:': 80, 'https:': 443, 'ws:':80, 'wss:': 443},
  9. SECURE_PROTOCOLS = ['https:', 'wss:'];
  10. var Client = function(_url, protocols, options) {
  11. options = options || {};
  12. this.url = _url;
  13. this._driver = driver.client(this.url, {maxLength: options.maxLength, protocols: protocols});
  14. ['open', 'error'].forEach(function(event) {
  15. this._driver.on(event, function() {
  16. self.headers = self._driver.headers;
  17. self.statusCode = self._driver.statusCode;
  18. });
  19. }, this);
  20. var proxy = options.proxy || {},
  21. endpoint = url.parse(proxy.origin || this.url),
  22. port = endpoint.port || DEFAULT_PORTS[endpoint.protocol],
  23. secure = SECURE_PROTOCOLS.indexOf(endpoint.protocol) >= 0,
  24. onConnect = function() { self._onConnect() },
  25. originTLS = options.tls || {},
  26. socketTLS = proxy.origin ? (proxy.tls || {}) : originTLS,
  27. self = this;
  28. originTLS.ca = originTLS.ca || options.ca;
  29. this._stream = secure
  30. ? tls.connect(port, endpoint.hostname, socketTLS, onConnect)
  31. : net.connect(port, endpoint.hostname, onConnect);
  32. if (proxy.origin) this._configureProxy(proxy, originTLS);
  33. API.call(this, options);
  34. };
  35. util.inherits(Client, API);
  36. Client.prototype._onConnect = function() {
  37. var worker = this._proxy || this._driver;
  38. worker.start();
  39. };
  40. Client.prototype._configureProxy = function(proxy, originTLS) {
  41. var uri = url.parse(this.url),
  42. secure = SECURE_PROTOCOLS.indexOf(uri.protocol) >= 0,
  43. self = this,
  44. name;
  45. this._proxy = this._driver.proxy(proxy.origin);
  46. if (proxy.headers) {
  47. for (name in proxy.headers) this._proxy.setHeader(name, proxy.headers[name]);
  48. }
  49. this._proxy.pipe(this._stream, {end: false});
  50. this._stream.pipe(this._proxy);
  51. this._proxy.on('connect', function() {
  52. if (secure) {
  53. var options = {socket: self._stream, servername: uri.hostname};
  54. for (name in originTLS) options[name] = originTLS[name];
  55. self._stream = tls.connect(options);
  56. self._configureStream();
  57. }
  58. self._driver.io.pipe(self._stream);
  59. self._stream.pipe(self._driver.io);
  60. self._driver.start();
  61. });
  62. this._proxy.on('error', function(error) {
  63. self._driver.emit('error', error);
  64. });
  65. };
  66. module.exports = Client;