peer.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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);
  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. switch (type) {
  164. case 'OPEN': // The connection to the server is open.
  165. this.emit('open', this.id);
  166. this.open = true;
  167. break;
  168. case 'ERROR': // Server error.
  169. this._abort('server-error', payload.msg);
  170. break;
  171. case 'ID-TAKEN': // The selected ID is taken.
  172. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  173. break;
  174. case 'INVALID-KEY': // The given API key cannot be found.
  175. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  176. break;
  177. //
  178. case 'LEAVE': // Another peer has closed its connection to this peer.
  179. util.log('Received leave message from', peer);
  180. this._cleanupPeer(peer);
  181. break;
  182. case 'EXPIRE': // The offer sent to a peer has expired without response.
  183. this.emitError('peer-unavailable', 'Could not connect to peer ' + peer);
  184. break;
  185. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  186. var connectionId = payload.connectionId;
  187. var connection = this.getConnection(peer, connectionId);
  188. if (connection) {
  189. util.warn('Offer received for existing Connection ID:', connectionId);
  190. //connection.handleMessage(message);
  191. } else {
  192. // Create a new connection.
  193. if (payload.type === 'media') {
  194. connection = new MediaConnection(peer, this, {
  195. connectionId: connectionId,
  196. _payload: payload,
  197. metadata: payload.metadata
  198. });
  199. this._addConnection(peer, connection);
  200. this.emit('call', connection);
  201. } else if (payload.type === 'data') {
  202. connection = new DataConnection(peer, this, {
  203. connectionId: connectionId,
  204. _payload: payload,
  205. metadata: payload.metadata,
  206. label: payload.label,
  207. serialization: payload.serialization,
  208. reliable: payload.reliable
  209. });
  210. this._addConnection(peer, connection);
  211. this.emit('connection', connection);
  212. } else {
  213. util.warn('Received malformed connection type:', payload.type);
  214. return;
  215. }
  216. // Find messages.
  217. var messages = this._getMessages(connectionId);
  218. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  219. connection.handleMessage(messages[i]);
  220. }
  221. }
  222. break;
  223. default:
  224. if (!payload) {
  225. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  226. return;
  227. }
  228. var id = payload.connectionId;
  229. connection = this.getConnection(peer, id);
  230. if (connection && connection.pc) {
  231. // Pass it on.
  232. connection.handleMessage(message);
  233. } else if (id) {
  234. // Store for possible later use
  235. this._storeMessage(id, message);
  236. } else {
  237. util.warn('You received an unrecognized message:', message);
  238. }
  239. break;
  240. }
  241. };
  242. /** Stores messages without a set up connection, to be claimed later. */
  243. Peer.prototype._storeMessage = function(connectionId, message) {
  244. if (!this._lostMessages[connectionId]) {
  245. this._lostMessages[connectionId] = [];
  246. }
  247. this._lostMessages[connectionId].push(message);
  248. };
  249. /** Retrieve messages from lost message store */
  250. Peer.prototype._getMessages = function(connectionId) {
  251. var messages = this._lostMessages[connectionId];
  252. if (messages) {
  253. delete this._lostMessages[connectionId];
  254. return messages;
  255. } else {
  256. return [];
  257. }
  258. };
  259. /**
  260. * Returns a DataConnection to the specified peer. See documentation for a
  261. * complete list of options.
  262. */
  263. Peer.prototype.connect = function(peer, options) {
  264. if (this.disconnected) {
  265. util.warn('You cannot connect to a new Peer because you called ' +
  266. '.disconnect() on this Peer and ended your connection with the ' +
  267. 'server. You can create a new Peer to reconnect, or call reconnect ' +
  268. 'on this peer if you believe its ID to still be available.');
  269. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  270. return;
  271. }
  272. var connection = new DataConnection(peer, this, options);
  273. this._addConnection(peer, connection);
  274. return connection;
  275. };
  276. /**
  277. * Returns a MediaConnection to the specified peer. See documentation for a
  278. * complete list of options.
  279. */
  280. Peer.prototype.call = function(peer, stream, options) {
  281. if (this.disconnected) {
  282. util.warn('You cannot connect to a new Peer because you called ' +
  283. '.disconnect() on this Peer and ended your connection with the ' +
  284. 'server. You can create a new Peer to reconnect.');
  285. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  286. return;
  287. }
  288. if (!stream) {
  289. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  290. return;
  291. }
  292. options = options || {};
  293. options._stream = stream;
  294. var call = new MediaConnection(peer, this, options);
  295. this._addConnection(peer, call);
  296. return call;
  297. };
  298. /** Add a data/media connection to this peer. */
  299. Peer.prototype._addConnection = function(peer, connection) {
  300. if (!this.connections[peer]) {
  301. this.connections[peer] = [];
  302. }
  303. this.connections[peer].push(connection);
  304. };
  305. /** Retrieve a data/media connection for this peer. */
  306. Peer.prototype.getConnection = function(peer, id) {
  307. var connections = this.connections[peer];
  308. if (!connections) {
  309. return null;
  310. }
  311. for (var i = 0, ii = connections.length; i < ii; i++) {
  312. if (connections[i].id === id) {
  313. return connections[i];
  314. }
  315. }
  316. return null;
  317. };
  318. Peer.prototype._delayedAbort = function(type, message) {
  319. var self = this;
  320. util.setZeroTimeout(function(){
  321. self._abort(type, message);
  322. });
  323. };
  324. /**
  325. * Destroys the Peer and emits an error message.
  326. * The Peer is not destroyed if it's in a disconnected state, in which case
  327. * it retains its disconnected state and its existing connections.
  328. */
  329. Peer.prototype._abort = function(type, message) {
  330. util.error('Aborting!');
  331. if (!this._lastServerId) {
  332. this.destroy();
  333. } else {
  334. this.disconnect();
  335. }
  336. this.emitError(type, message);
  337. };
  338. /** Emits a typed error message. */
  339. Peer.prototype.emitError = function(type, err) {
  340. util.error('Error:', err);
  341. if (typeof err === 'string') {
  342. err = new Error(err);
  343. }
  344. err.type = type;
  345. this.emit('error', err);
  346. };
  347. /**
  348. * Destroys the Peer: closes all active connections as well as the connection
  349. * to the server.
  350. * Warning: The peer can no longer create or accept connections after being
  351. * destroyed.
  352. */
  353. Peer.prototype.destroy = function() {
  354. if (!this.destroyed) {
  355. this._cleanup();
  356. this.disconnect();
  357. this.destroyed = true;
  358. }
  359. };
  360. /** Disconnects every connection on this peer. */
  361. Peer.prototype._cleanup = function() {
  362. if (this.connections) {
  363. var peers = Object.keys(this.connections);
  364. for (var i = 0, ii = peers.length; i < ii; i++) {
  365. this._cleanupPeer(peers[i]);
  366. }
  367. }
  368. this.emit('close');
  369. };
  370. /** Closes all connections to this peer. */
  371. Peer.prototype._cleanupPeer = function(peer) {
  372. var connections = this.connections[peer];
  373. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  374. connections[j].close();
  375. }
  376. };
  377. /**
  378. * Disconnects the Peer's connection to the PeerServer. Does not close any
  379. * active connections.
  380. * Warning: The peer can no longer create or accept connections after being
  381. * disconnected. It also cannot reconnect to the server.
  382. */
  383. Peer.prototype.disconnect = function() {
  384. var self = this;
  385. util.setZeroTimeout(function(){
  386. if (!self.disconnected) {
  387. self.disconnected = true;
  388. self.open = false;
  389. if (self.socket) {
  390. self.socket.close();
  391. }
  392. self.emit('disconnected', self.id);
  393. self._lastServerId = self.id;
  394. self.id = null;
  395. }
  396. });
  397. };
  398. /** Attempts to reconnect with the same ID. */
  399. Peer.prototype.reconnect = function() {
  400. if (this.disconnected && !this.destroyed) {
  401. util.log('Attempting reconnection to server with ID ' + this._lastServerId);
  402. this.disconnected = false;
  403. this._initializeServerConnection();
  404. this._initialize(this._lastServerId);
  405. } else if (this.destroyed) {
  406. throw new Error('This peer cannot reconnect to the server. It has already been destroyed.');
  407. } else if (!this.disconnected && !this.open) {
  408. // Do nothing. We're still connecting the first time.
  409. util.error('In a hurry? We\'re still trying to make the initial connection!');
  410. } else {
  411. throw new Error('Peer ' + this.id + ' cannot reconnect because it is not disconnected from the server!');
  412. }
  413. };
  414. /**
  415. * Get a list of available peer IDs. If you're running your own server, you'll
  416. * want to set allow_discovery: true in the PeerServer options. If you're using
  417. * the cloud server, email team@peerjs.com to get the functionality enabled for
  418. * your key.
  419. */
  420. Peer.prototype.listAllPeers = function(cb) {
  421. cb = cb || function() {};
  422. var self = this;
  423. var http = new XMLHttpRequest();
  424. var protocol = this.options.secure ? 'https://' : 'http://';
  425. var url = protocol + this.options.host + ':' + this.options.port +
  426. this.options.path + this.options.key + '/peers';
  427. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  428. url += queryString;
  429. // If there's no ID we need to wait for one before trying to init socket.
  430. http.open('get', url, true);
  431. http.onerror = function(e) {
  432. self._abort('server-error', 'Could not get peers from the server.');
  433. cb([]);
  434. };
  435. http.onreadystatechange = function() {
  436. if (http.readyState !== 4) {
  437. return;
  438. }
  439. if (http.status === 401) {
  440. var helpfulError = '';
  441. if (self.options.host !== util.CLOUD_HOST) {
  442. helpfulError = 'It looks like you\'re using the cloud server. You can email ' +
  443. 'team@peerjs.com to enable peer listing for your API key.';
  444. } else {
  445. helpfulError = 'You need to enable `allow_discovery` on your self-hosted ' +
  446. 'PeerServer to use this feature.';
  447. }
  448. cb([]);
  449. throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError);
  450. } else if (http.status !== 200) {
  451. cb([]);
  452. } else {
  453. cb(JSON.parse(http.responseText));
  454. }
  455. };
  456. http.send(null);
  457. };
  458. module.exports = Peer;