peer.js 16 KB

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