peer.js 16 KB

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