peer.js 15 KB

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