peer.js 6.2 KB

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