peer.js 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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 manager = this.managers[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. sdp: payload.sdp,
  109. labels: payload.labels,
  110. config: this._options.config
  111. };
  112. var manager = this.managers[peer];
  113. if (!manager) {
  114. manager = new ConnectionManager(this.id, peer, this._socket, options);
  115. this._attachManagerListeners(manager);
  116. this.managers[peer] = manager;
  117. this.connections[peer] = {};
  118. }
  119. manager.update(options.labels);
  120. manager.handleSDP(payload.sdp, message.type);
  121. break;
  122. case 'EXPIRE':
  123. if (manager) {
  124. manager.close();
  125. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  126. }
  127. break;
  128. case 'ANSWER':
  129. if (manager) {
  130. manager.handleSDP(payload.sdp, message.type);
  131. }
  132. break;
  133. case 'CANDIDATE':
  134. if (manager) {
  135. manager.handleCandidate(payload);
  136. }
  137. break;
  138. case 'LEAVE':
  139. if (manager) {
  140. manager.handleLeave();
  141. }
  142. break;
  143. case 'INVALID-KEY':
  144. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  145. break;
  146. case 'PORT':
  147. //if (util.browserisms === 'Firefox') {
  148. // connection.handlePort(payload);
  149. // break;
  150. //}
  151. default:
  152. util.log('Unrecognized message type:', message.type);
  153. break;
  154. }
  155. };
  156. /** Process queued calls to connect. */
  157. Peer.prototype._processQueue = function() {
  158. while (this._queued.length > 0) {
  159. var manager = this._queued.pop();
  160. manager.initialize(this.id, this._socket);
  161. }
  162. };
  163. /** Listeners for manager. */
  164. Peer.prototype._attachManagerListeners = function(manager) {
  165. var self = this;
  166. // Handle receiving a connection.
  167. manager.on('connection', function(connection) {
  168. self.connections[connection.peer][connection.label] = connection;
  169. self.emit('connection', connection);
  170. });
  171. // Handle a connection closing.
  172. manager.on('close', function() {
  173. if (!!self.managers[manager.peer]) {
  174. delete self.managers[manager.peer]
  175. }
  176. });
  177. manager.on('error', function(err) {
  178. self.emit('error', err);
  179. });
  180. };
  181. /** Destroys the Peer and emits an error message. */
  182. Peer.prototype._abort = function(type, message) {
  183. var err = new Error(message);
  184. err.type = type;
  185. this.destroy();
  186. this.emit('error', err);
  187. };
  188. Peer.prototype._cleanup = function() {
  189. var self = this;
  190. if (!!this.managers) {
  191. var peers = Object.keys(this.managers);
  192. for (var i = 0, ii = peers.length; i < ii; i++) {
  193. this.managers[peers[i]].close();
  194. }
  195. util.setZeroTimeout(function(){
  196. self._socket.close();
  197. });
  198. }
  199. this.emit('close');
  200. };
  201. /** Exposed connect function for users. Will try to connect later if user
  202. * is waiting for an ID. */
  203. // TODO: pause XHR streaming when not in use and start again when this is
  204. // called.
  205. Peer.prototype.connect = function(peer, options) {
  206. if (this.destroyed) {
  207. this._abort('peer-destroyed', 'This Peer has been destroyed and is no longer able to make connections.');
  208. return;
  209. }
  210. options = util.extend({
  211. config: this._options.config,
  212. label: 'peerjs'
  213. }, options);
  214. var manager = this.managers[peer];
  215. if (!manager) {
  216. manager = new ConnectionManager(this.id, peer, this._socket, options);
  217. this._attachManagerListeners(manager);
  218. this.managers[peer] = manager;
  219. this.connections[peer] = {};
  220. }
  221. var connectionInfo = manager.connect(options.label);
  222. if (!!connectionInfo) {
  223. this.connections[peer][connectionInfo[0]] = connectionInfo[1];
  224. }
  225. if (!this.id) {
  226. this._queued.push(manager);
  227. }
  228. return connectionInfo[1];
  229. };
  230. Peer.prototype.destroy = function() {
  231. if (!this.destroyed) {
  232. this._cleanup();
  233. this.destroyed = true;
  234. }
  235. };
  236. exports.Peer = Peer;