peer.js 7.0 KB

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