peer.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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. key: "peerjs",
  28. path: "/",
  29. token: util.randomToken(),
  30. config: util.defaultConfig
  31. },
  32. options
  33. );
  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. //connection.handleMessage(message);
  224. }
  225. // Create a new connection.
  226. if (payload.type === "media") {
  227. connection = new MediaConnection(peer, this, {
  228. connectionId: connectionId,
  229. _payload: payload,
  230. metadata: payload.metadata
  231. });
  232. this._addConnection(peer, connection);
  233. this.emit("call", connection);
  234. } else if (payload.type === "data") {
  235. connection = new DataConnection(peer, this, {
  236. connectionId: connectionId,
  237. _payload: payload,
  238. metadata: payload.metadata,
  239. label: payload.label,
  240. serialization: payload.serialization,
  241. reliable: payload.reliable
  242. });
  243. this._addConnection(peer, connection);
  244. this.emit("connection", connection);
  245. } else {
  246. util.warn("Received malformed connection type:", payload.type);
  247. return;
  248. }
  249. // Find messages.
  250. var messages = this._getMessages(connectionId);
  251. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  252. connection.handleMessage(messages[i]);
  253. }
  254. break;
  255. default:
  256. if (!payload) {
  257. util.warn(
  258. "You received a malformed message from " + peer + " of type " + type
  259. );
  260. return;
  261. }
  262. var id = payload.connectionId;
  263. connection = this.getConnection(peer, id);
  264. if (connection && connection.pc) {
  265. // Pass it on.
  266. connection.handleMessage(message);
  267. } else if (id) {
  268. // Store for possible later use
  269. this._storeMessage(id, message);
  270. } else {
  271. util.warn("You received an unrecognized message:", message);
  272. }
  273. break;
  274. }
  275. };
  276. /** Stores messages without a set up connection, to be claimed later. */
  277. Peer.prototype._storeMessage = function(connectionId, message) {
  278. if (!this._lostMessages[connectionId]) {
  279. this._lostMessages[connectionId] = [];
  280. }
  281. this._lostMessages[connectionId].push(message);
  282. };
  283. /** Retrieve messages from lost message store */
  284. Peer.prototype._getMessages = function(connectionId) {
  285. var messages = this._lostMessages[connectionId];
  286. if (messages) {
  287. delete this._lostMessages[connectionId];
  288. return messages;
  289. } else {
  290. return [];
  291. }
  292. };
  293. /**
  294. * Returns a DataConnection to the specified peer. See documentation for a
  295. * complete list of options.
  296. */
  297. Peer.prototype.connect = function(peer, options) {
  298. if (this.disconnected) {
  299. util.warn(
  300. "You cannot connect to a new Peer because you called " +
  301. ".disconnect() on this Peer and ended your connection with the " +
  302. "server. You can create a new Peer to reconnect, or call reconnect " +
  303. "on this peer if you believe its ID to still be available."
  304. );
  305. this.emitError(
  306. "disconnected",
  307. "Cannot connect to new Peer after disconnecting from server."
  308. );
  309. return;
  310. }
  311. var connection = new DataConnection(peer, this, options);
  312. this._addConnection(peer, connection);
  313. return connection;
  314. };
  315. /**
  316. * Returns a MediaConnection to the specified peer. See documentation for a
  317. * complete list of options.
  318. */
  319. Peer.prototype.call = function(peer, stream, options) {
  320. if (this.disconnected) {
  321. util.warn(
  322. "You cannot connect to a new Peer because you called " +
  323. ".disconnect() on this Peer and ended your connection with the " +
  324. "server. You can create a new Peer to reconnect."
  325. );
  326. this.emitError(
  327. "disconnected",
  328. "Cannot connect to new Peer after disconnecting from server."
  329. );
  330. return;
  331. }
  332. if (!stream) {
  333. util.error(
  334. "To call a peer, you must provide a stream from your browser's `getUserMedia`."
  335. );
  336. return;
  337. }
  338. options = options || {};
  339. options._stream = stream;
  340. var call = new MediaConnection(peer, this, options);
  341. this._addConnection(peer, call);
  342. return call;
  343. };
  344. /** Add a data/media connection to this peer. */
  345. Peer.prototype._addConnection = function(peer, connection) {
  346. if (!this.connections[peer]) {
  347. this.connections[peer] = [];
  348. }
  349. this.connections[peer].push(connection);
  350. };
  351. /** Retrieve a data/media connection for this peer. */
  352. Peer.prototype.getConnection = function(peer, id) {
  353. var connections = this.connections[peer];
  354. if (!connections) {
  355. return null;
  356. }
  357. for (var i = 0, ii = connections.length; i < ii; i++) {
  358. if (connections[i].id === id) {
  359. return connections[i];
  360. }
  361. }
  362. return null;
  363. };
  364. Peer.prototype._delayedAbort = function(type, message) {
  365. var self = this;
  366. util.setZeroTimeout(function() {
  367. self._abort(type, message);
  368. });
  369. };
  370. /**
  371. * Destroys the Peer and emits an error message.
  372. * The Peer is not destroyed if it's in a disconnected state, in which case
  373. * it retains its disconnected state and its existing connections.
  374. */
  375. Peer.prototype._abort = function(type, message) {
  376. util.error("Aborting!");
  377. if (!this._lastServerId) {
  378. this.destroy();
  379. } else {
  380. this.disconnect();
  381. }
  382. this.emitError(type, message);
  383. };
  384. /** Emits a typed error message. */
  385. Peer.prototype.emitError = function(type, err) {
  386. util.error("Error:", err);
  387. if (typeof err === "string") {
  388. err = new Error(err);
  389. }
  390. err.type = type;
  391. this.emit("error", err);
  392. };
  393. /**
  394. * Destroys the Peer: closes all active connections as well as the connection
  395. * to the server.
  396. * Warning: The peer can no longer create or accept connections after being
  397. * destroyed.
  398. */
  399. Peer.prototype.destroy = function() {
  400. if (!this.destroyed) {
  401. this._cleanup();
  402. this.disconnect();
  403. this.destroyed = true;
  404. }
  405. };
  406. /** Disconnects every connection on this peer. */
  407. Peer.prototype._cleanup = function() {
  408. if (this.connections) {
  409. var peers = Object.keys(this.connections);
  410. for (var i = 0, ii = peers.length; i < ii; i++) {
  411. this._cleanupPeer(peers[i]);
  412. }
  413. }
  414. this.emit("close");
  415. };
  416. /** Closes all connections to this peer. */
  417. Peer.prototype._cleanupPeer = function(peer) {
  418. var connections = this.connections[peer];
  419. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  420. connections[j].close();
  421. }
  422. };
  423. /**
  424. * Disconnects the Peer's connection to the PeerServer. Does not close any
  425. * active connections.
  426. * Warning: The peer can no longer create or accept connections after being
  427. * disconnected. It also cannot reconnect to the server.
  428. */
  429. Peer.prototype.disconnect = function() {
  430. var self = this;
  431. util.setZeroTimeout(function() {
  432. if (!self.disconnected) {
  433. self.disconnected = true;
  434. self.open = false;
  435. if (self.socket) {
  436. self.socket.close();
  437. }
  438. self.emit("disconnected", self.id);
  439. self._lastServerId = self.id;
  440. self.id = null;
  441. }
  442. });
  443. };
  444. /** Attempts to reconnect with the same ID. */
  445. Peer.prototype.reconnect = function() {
  446. if (this.disconnected && !this.destroyed) {
  447. util.log("Attempting reconnection to server with ID " + this._lastServerId);
  448. this.disconnected = false;
  449. this._initializeServerConnection();
  450. this._initialize(this._lastServerId);
  451. } else if (this.destroyed) {
  452. throw new Error(
  453. "This peer cannot reconnect to the server. It has already been destroyed."
  454. );
  455. } else if (!this.disconnected && !this.open) {
  456. // Do nothing. We're still connecting the first time.
  457. util.error(
  458. "In a hurry? We're still trying to make the initial connection!"
  459. );
  460. } else {
  461. throw new Error(
  462. "Peer " +
  463. this.id +
  464. " cannot reconnect because it is not disconnected from the server!"
  465. );
  466. }
  467. };
  468. /**
  469. * Get a list of available peer IDs. If you're running your own server, you'll
  470. * want to set allow_discovery: true in the PeerServer options. If you're using
  471. * the cloud server, email team@peerjs.com to get the functionality enabled for
  472. * your key.
  473. */
  474. Peer.prototype.listAllPeers = function(cb) {
  475. cb = cb || function() {};
  476. var self = this;
  477. var http = new XMLHttpRequest();
  478. var protocol = this.options.secure ? "https://" : "http://";
  479. var url =
  480. protocol +
  481. this.options.host +
  482. ":" +
  483. this.options.port +
  484. this.options.path +
  485. this.options.key +
  486. "/peers";
  487. var queryString = "?ts=" + new Date().getTime() + "" + Math.random();
  488. url += queryString;
  489. // If there's no ID we need to wait for one before trying to init socket.
  490. http.open("get", url, true);
  491. http.onerror = function(e) {
  492. self._abort("server-error", "Could not get peers from the server.");
  493. cb([]);
  494. };
  495. http.onreadystatechange = function() {
  496. if (http.readyState !== 4) {
  497. return;
  498. }
  499. if (http.status === 401) {
  500. var helpfulError = "";
  501. if (self.options.host !== util.CLOUD_HOST) {
  502. helpfulError =
  503. "It looks like you're using the cloud server. You can email " +
  504. "team@peerjs.com to enable peer listing for your API key.";
  505. } else {
  506. helpfulError =
  507. "You need to enable `allow_discovery` on your self-hosted " +
  508. "PeerServer to use this feature.";
  509. }
  510. cb([]);
  511. throw new Error(
  512. "It doesn't look like you have permission to list peers IDs. " +
  513. helpfulError
  514. );
  515. } else if (http.status !== 200) {
  516. cb([]);
  517. } else {
  518. cb(JSON.parse(http.responseText));
  519. }
  520. };
  521. http.send(null);
  522. };
  523. module.exports = Peer;