peer.js 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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. port: 9000,
  15. key: 'peerjs',
  16. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  17. }, options);
  18. this._options = options;
  19. util.debug = options.debug;
  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. // Connections for this peer.
  28. this.connections = {};
  29. // Queued connections to make.
  30. this._queued = [];
  31. // Init immediately if ID is given, otherwise ask server for ID
  32. if (id) {
  33. this.id = id;
  34. this._init();
  35. } else {
  36. this._getId();
  37. }
  38. };
  39. util.inherits(Peer, EventEmitter);
  40. Peer.prototype._getId = function(cb) {
  41. var self = this;
  42. try {
  43. var http = new XMLHttpRequest();
  44. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  45. // If there's no ID we need to wait for one before trying to init socket.
  46. http.open('get', url, true);
  47. http.onreadystatechange = function() {
  48. if (http.readyState === 4) {
  49. self.id = http.responseText;
  50. self._init();
  51. }
  52. };
  53. http.send(null);
  54. } catch(e) {
  55. this.emit('error', 'Could not get an ID from the server');
  56. }
  57. };
  58. Peer.prototype._init = function() {
  59. var self = this;
  60. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  61. this._socket.on('message', function(data) {
  62. self._handleServerJSONMessage(data);
  63. });
  64. this._socket.on('error', function(error) {
  65. util.log(error);
  66. self.emit('error', error);
  67. self.destroy();
  68. });
  69. this._socket.on('close', function() {
  70. var msg = 'Underlying socket has closed';
  71. util.log('error', msg);
  72. self.emit('error', msg);
  73. self.destroy();
  74. });
  75. this._socket.start();
  76. }
  77. Peer.prototype._handleServerJSONMessage = function(message) {
  78. var peer = message.src;
  79. var connection = this.connections[peer];
  80. payload = message.payload;
  81. switch (message.type) {
  82. case 'OPEN':
  83. this._processQueue();
  84. this.emit('open', this.id);
  85. break;
  86. case 'ERROR':
  87. this.emit('error', payload.msg);
  88. util.log(payload.msg);
  89. break;
  90. case 'ID-TAKEN':
  91. this.emit('error', 'ID `'+this.id+'` is taken');
  92. this.destroy();
  93. break;
  94. case 'OFFER':
  95. var options = {
  96. metadata: payload.metadata,
  97. sdp: payload.sdp,
  98. config: this._options.config,
  99. };
  100. var connection = new DataConnection(this.id, peer, this._socket, options);
  101. this._attachConnectionListeners(connection);
  102. this.connections[peer] = connection;
  103. this.emit('connection', connection, payload.metadata);
  104. break;
  105. case 'EXPIRE':
  106. connection = this.connections[peer];
  107. if (connection) {
  108. connection.close();
  109. connection.emit('error', 'Could not connect to peer ' + connection.peer);
  110. }
  111. break;
  112. case 'ANSWER':
  113. if (connection) {
  114. connection.handleSDP(payload.sdp, message.type);
  115. }
  116. break;
  117. case 'CANDIDATE':
  118. if (connection) {
  119. connection.handleCandidate(payload);
  120. }
  121. break;
  122. case 'LEAVE':
  123. if (connection) {
  124. connection.handleLeave();
  125. }
  126. break;
  127. case 'INVALID-KEY':
  128. this.emit('error', 'API KEY "' + this._key + '" is invalid');
  129. this.destroy();
  130. break;
  131. case 'PORT':
  132. //if (util.browserisms === 'Firefox') {
  133. // connection.handlePort(payload);
  134. // break;
  135. //}
  136. default:
  137. util.log('Unrecognized message type:', message.type);
  138. break;
  139. }
  140. };
  141. /** Process queued calls to connect. */
  142. Peer.prototype._processQueue = function() {
  143. while (this._queued.length > 0) {
  144. var conn = this._queued.pop();
  145. conn.initialize(this.id, this._socket);
  146. }
  147. };
  148. Peer.prototype._cleanup = function() {
  149. var self = this;
  150. var peers = Object.keys(this.connections);
  151. for (var i = 0, ii = peers.length; i < ii; i++) {
  152. this.connections[peers[i]].close();
  153. }
  154. util.setZeroTimeout(function(){
  155. self._socket.close();
  156. });
  157. this.emit('close');
  158. };
  159. /** Listeners for DataConnection events. */
  160. Peer.prototype._attachConnectionListeners = function(connection) {
  161. var self = this;
  162. connection.on('close', function(peer) {
  163. if (self.connections[peer]) {
  164. delete self.connections[peer];
  165. }
  166. });
  167. };
  168. /** Exposed connect function for users. Will try to connect later if user
  169. * is waiting for an ID. */
  170. // TODO: pause XHR streaming when not in use and start again when this is
  171. // called.
  172. Peer.prototype.connect = function(peer, metadata, options) {
  173. options = util.extend({
  174. metadata: metadata,
  175. config: this._options.config,
  176. }, options);
  177. var connection = new DataConnection(this.id, peer, this._socket, options);
  178. this._attachConnectionListeners(connection);
  179. this.connections[peer] = connection;
  180. if (!this.id) {
  181. this._queued.push(connection);
  182. }
  183. return connection;
  184. };
  185. Peer.prototype.destroy = function() {
  186. this._cleanup();
  187. };
  188. exports.Peer = Peer;