peer.js 6.4 KB

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