peer.js 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(options) {
  5. if (!(this instanceof Peer)) return new Peer(options);
  6. EventEmitter.call(this);
  7. options = util.extend({
  8. debug: false,
  9. host: '0.peerjs.com',
  10. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  11. port: 80
  12. }, options);
  13. this._options = options;
  14. util.debug = options.debug;
  15. // TODO: default should be the cloud server.
  16. this._server = options.host + ':' + options.port;
  17. // Ensure alphanumeric_-
  18. if (options.id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.id))
  19. throw new Error('Peer ID can only contain alphanumerics, "_", and "-".');
  20. if (options.apikey && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.apikey))
  21. throw new Error('API key can only contain alphanumerics, "_", and "-".');
  22. this._id = options.id;
  23. // Not used unless using cloud server.
  24. this._apikey = options.apikey;
  25. this._startSocket();
  26. // Connections for this peer.
  27. this.connections = {};
  28. // Queued connections to make.
  29. this._queued = [];
  30. };
  31. util.inherits(Peer, EventEmitter);
  32. Peer.prototype._startSocket = function() {
  33. var self = this;
  34. this._socket = new Socket(this._server, this._id, this._apikey);
  35. this._socket.on('message', function(data) {
  36. self._handleServerJSONMessage(data);
  37. });
  38. this._socket.on('open', function() {
  39. self._processQueue();
  40. });
  41. this._socket.on('unavailable', function(peer) {
  42. util.log('Destination peer not available.', peer);
  43. if (self.connections[peer])
  44. self.connections[peer].close();
  45. });
  46. this._socket.on('error', function(error) {
  47. util.log(error);
  48. });
  49. this._socket.start();
  50. }
  51. Peer.prototype._handleServerJSONMessage = function(message) {
  52. var peer = message.src;
  53. var connection = this.connections[peer];
  54. switch (message.type) {
  55. case 'ID':
  56. if (!this._id) {
  57. // If we're just now getting an ID then we may have a queue.
  58. this._id = message.id;
  59. this.emit('ready', this._id);
  60. this._processQueue();
  61. }
  62. break;
  63. case 'ERROR':
  64. this.emit('error', message.msg);
  65. util.log(message.msg);
  66. break;
  67. case 'OFFER':
  68. var options = {
  69. metadata: message.metadata,
  70. sdp: message.sdp,
  71. socketOpen: this._socketOpen,
  72. config: this._options.config,
  73. apikey: this._apikey
  74. };
  75. var self = this;
  76. var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, function(err, connection) {
  77. if (!err) {
  78. self.emit('connection', connection, message.metadata);
  79. }
  80. }, options);
  81. this._attachConnectionListeners(connection);
  82. this.connections[peer] = connection;
  83. break;
  84. case 'ANSWER':
  85. if (connection) connection.handleSDP(message);
  86. break;
  87. case 'CANDIDATE':
  88. if (connection) connection.handleCandidate(message);
  89. break;
  90. case 'LEAVE':
  91. if (connection) connection.handleLeave();
  92. break;
  93. case 'PORT':
  94. if (util.browserisms === 'Firefox') {
  95. connection.handlePort(message);
  96. break;
  97. }
  98. case 'DEFAULT':
  99. util.log('Unrecognized message type:', message.type);
  100. break;
  101. }
  102. };
  103. /** Process queued calls to connect. */
  104. Peer.prototype._processQueue = function() {
  105. while (this._queued.length > 0) {
  106. var cdata = this._queued.pop();
  107. this.connect.apply(this, cdata);
  108. }
  109. };
  110. Peer.prototype._cleanup = function() {
  111. for (var peer in this.connections) {
  112. if (this.connections.hasOwnProperty(peer)) {
  113. this.connections[peer].close();
  114. }
  115. }
  116. this._socket.close();
  117. };
  118. /** Listeners for DataConnection events. */
  119. Peer.prototype._attachConnectionListeners = function(connection) {
  120. var self = this;
  121. connection.on('close', function(peer) {
  122. if (self.connections[peer]) delete self.connections[peer];
  123. });
  124. };
  125. /** Exposed connect function for users. Will try to connect later if user
  126. * is waiting for an ID. */
  127. // TODO: pause XHR streaming when not in use and start again when this is
  128. // called.
  129. Peer.prototype.connect = function(peer, metadata, cb) {
  130. if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
  131. if (!this._id) {
  132. this._queued.push(Array.prototype.slice.apply(arguments));
  133. return;
  134. }
  135. var options = {
  136. metadata: metadata,
  137. socketOpen: this._socketOpen,
  138. config: this._options.config,
  139. apikey: this._apikey
  140. };
  141. var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, cb, options);
  142. this._attachConnectionListeners(connection);
  143. this.connections[peer] = connection;
  144. };
  145. Peer.prototype.destroy = function() {
  146. this._cleanup();
  147. };
  148. exports.Peer = Peer;