peer.js 6.1 KB

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