peer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  1. var util = require('./util');
  2. var EventEmitter = require('eventemitter3');
  3. var Socket = require('./socket');
  4. var MediaConnection = require('./mediaconnection');
  5. var DataConnection = require('./dataconnection');
  6. /**
  7. * A peer who can initiate connections with other peers.
  8. */
  9. function Peer(id, options) {
  10. if (!(this instanceof Peer)) return new Peer(id, options);
  11. EventEmitter.call(this);
  12. // Deal with overloading
  13. if (id && id.constructor == Object) {
  14. options = id;
  15. id = undefined;
  16. } else if (id) {
  17. // Ensure id is a string
  18. id = id.toString();
  19. }
  20. //
  21. // Configurize options
  22. options = util.extend({
  23. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  24. host: util.CLOUD_HOST,
  25. port: util.CLOUD_PORT,
  26. key: 'peerjs',
  27. path: '/',
  28. token: util.randomToken(),
  29. config: util.defaultConfig
  30. }, options);
  31. this.options = options;
  32. // Detect relative URL host.
  33. if (options.host === '/') {
  34. options.host = window.location.hostname;
  35. }
  36. // Set path correctly.
  37. if (options.path[0] !== '/') {
  38. options.path = '/' + options.path;
  39. }
  40. if (options.path[options.path.length - 1] !== '/') {
  41. options.path += '/';
  42. }
  43. // Set whether we use SSL to same as current host
  44. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  45. options.secure = util.isSecure();
  46. }
  47. // Set a custom log function if present
  48. if (options.logFunction) {
  49. util.setLogFunction(options.logFunction);
  50. }
  51. util.setLogLevel(options.debug);
  52. //
  53. // Sanity checks
  54. // Ensure WebRTC supported
  55. if (!util.supports.audioVideo && !util.supports.data ) {
  56. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  57. return;
  58. }
  59. // Ensure alphanumeric id
  60. if (!util.validateId(id)) {
  61. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  62. return;
  63. }
  64. // Ensure valid key
  65. if (!util.validateKey(options.key)) {
  66. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  67. return;
  68. }
  69. // Ensure not using unsecure cloud server on SSL page
  70. if (options.secure && options.host === '0.peerjs.com') {
  71. this._delayedAbort('ssl-unavailable',
  72. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  73. return;
  74. }
  75. //
  76. // States.
  77. this.destroyed = false; // Connections have been killed
  78. this.disconnected = false; // Connection to PeerServer killed but P2P connections still active
  79. this.open = false; // Sockets and such are not yet open.
  80. //
  81. // References
  82. this.connections = {}; // DataConnections for this peer.
  83. this._lostMessages = {}; // src => [list of messages]
  84. //
  85. // Start the server connection
  86. this._initializeServerConnection();
  87. if (id) {
  88. this._initialize(id);
  89. } else {
  90. this._retrieveId();
  91. }
  92. //
  93. }
  94. util.inherits(Peer, EventEmitter);
  95. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  96. // websockets.)
  97. Peer.prototype._initializeServerConnection = function() {
  98. var self = this;
  99. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key, this.options.wsport);
  100. this.socket.on('message', function(data) {
  101. self._handleMessage(data);
  102. });
  103. this.socket.on('error', function(error) {
  104. self._abort('socket-error', error);
  105. });
  106. this.socket.on('disconnected', function() {
  107. // If we haven't explicitly disconnected, emit error and disconnect.
  108. if (!self.disconnected) {
  109. self.emitError('network', 'Lost connection to server.');
  110. self.disconnect();
  111. }
  112. });
  113. this.socket.on('close', function() {
  114. // If we haven't explicitly disconnected, emit error.
  115. if (!self.disconnected) {
  116. self._abort('socket-closed', 'Underlying socket is already closed.');
  117. }
  118. });
  119. };
  120. /** Get a unique ID from the server via XHR. */
  121. Peer.prototype._retrieveId = function(cb) {
  122. var self = this;
  123. var http = new XMLHttpRequest();
  124. var protocol = this.options.secure ? 'https://' : 'http://';
  125. var url = protocol + this.options.host + ':' + this.options.port +
  126. this.options.path + this.options.key + '/id';
  127. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  128. url += queryString;
  129. // If there's no ID we need to wait for one before trying to init socket.
  130. http.open('get', url, true);
  131. http.onerror = function(e) {
  132. util.error('Error retrieving ID', e);
  133. var pathError = '';
  134. if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) {
  135. pathError = ' If you passed in a `path` to your self-hosted PeerServer, ' +
  136. 'you\'ll also need to pass in that same path when creating a new ' +
  137. 'Peer.';
  138. }
  139. self._abort('server-error', 'Could not get an ID from the server.' + pathError);
  140. };
  141. http.onreadystatechange = function() {
  142. if (http.readyState !== 4) {
  143. return;
  144. }
  145. if (http.status !== 200) {
  146. http.onerror();
  147. return;
  148. }
  149. self._initialize(http.responseText);
  150. };
  151. http.send(null);
  152. };
  153. /** Initialize a connection with the server. */
  154. Peer.prototype._initialize = function(id) {
  155. this.id = id;
  156. this.socket.start(this.id, this.options.token);
  157. };
  158. /** Handles messages from the server. */
  159. Peer.prototype._handleMessage = function(message) {
  160. var type = message.type;
  161. var payload = message.payload;
  162. var peer = message.src;
  163. var connection;
  164. switch (type) {
  165. case 'OPEN': // The connection to the server is open.
  166. this.emit('open', this.id);
  167. this.open = true;
  168. break;
  169. case 'ERROR': // Server error.
  170. this._abort('server-error', payload.msg);
  171. break;
  172. case 'ID-TAKEN': // The selected ID is taken.
  173. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  174. break;
  175. case 'INVALID-KEY': // The given API key cannot be found.
  176. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  177. break;
  178. //
  179. case 'LEAVE': // Another peer has closed its connection to this peer.
  180. util.log('Received leave message from', peer);
  181. this._cleanupPeer(peer);
  182. break;
  183. case 'EXPIRE': // The offer sent to a peer has expired without response.
  184. this.emitError('peer-unavailable', 'Could not connect to peer ' + peer);
  185. break;
  186. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  187. var connectionId = payload.connectionId;
  188. connection = this.getConnection(peer, connectionId);
  189. if (connection) {
  190. util.warn('Offer received for existing Connection ID:', connectionId);
  191. //connection.handleMessage(message);
  192. } else {
  193. // Create a new connection.
  194. if (payload.type === 'media') {
  195. connection = new MediaConnection(peer, this, {
  196. connectionId: connectionId,
  197. _payload: payload,
  198. metadata: payload.metadata
  199. });
  200. this._addConnection(peer, connection);
  201. this.emit('call', connection);
  202. } else if (payload.type === 'data') {
  203. connection = new DataConnection(peer, this, {
  204. connectionId: connectionId,
  205. _payload: payload,
  206. metadata: payload.metadata,
  207. label: payload.label,
  208. serialization: payload.serialization,
  209. reliable: payload.reliable
  210. });
  211. this._addConnection(peer, connection);
  212. this.emit('connection', connection);
  213. } else {
  214. util.warn('Received malformed connection type:', payload.type);
  215. return;
  216. }
  217. // Find messages.
  218. var messages = this._getMessages(connectionId);
  219. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  220. connection.handleMessage(messages[i]);
  221. }
  222. }
  223. break;
  224. default:
  225. if (!payload) {
  226. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  227. return;
  228. }
  229. var id = payload.connectionId;
  230. connection = this.getConnection(peer, id);
  231. if (connection && connection.pc) {
  232. // Pass it on.
  233. connection.handleMessage(message);
  234. } else if (id) {
  235. // Store for possible later use
  236. this._storeMessage(id, message);
  237. } else {
  238. util.warn('You received an unrecognized message:', message);
  239. }
  240. break;
  241. }
  242. };
  243. /** Stores messages without a set up connection, to be claimed later. */
  244. Peer.prototype._storeMessage = function(connectionId, message) {
  245. if (!this._lostMessages[connectionId]) {
  246. this._lostMessages[connectionId] = [];
  247. }
  248. this._lostMessages[connectionId].push(message);
  249. };
  250. /** Retrieve messages from lost message store */
  251. Peer.prototype._getMessages = function(connectionId) {
  252. var messages = this._lostMessages[connectionId];
  253. if (messages) {
  254. delete this._lostMessages[connectionId];
  255. return messages;
  256. } else {
  257. return [];
  258. }
  259. };
  260. /**
  261. * Returns a DataConnection to the specified peer. See documentation for a
  262. * complete list of options.
  263. */
  264. Peer.prototype.connect = function(peer, options) {
  265. if (this.disconnected) {
  266. util.warn('You cannot connect to a new Peer because you called ' +
  267. '.disconnect() on this Peer and ended your connection with the ' +
  268. 'server. You can create a new Peer to reconnect, or call reconnect ' +
  269. 'on this peer if you believe its ID to still be available.');
  270. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  271. return;
  272. }
  273. var connection = new DataConnection(peer, this, options);
  274. this._addConnection(peer, connection);
  275. return connection;
  276. };
  277. /**
  278. * Returns a MediaConnection to the specified peer. See documentation for a
  279. * complete list of options.
  280. */
  281. Peer.prototype.call = function(peer, stream, options) {
  282. if (this.disconnected) {
  283. util.warn('You cannot connect to a new Peer because you called ' +
  284. '.disconnect() on this Peer and ended your connection with the ' +
  285. 'server. You can create a new Peer to reconnect.');
  286. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  287. return;
  288. }
  289. if (!stream) {
  290. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  291. return;
  292. }
  293. options = options || {};
  294. options._stream = stream;
  295. var call = new MediaConnection(peer, this, options);
  296. this._addConnection(peer, call);
  297. return call;
  298. };
  299. /** Add a data/media connection to this peer. */
  300. Peer.prototype._addConnection = function(peer, connection) {
  301. if (!this.connections[peer]) {
  302. this.connections[peer] = [];
  303. }
  304. this.connections[peer].push(connection);
  305. };
  306. /** Retrieve a data/media connection for this peer. */
  307. Peer.prototype.getConnection = function(peer, id) {
  308. var connections = this.connections[peer];
  309. if (!connections) {
  310. return null;
  311. }
  312. for (var i = 0, ii = connections.length; i < ii; i++) {
  313. if (connections[i].id === id) {
  314. return connections[i];
  315. }
  316. }
  317. return null;
  318. };
  319. Peer.prototype._delayedAbort = function(type, message) {
  320. var self = this;
  321. util.setZeroTimeout(function(){
  322. self._abort(type, message);
  323. });
  324. };
  325. /**
  326. * Destroys the Peer and emits an error message.
  327. * The Peer is not destroyed if it's in a disconnected state, in which case
  328. * it retains its disconnected state and its existing connections.
  329. */
  330. Peer.prototype._abort = function(type, message) {
  331. util.error('Aborting!');
  332. if (!this._lastServerId) {
  333. this.destroy();
  334. } else {
  335. this.disconnect();
  336. }
  337. this.emitError(type, message);
  338. };
  339. /** Emits a typed error message. */
  340. Peer.prototype.emitError = function(type, err) {
  341. util.error('Error:', err);
  342. if (typeof err === 'string') {
  343. err = new Error(err);
  344. }
  345. err.type = type;
  346. this.emit('error', err);
  347. };
  348. /**
  349. * Destroys the Peer: closes all active connections as well as the connection
  350. * to the server.
  351. * Warning: The peer can no longer create or accept connections after being
  352. * destroyed.
  353. */
  354. Peer.prototype.destroy = function() {
  355. if (!this.destroyed) {
  356. this._cleanup();
  357. this.disconnect();
  358. this.destroyed = true;
  359. }
  360. };
  361. /** Disconnects every connection on this peer. */
  362. Peer.prototype._cleanup = function() {
  363. if (this.connections) {
  364. var peers = Object.keys(this.connections);
  365. for (var i = 0, ii = peers.length; i < ii; i++) {
  366. this._cleanupPeer(peers[i]);
  367. }
  368. }
  369. this.emit('close');
  370. };
  371. /** Closes all connections to this peer. */
  372. Peer.prototype._cleanupPeer = function(peer) {
  373. var connections = this.connections[peer];
  374. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  375. connections[j].close();
  376. }
  377. };
  378. /**
  379. * Disconnects the Peer's connection to the PeerServer. Does not close any
  380. * active connections.
  381. * Warning: The peer can no longer create or accept connections after being
  382. * disconnected. It also cannot reconnect to the server.
  383. */
  384. Peer.prototype.disconnect = function() {
  385. var self = this;
  386. util.setZeroTimeout(function(){
  387. if (!self.disconnected) {
  388. self.disconnected = true;
  389. self.open = false;
  390. if (self.socket) {
  391. self.socket.close();
  392. }
  393. self.emit('disconnected', self.id);
  394. self._lastServerId = self.id;
  395. self.id = null;
  396. }
  397. });
  398. };
  399. /** Attempts to reconnect with the same ID. */
  400. Peer.prototype.reconnect = function() {
  401. if (this.disconnected && !this.destroyed) {
  402. util.log('Attempting reconnection to server with ID ' + this._lastServerId);
  403. this.disconnected = false;
  404. this._initializeServerConnection();
  405. this._initialize(this._lastServerId);
  406. } else if (this.destroyed) {
  407. throw new Error('This peer cannot reconnect to the server. It has already been destroyed.');
  408. } else if (!this.disconnected && !this.open) {
  409. // Do nothing. We're still connecting the first time.
  410. util.error('In a hurry? We\'re still trying to make the initial connection!');
  411. } else {
  412. throw new Error('Peer ' + this.id + ' cannot reconnect because it is not disconnected from the server!');
  413. }
  414. };
  415. /**
  416. * Get a list of available peer IDs. If you're running your own server, you'll
  417. * want to set allow_discovery: true in the PeerServer options. If you're using
  418. * the cloud server, email team@peerjs.com to get the functionality enabled for
  419. * your key.
  420. */
  421. Peer.prototype.listAllPeers = function(cb) {
  422. cb = cb || function() {};
  423. var self = this;
  424. var http = new XMLHttpRequest();
  425. var protocol = this.options.secure ? 'https://' : 'http://';
  426. var url = protocol + this.options.host + ':' + this.options.port +
  427. this.options.path + this.options.key + '/peers';
  428. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  429. url += queryString;
  430. // If there's no ID we need to wait for one before trying to init socket.
  431. http.open('get', url, true);
  432. http.onerror = function(e) {
  433. self._abort('server-error', 'Could not get peers from the server.');
  434. cb([]);
  435. };
  436. http.onreadystatechange = function() {
  437. if (http.readyState !== 4) {
  438. return;
  439. }
  440. if (http.status === 401) {
  441. var helpfulError = '';
  442. if (self.options.host !== util.CLOUD_HOST) {
  443. helpfulError = 'It looks like you\'re using the cloud server. You can email ' +
  444. 'team@peerjs.com to enable peer listing for your API key.';
  445. } else {
  446. helpfulError = 'You need to enable `allow_discovery` on your self-hosted ' +
  447. 'PeerServer to use this feature.';
  448. }
  449. cb([]);
  450. throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError);
  451. } else if (http.status !== 200) {
  452. cb([]);
  453. } else {
  454. cb(JSON.parse(http.responseText));
  455. }
  456. };
  457. http.send(null);
  458. };
  459. module.exports = Peer;