peer.js 5.0 KB

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