peer.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. // States.
  46. this.destroyed = false;
  47. this.disconnected = false;
  48. // Connections for this peer.
  49. this.connections = {};
  50. // Connection managers.
  51. this.managers = {};
  52. // Queued connections to make.
  53. this._queued = [];
  54. // Init immediately if ID is given, otherwise ask server for ID
  55. if (id) {
  56. this.id = id;
  57. this._init();
  58. } else {
  59. this._getId();
  60. }
  61. };
  62. util.inherits(Peer, EventEmitter);
  63. Peer.prototype._getId = function(cb) {
  64. var self = this;
  65. try {
  66. var http = new XMLHttpRequest();
  67. var url = 'http://' + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  68. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  69. url += queryString;
  70. // If there's no ID we need to wait for one before trying to init socket.
  71. http.open('get', url, true);
  72. http.onreadystatechange = function() {
  73. if (http.readyState === 4) {
  74. self.id = http.responseText;
  75. self._init();
  76. }
  77. };
  78. http.send(null);
  79. } catch(e) {
  80. this._abort('server-error', 'Could not get an ID from the server');
  81. }
  82. };
  83. Peer.prototype._init = function() {
  84. var self = this;
  85. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  86. this._socket.on('message', function(data) {
  87. self._handleServerJSONMessage(data);
  88. });
  89. this._socket.on('error', function(error) {
  90. util.log(error);
  91. self._abort('socket-error', error);
  92. });
  93. this._socket.on('close', function() {
  94. var msg = 'Underlying socket has closed';
  95. util.log('error', msg);
  96. self._abort('socket-closed', msg);
  97. });
  98. this._socket.start();
  99. }
  100. Peer.prototype._handleServerJSONMessage = function(message) {
  101. var peer = message.src;
  102. var manager = this.managers[peer];
  103. var payload = message.payload;
  104. // Check that browsers match.
  105. if (!!payload && !!payload.browserisms && payload.browserisms !== util.browserisms) {
  106. this._warn('incompatible-peer', 'Peer ' + self.peer + ' is on an incompatible browser. Please clean up this peer.');
  107. }
  108. switch (message.type) {
  109. case 'OPEN':
  110. this._processQueue();
  111. this.emit('open', this.id);
  112. break;
  113. case 'ERROR':
  114. util.log(payload.msg);
  115. this._abort('server-error', payload.msg);
  116. break;
  117. case 'ID-TAKEN':
  118. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  119. break;
  120. case 'OFFER':
  121. var options = {
  122. sdp: payload.sdp,
  123. labels: payload.labels,
  124. config: this._options.config
  125. };
  126. var manager = this.managers[peer];
  127. if (!manager) {
  128. manager = new ConnectionManager(this.id, peer, this._socket, options);
  129. this._attachManagerListeners(manager);
  130. this.managers[peer] = manager;
  131. this.connections[peer] = {};
  132. }
  133. manager.update(options.labels);
  134. manager.handleSDP(payload.sdp, message.type);
  135. break;
  136. case 'EXPIRE':
  137. if (manager) {
  138. manager.close();
  139. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  140. }
  141. break;
  142. case 'ANSWER':
  143. if (manager) {
  144. manager.handleSDP(payload.sdp, message.type);
  145. }
  146. break;
  147. case 'CANDIDATE':
  148. if (manager) {
  149. manager.handleCandidate(payload);
  150. }
  151. break;
  152. case 'LEAVE':
  153. if (manager) {
  154. manager.handleLeave();
  155. }
  156. break;
  157. case 'INVALID-KEY':
  158. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  159. break;
  160. case 'PORT':
  161. // Firefoxism: exchanging ports.
  162. if (util.browserisms === 'Firefox' && manager) {
  163. manager.handlePort(payload);
  164. break;
  165. }
  166. default:
  167. util.log('Unrecognized message type:', message.type);
  168. break;
  169. }
  170. };
  171. /** Process queued calls to connect. */
  172. Peer.prototype._processQueue = function() {
  173. while (this._queued.length > 0) {
  174. var manager = this._queued.pop();
  175. manager.initialize(this.id, this._socket);
  176. }
  177. };
  178. /** Listeners for manager. */
  179. Peer.prototype._attachManagerListeners = function(manager) {
  180. var self = this;
  181. // Handle receiving a connection.
  182. manager.on('connection', function(connection) {
  183. self.connections[connection.peer][connection.label] = connection;
  184. self.emit('connection', connection);
  185. });
  186. // Handle a connection closing.
  187. manager.on('close', function() {
  188. if (!!self.managers[manager.peer]) {
  189. delete self.managers[manager.peer]
  190. }
  191. });
  192. manager.on('error', function(err) {
  193. self.emit('error', err);
  194. });
  195. };
  196. /** Destroys the Peer and emits an error message. */
  197. Peer.prototype._abort = function(type, message) {
  198. var err = new Error(message);
  199. err.type = type;
  200. this.destroy();
  201. this.emit('error', err);
  202. };
  203. /** Emits an error message that things may not work. */
  204. Peer.prototype._warn = function(type, message) {
  205. var err = new Error(message);
  206. err.type = type;
  207. this.emit('error', err);
  208. };
  209. Peer.prototype._cleanup = function() {
  210. var self = this;
  211. if (!!this.managers) {
  212. var peers = Object.keys(this.managers);
  213. for (var i = 0, ii = peers.length; i < ii; i++) {
  214. this.managers[peers[i]].close();
  215. }
  216. util.setZeroTimeout(function(){
  217. self.disconnect();
  218. });
  219. }
  220. this.emit('close');
  221. };
  222. /** Exposed connect function for users. Will try to connect later if user
  223. * is waiting for an ID. */
  224. Peer.prototype.connect = function(peer, options) {
  225. if (this.disconnected) {
  226. this._warn('peer-disconnected', 'This Peer has been disconnected from the server and');
  227. return;
  228. }
  229. options = util.extend({
  230. config: this._options.config
  231. }, options);
  232. options.originator = true;
  233. var manager = this.managers[peer];
  234. if (!manager) {
  235. manager = new ConnectionManager(this.id, peer, this._socket, options);
  236. this._attachManagerListeners(manager);
  237. this.managers[peer] = manager;
  238. this.connections[peer] = {};
  239. }
  240. var connectionInfo = manager.connect(options);
  241. if (!!connectionInfo) {
  242. this.connections[peer][connectionInfo[0]] = connectionInfo[1];
  243. }
  244. if (!this.id) {
  245. this._queued.push(manager);
  246. }
  247. return connectionInfo[1];
  248. };
  249. /**
  250. * Destroys the Peer: closes all active connections as well as the connection
  251. * to the server.
  252. * Warning: The peer can no longer create or accept connections after being
  253. * destroyed.
  254. */
  255. Peer.prototype.destroy = function() {
  256. if (!this.destroyed) {
  257. this._cleanup();
  258. this.destroyed = true;
  259. }
  260. };
  261. /**
  262. * Disconnects the Peer's connection to the PeerServer. Does not close any
  263. * active connections.
  264. * Warning: The peer can no longer create or accept connections after being
  265. * disconnected. It also cannot reconnect to the server.
  266. */
  267. Peer.prototype.disconnect = function() {
  268. if (!this.disconnected) {
  269. this._socket.close();
  270. this.disconnected = true;
  271. }
  272. };
  273. exports.Peer = Peer;