peer.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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;
  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 = id;
  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. if (!this.id) {
  84. // If we're just now getting an ID then we may have a queue.
  85. this.id = payload.id;
  86. }
  87. this.emit('open', this.id);
  88. this._processQueue();
  89. break;
  90. case 'ERROR':
  91. this.emit('error', payload.msg);
  92. util.log(payload.msg);
  93. break;
  94. case 'ID-TAKEN':
  95. this.emit('error', 'ID `'+this.id+'` is taken');
  96. this.destroy();
  97. break;
  98. case 'OFFER':
  99. var options = {
  100. metadata: payload.metadata,
  101. sdp: payload.sdp,
  102. config: this._options.config,
  103. };
  104. var connection = new DataConnection(this.id, peer, this._socket, options);
  105. this._attachConnectionListeners(connection);
  106. this.connections[peer] = connection;
  107. this.emit('connection', connection, payload.metadata);
  108. break;
  109. case 'EXPIRE':
  110. connection = this.connections[payload.expired];
  111. if (connection) {
  112. connection.close();
  113. connection.emit('Could not connect to peer ' + connection.peer);
  114. }
  115. break;
  116. case 'ANSWER':
  117. if (connection) {
  118. connection.handleSDP(payload.sdp, message.type);
  119. }
  120. break;
  121. case 'CANDIDATE':
  122. if (connection) {
  123. connection.handleCandidate(payload);
  124. }
  125. break;
  126. case 'LEAVE':
  127. if (connection) {
  128. connection.handleLeave();
  129. }
  130. break;
  131. case 'INVALID-KEY':
  132. this.emit('error', 'API KEY "' + this._key + '" is invalid');
  133. this.destroy();
  134. break;
  135. case 'PORT':
  136. //if (util.browserisms === 'Firefox') {
  137. // connection.handlePort(payload);
  138. // break;
  139. //}
  140. default:
  141. util.log('Unrecognized message type:', message.type);
  142. break;
  143. }
  144. };
  145. /** Process queued calls to connect. */
  146. Peer.prototype._processQueue = function() {
  147. while (this._queued.length > 0) {
  148. var conn = this._queued.pop();
  149. conn.initialize(this.id);
  150. }
  151. };
  152. Peer.prototype._cleanup = function() {
  153. var self = this;
  154. var peers = Object.keys(this.connections);
  155. for (var i = 0, ii = peers.length; i < ii; i++) {
  156. this.connections[peers[i]].close();
  157. }
  158. util.setZeroTimeout(function(){
  159. self._socket.close();
  160. });
  161. this.emit('close');
  162. };
  163. /** Listeners for DataConnection events. */
  164. Peer.prototype._attachConnectionListeners = function(connection) {
  165. var self = this;
  166. connection.on('close', function(peer) {
  167. if (self.connections[peer]) {
  168. delete self.connections[peer];
  169. }
  170. });
  171. };
  172. /** Exposed connect function for users. Will try to connect later if user
  173. * is waiting for an ID. */
  174. // TODO: pause XHR streaming when not in use and start again when this is
  175. // called.
  176. Peer.prototype.connect = function(peer, metadata, options) {
  177. options = util.extend({
  178. metadata: metadata,
  179. config: this._options.config,
  180. }, options);
  181. var connection = new DataConnection(this.id, peer, this._socket, options);
  182. this._attachConnectionListeners(connection);
  183. this.connections[peer] = connection;
  184. if (!this.id) {
  185. this._queued.push(connection);
  186. }
  187. return connection;
  188. };
  189. Peer.prototype.destroy = function() {
  190. this._cleanup();
  191. };
  192. exports.Peer = Peer;