peer.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(id, options) {
  5. if (id && id.constructor == Object) {
  6. options = id;
  7. id = undefined;
  8. }
  9. if (!(this instanceof Peer)) return new Peer(id, 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. var self = this;
  22. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  23. util.setZeroTimeout(function() {
  24. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  25. });
  26. return
  27. }
  28. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  29. util.setZeroTimeout(function() {
  30. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  31. });
  32. return
  33. }
  34. // Connections for this peer.
  35. this.connections = {};
  36. // Queued connections to make.
  37. this._queued = [];
  38. // Init immediately if ID is given, otherwise ask server for ID
  39. if (id) {
  40. this.id = id;
  41. this._init();
  42. } else {
  43. this._getId();
  44. }
  45. };
  46. util.inherits(Peer, EventEmitter);
  47. Peer.prototype._getId = function(cb) {
  48. var self = this;
  49. try {
  50. var http = new XMLHttpRequest();
  51. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  52. // If there's no ID we need to wait for one before trying to init socket.
  53. http.open('get', url, true);
  54. http.onreadystatechange = function() {
  55. if (http.readyState === 4) {
  56. self.id = http.responseText;
  57. self._init();
  58. }
  59. };
  60. http.send(null);
  61. } catch(e) {
  62. this._abort('server-error', 'Could not get an ID from the server');
  63. }
  64. };
  65. Peer.prototype._init = function() {
  66. var self = this;
  67. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  68. this._socket.on('message', function(data) {
  69. self._handleServerJSONMessage(data);
  70. });
  71. this._socket.on('error', function(error) {
  72. util.log(error);
  73. self._abort('socket-error', error);
  74. });
  75. this._socket.on('close', function() {
  76. var msg = 'Underlying socket has closed';
  77. util.log('error', msg);
  78. self._abort('socket-closed', msg);
  79. });
  80. this._socket.start();
  81. }
  82. Peer.prototype._handleServerJSONMessage = function(message) {
  83. var peer = message.src;
  84. var connection = this.connections[peer];
  85. var payload = message.payload;
  86. switch (message.type) {
  87. case 'OPEN':
  88. this._processQueue();
  89. this.emit('open', this.id);
  90. break;
  91. case 'ERROR':
  92. util.log(payload.msg);
  93. this._abort('server-error', payload.msg);
  94. break;
  95. case 'ID-TAKEN':
  96. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  97. break;
  98. case 'OFFER':
  99. var options = {
  100. metadata: payload.metadata,
  101. serialization: payload.serialization,
  102. sdp: payload.sdp,
  103. config: this._options.config
  104. };
  105. var connection = new DataConnection(this.id, peer, this._socket, options);
  106. this._attachConnectionListeners(connection);
  107. this.connections[peer] = connection;
  108. this.emit('connection', connection, payload.metadata);
  109. break;
  110. case 'EXPIRE':
  111. connection = this.connections[peer];
  112. if (connection) {
  113. connection.close();
  114. connection.emit('error', new Error('Could not connect to peer ' + connection.peer));
  115. }
  116. break;
  117. case 'ANSWER':
  118. if (connection) {
  119. connection.handleSDP(payload.sdp, message.type);
  120. }
  121. break;
  122. case 'CANDIDATE':
  123. if (connection) {
  124. connection.handleCandidate(payload);
  125. }
  126. break;
  127. case 'LEAVE':
  128. if (connection) {
  129. connection.handleLeave();
  130. }
  131. break;
  132. case 'INVALID-KEY':
  133. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  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, this._socket);
  150. }
  151. };
  152. /** Destroys the Peer and emits an error message. */
  153. Peer.prototype._abort = function(type, message) {
  154. var err = new Error(message);
  155. err.type = type;
  156. this.destroy();
  157. this.emit('error', err);
  158. };
  159. Peer.prototype._cleanup = function() {
  160. var self = this;
  161. if (!!this.connections) {
  162. var peers = Object.keys(this.connections);
  163. for (var i = 0, ii = peers.length; i < ii; i++) {
  164. this.connections[peers[i]].close();
  165. }
  166. util.setZeroTimeout(function(){
  167. self._socket.close();
  168. });
  169. }
  170. this.emit('close');
  171. };
  172. /** Listeners for DataConnection events. */
  173. Peer.prototype._attachConnectionListeners = function(connection) {
  174. var self = this;
  175. connection.on('close', function(peer) {
  176. if (self.connections[peer]) {
  177. delete self.connections[peer];
  178. }
  179. });
  180. };
  181. /** Exposed connect function for users. Will try to connect later if user
  182. * is waiting for an ID. */
  183. // TODO: pause XHR streaming when not in use and start again when this is
  184. // called.
  185. Peer.prototype.connect = function(peer, options) {
  186. if (this.destroyed) {
  187. this._abort('peer-destroyed', 'This Peer has been destroyed and is no longer able to make connections.');
  188. return;
  189. }
  190. options = util.extend({
  191. config: this._options.config
  192. }, options);
  193. var connection = new DataConnection(this.id, peer, this._socket, options);
  194. this._attachConnectionListeners(connection);
  195. this.connections[peer] = connection;
  196. if (!this.id) {
  197. this._queued.push(connection);
  198. }
  199. return connection;
  200. };
  201. Peer.prototype.destroy = function() {
  202. if (!this.destroyed) {
  203. this._cleanup();
  204. this.destroyed = true;
  205. }
  206. };
  207. exports.Peer = Peer;