peer.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729
  1. import { EventEmitter } from "eventemitter3";
  2. import { util } from "./util";
  3. import logger, { LogLevel } from "./logger";
  4. import { Socket } from "./socket";
  5. import { MediaConnection } from "./mediaconnection";
  6. import { DataConnection } from "./dataconnection";
  7. import {
  8. ConnectionType,
  9. PeerErrorType,
  10. SocketEventType,
  11. ServerMessageType,
  12. } from "./enums";
  13. import { ServerMessage } from "./servermessage";
  14. import { API } from "./api";
  15. import type {
  16. PeerConnectOption,
  17. PeerJSOption,
  18. CallOption,
  19. } from "./optionInterfaces";
  20. class PeerOptions implements PeerJSOption {
  21. /**
  22. * Prints log messages depending on the debug level passed in.
  23. */
  24. debug?: LogLevel;
  25. /**
  26. * Server host. Defaults to `0.peerjs.com`.
  27. * Also accepts `'/'` to signify relative hostname.
  28. */
  29. host?: string;
  30. /**
  31. * Server port. Defaults to `443`.
  32. */
  33. port?: number;
  34. /**
  35. * The path where your self-hosted PeerServer is running. Defaults to `'/'`
  36. */
  37. path?: string;
  38. /**
  39. * API key for the PeerServer.
  40. * This is not used anymore.
  41. * @deprecated
  42. */
  43. key?: string;
  44. token?: string;
  45. /**
  46. * Configuration hash passed to RTCPeerConnection.
  47. * This hash contains any custom ICE/TURN server configuration.
  48. *
  49. * Defaults to {@apilink util.defaultConfig}
  50. */
  51. config?: any;
  52. /**
  53. * Set to true `true` if you're using TLS.
  54. * :::danger
  55. * If possible *always use TLS*
  56. * :::
  57. */
  58. secure?: boolean;
  59. pingInterval?: number;
  60. referrerPolicy?: ReferrerPolicy;
  61. logFunction?: (logLevel: LogLevel, ...rest: any[]) => void;
  62. }
  63. class PeerError extends Error {
  64. constructor(type: PeerErrorType, err: Error | string) {
  65. if (typeof err === "string") {
  66. super(err);
  67. } else {
  68. super();
  69. Object.assign(this, err);
  70. }
  71. this.type = type;
  72. }
  73. type: PeerErrorType;
  74. }
  75. export type { PeerError, PeerOptions };
  76. export type PeerEvents = {
  77. /**
  78. * Emitted when a connection to the PeerServer is established.
  79. *
  80. * You may use the peer before this is emitted, but messages to the server will be queued. <code>id</code> is the brokering ID of the peer (which was either provided in the constructor or assigned by the server).<span class='tip'>You should not wait for this event before connecting to other peers if connection speed is important.</span>
  81. */
  82. open: (id: string) => void;
  83. /**
  84. * Emitted when a new data connection is established from a remote peer.
  85. */
  86. connection: (dataConnection: DataConnection) => void;
  87. /**
  88. * Emitted when a remote peer attempts to call you.
  89. */
  90. call: (mediaConnection: MediaConnection) => void;
  91. /**
  92. * Emitted when the peer is destroyed and can no longer accept or create any new connections.
  93. */
  94. close: () => void;
  95. /**
  96. * Emitted when the peer is disconnected from the signalling server
  97. */
  98. disconnected: (currentId: string) => void;
  99. /**
  100. * Errors on the peer are almost always fatal and will destroy the peer.
  101. *
  102. * Errors from the underlying socket and PeerConnections are forwarded here.
  103. */
  104. error: (error: PeerError) => void;
  105. };
  106. /**
  107. * A peer who can initiate connections with other peers.
  108. */
  109. export class Peer extends EventEmitter<PeerEvents> {
  110. private static readonly DEFAULT_KEY = "peerjs";
  111. private readonly _options: PeerOptions;
  112. private readonly _api: API;
  113. private readonly _socket: Socket;
  114. private _id: string | null = null;
  115. private _lastServerId: string | null = null;
  116. // States.
  117. private _destroyed = false; // Connections have been killed
  118. private _disconnected = false; // Connection to PeerServer killed but P2P connections still active
  119. private _open = false; // Sockets and such are not yet open.
  120. private readonly _connections: Map<
  121. string,
  122. (DataConnection | MediaConnection)[]
  123. > = new Map(); // All connections for this peer.
  124. private readonly _lostMessages: Map<string, ServerMessage[]> = new Map(); // src => [list of messages]
  125. /**
  126. * The brokering ID of this peer
  127. *
  128. * If no ID was specified in {@apilink Peer | the constructor},
  129. * this will be `undefined` until the {@apilink PeerEvents | `open`} event is emitted.
  130. */
  131. get id() {
  132. return this._id;
  133. }
  134. get options() {
  135. return this._options;
  136. }
  137. get open() {
  138. return this._open;
  139. }
  140. /**
  141. * @internal
  142. */
  143. get socket() {
  144. return this._socket;
  145. }
  146. /**
  147. * A hash of all connections associated with this peer, keyed by the remote peer's ID.
  148. * @deprecated
  149. * Return type will change from Object to Map<string,[]>
  150. */
  151. get connections(): Object {
  152. const plainConnections = Object.create(null);
  153. for (const [k, v] of this._connections) {
  154. plainConnections[k] = v;
  155. }
  156. return plainConnections;
  157. }
  158. /**
  159. * true if this peer and all of its connections can no longer be used.
  160. */
  161. get destroyed() {
  162. return this._destroyed;
  163. }
  164. /**
  165. * false if there is an active connection to the PeerServer.
  166. */
  167. get disconnected() {
  168. return this._disconnected;
  169. }
  170. /**
  171. * A peer can connect to other peers and listen for connections.
  172. */
  173. constructor();
  174. /**
  175. * A peer can connect to other peers and listen for connections.
  176. * @param options for specifying details about PeerServer
  177. */
  178. constructor(options: PeerOptions);
  179. /**
  180. * A peer can connect to other peers and listen for connections.
  181. * @param id Other peers can connect to this peer using the provided ID.
  182. * If no ID is given, one will be generated by the brokering server.
  183. * The ID must start and end with an alphanumeric character (lower or upper case character or a digit). In the middle of the ID spaces, dashes (-) and underscores (_) are allowed. Use {@apilink PeerOptions.metadata } to send identifying information.
  184. * @param options for specifying details about PeerServer
  185. */
  186. constructor(id: string, options?: PeerOptions);
  187. constructor(id?: string | PeerOptions, options?: PeerOptions) {
  188. super();
  189. let userId: string | undefined;
  190. // Deal with overloading
  191. if (id && id.constructor == Object) {
  192. options = id as PeerOptions;
  193. } else if (id) {
  194. userId = id.toString();
  195. }
  196. // Configurize options
  197. options = {
  198. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  199. host: util.CLOUD_HOST,
  200. port: util.CLOUD_PORT,
  201. path: "/",
  202. key: Peer.DEFAULT_KEY,
  203. token: util.randomToken(),
  204. config: util.defaultConfig,
  205. referrerPolicy: "strict-origin-when-cross-origin",
  206. ...options,
  207. };
  208. this._options = options;
  209. // Detect relative URL host.
  210. if (this._options.host === "/") {
  211. this._options.host = window.location.hostname;
  212. }
  213. // Set path correctly.
  214. if (this._options.path) {
  215. if (this._options.path[0] !== "/") {
  216. this._options.path = "/" + this._options.path;
  217. }
  218. if (this._options.path[this._options.path.length - 1] !== "/") {
  219. this._options.path += "/";
  220. }
  221. }
  222. // Set whether we use SSL to same as current host
  223. if (
  224. this._options.secure === undefined &&
  225. this._options.host !== util.CLOUD_HOST
  226. ) {
  227. this._options.secure = util.isSecure();
  228. } else if (this._options.host == util.CLOUD_HOST) {
  229. this._options.secure = true;
  230. }
  231. // Set a custom log function if present
  232. if (this._options.logFunction) {
  233. logger.setLogFunction(this._options.logFunction);
  234. }
  235. logger.logLevel = this._options.debug || 0;
  236. this._api = new API(options);
  237. this._socket = this._createServerConnection();
  238. // Sanity checks
  239. // Ensure WebRTC supported
  240. if (!util.supports.audioVideo && !util.supports.data) {
  241. this._delayedAbort(
  242. PeerErrorType.BrowserIncompatible,
  243. "The current browser does not support WebRTC",
  244. );
  245. return;
  246. }
  247. // Ensure alphanumeric id
  248. if (!!userId && !util.validateId(userId)) {
  249. this._delayedAbort(PeerErrorType.InvalidID, `ID "${userId}" is invalid`);
  250. return;
  251. }
  252. if (userId) {
  253. this._initialize(userId);
  254. } else {
  255. this._api
  256. .retrieveId()
  257. .then((id) => this._initialize(id))
  258. .catch((error) => this._abort(PeerErrorType.ServerError, error));
  259. }
  260. }
  261. private _createServerConnection(): Socket {
  262. const socket = new Socket(
  263. this._options.secure,
  264. this._options.host!,
  265. this._options.port!,
  266. this._options.path!,
  267. this._options.key!,
  268. this._options.pingInterval,
  269. );
  270. socket.on(SocketEventType.Message, (data: ServerMessage) => {
  271. this._handleMessage(data);
  272. });
  273. socket.on(SocketEventType.Error, (error: string) => {
  274. this._abort(PeerErrorType.SocketError, error);
  275. });
  276. socket.on(SocketEventType.Disconnected, () => {
  277. if (this.disconnected) {
  278. return;
  279. }
  280. this.emitError(PeerErrorType.Network, "Lost connection to server.");
  281. this.disconnect();
  282. });
  283. socket.on(SocketEventType.Close, () => {
  284. if (this.disconnected) {
  285. return;
  286. }
  287. this._abort(
  288. PeerErrorType.SocketClosed,
  289. "Underlying socket is already closed.",
  290. );
  291. });
  292. return socket;
  293. }
  294. /** Initialize a connection with the server. */
  295. private _initialize(id: string): void {
  296. this._id = id;
  297. this.socket.start(id, this._options.token!);
  298. }
  299. /** Handles messages from the server. */
  300. private _handleMessage(message: ServerMessage): void {
  301. const type = message.type;
  302. const payload = message.payload;
  303. const peerId = message.src;
  304. switch (type) {
  305. case ServerMessageType.Open: // The connection to the server is open.
  306. this._lastServerId = this.id;
  307. this._open = true;
  308. this.emit("open", this.id);
  309. break;
  310. case ServerMessageType.Error: // Server error.
  311. this._abort(PeerErrorType.ServerError, payload.msg);
  312. break;
  313. case ServerMessageType.IdTaken: // The selected ID is taken.
  314. this._abort(PeerErrorType.UnavailableID, `ID "${this.id}" is taken`);
  315. break;
  316. case ServerMessageType.InvalidKey: // The given API key cannot be found.
  317. this._abort(
  318. PeerErrorType.InvalidKey,
  319. `API KEY "${this._options.key}" is invalid`,
  320. );
  321. break;
  322. case ServerMessageType.Leave: // Another peer has closed its connection to this peer.
  323. logger.log(`Received leave message from ${peerId}`);
  324. this._cleanupPeer(peerId);
  325. this._connections.delete(peerId);
  326. break;
  327. case ServerMessageType.Expire: // The offer sent to a peer has expired without response.
  328. this.emitError(
  329. PeerErrorType.PeerUnavailable,
  330. `Could not connect to peer ${peerId}`,
  331. );
  332. break;
  333. case ServerMessageType.Offer: {
  334. // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  335. const connectionId = payload.connectionId;
  336. let connection = this.getConnection(peerId, connectionId);
  337. if (connection) {
  338. connection.close();
  339. logger.warn(
  340. `Offer received for existing Connection ID:${connectionId}`,
  341. );
  342. }
  343. // Create a new connection.
  344. if (payload.type === ConnectionType.Media) {
  345. const mediaConnection = new MediaConnection(peerId, this, {
  346. connectionId: connectionId,
  347. _payload: payload,
  348. metadata: payload.metadata,
  349. });
  350. connection = mediaConnection;
  351. this._addConnection(peerId, connection);
  352. this.emit("call", mediaConnection);
  353. } else if (payload.type === ConnectionType.Data) {
  354. const dataConnection = new DataConnection(peerId, this, {
  355. connectionId: connectionId,
  356. _payload: payload,
  357. metadata: payload.metadata,
  358. label: payload.label,
  359. serialization: payload.serialization,
  360. reliable: payload.reliable,
  361. });
  362. connection = dataConnection;
  363. this._addConnection(peerId, connection);
  364. this.emit("connection", dataConnection);
  365. } else {
  366. logger.warn(`Received malformed connection type:${payload.type}`);
  367. return;
  368. }
  369. // Find messages.
  370. const messages = this._getMessages(connectionId);
  371. for (const message of messages) {
  372. connection.handleMessage(message);
  373. }
  374. break;
  375. }
  376. default: {
  377. if (!payload) {
  378. logger.warn(
  379. `You received a malformed message from ${peerId} of type ${type}`,
  380. );
  381. return;
  382. }
  383. const connectionId = payload.connectionId;
  384. const connection = this.getConnection(peerId, connectionId);
  385. if (connection && connection.peerConnection) {
  386. // Pass it on.
  387. connection.handleMessage(message);
  388. } else if (connectionId) {
  389. // Store for possible later use
  390. this._storeMessage(connectionId, message);
  391. } else {
  392. logger.warn("You received an unrecognized message:", message);
  393. }
  394. break;
  395. }
  396. }
  397. }
  398. /** Stores messages without a set up connection, to be claimed later. */
  399. private _storeMessage(connectionId: string, message: ServerMessage): void {
  400. if (!this._lostMessages.has(connectionId)) {
  401. this._lostMessages.set(connectionId, []);
  402. }
  403. this._lostMessages.get(connectionId).push(message);
  404. }
  405. /**
  406. * Retrieve messages from lost message store
  407. * @internal
  408. */
  409. //TODO Change it to private
  410. public _getMessages(connectionId: string): ServerMessage[] {
  411. const messages = this._lostMessages.get(connectionId);
  412. if (messages) {
  413. this._lostMessages.delete(connectionId);
  414. return messages;
  415. }
  416. return [];
  417. }
  418. /**
  419. * Connects to the remote peer specified by id and returns a data connection.
  420. * @param peer The brokering ID of the remote peer (their {@apilink Peer.id}).
  421. * @param options for specifying details about Peer Connection
  422. */
  423. connect(peer: string, options: PeerConnectOption = {}): DataConnection {
  424. if (this.disconnected) {
  425. logger.warn(
  426. "You cannot connect to a new Peer because you called " +
  427. ".disconnect() on this Peer and ended your connection with the " +
  428. "server. You can create a new Peer to reconnect, or call reconnect " +
  429. "on this peer if you believe its ID to still be available.",
  430. );
  431. this.emitError(
  432. PeerErrorType.Disconnected,
  433. "Cannot connect to new Peer after disconnecting from server.",
  434. );
  435. return;
  436. }
  437. const dataConnection = new DataConnection(peer, this, options);
  438. this._addConnection(peer, dataConnection);
  439. return dataConnection;
  440. }
  441. /**
  442. * Calls the remote peer specified by id and returns a media connection.
  443. * @param peer The brokering ID of the remote peer (their peer.id).
  444. * @param stream The caller's media stream
  445. * @param options Metadata associated with the connection, passed in by whoever initiated the connection.
  446. */
  447. call(
  448. peer: string,
  449. stream: MediaStream,
  450. options: CallOption = {},
  451. ): MediaConnection {
  452. if (this.disconnected) {
  453. logger.warn(
  454. "You cannot connect to a new Peer because you called " +
  455. ".disconnect() on this Peer and ended your connection with the " +
  456. "server. You can create a new Peer to reconnect.",
  457. );
  458. this.emitError(
  459. PeerErrorType.Disconnected,
  460. "Cannot connect to new Peer after disconnecting from server.",
  461. );
  462. return;
  463. }
  464. if (!stream) {
  465. logger.error(
  466. "To call a peer, you must provide a stream from your browser's `getUserMedia`.",
  467. );
  468. return;
  469. }
  470. const mediaConnection = new MediaConnection(peer, this, {
  471. ...options,
  472. _stream: stream,
  473. });
  474. this._addConnection(peer, mediaConnection);
  475. return mediaConnection;
  476. }
  477. /** Add a data/media connection to this peer. */
  478. private _addConnection(
  479. peerId: string,
  480. connection: MediaConnection | DataConnection,
  481. ): void {
  482. logger.log(
  483. `add connection ${connection.type}:${connection.connectionId} to peerId:${peerId}`,
  484. );
  485. if (!this._connections.has(peerId)) {
  486. this._connections.set(peerId, []);
  487. }
  488. this._connections.get(peerId).push(connection);
  489. }
  490. //TODO should be private
  491. _removeConnection(connection: DataConnection | MediaConnection): void {
  492. const connections = this._connections.get(connection.peer);
  493. if (connections) {
  494. const index = connections.indexOf(connection);
  495. if (index !== -1) {
  496. connections.splice(index, 1);
  497. }
  498. }
  499. //remove from lost messages
  500. this._lostMessages.delete(connection.connectionId);
  501. }
  502. /** Retrieve a data/media connection for this peer. */
  503. getConnection(
  504. peerId: string,
  505. connectionId: string,
  506. ): null | DataConnection | MediaConnection {
  507. const connections = this._connections.get(peerId);
  508. if (!connections) {
  509. return null;
  510. }
  511. for (const connection of connections) {
  512. if (connection.connectionId === connectionId) {
  513. return connection;
  514. }
  515. }
  516. return null;
  517. }
  518. private _delayedAbort(type: PeerErrorType, message: string | Error): void {
  519. setTimeout(() => {
  520. this._abort(type, message);
  521. }, 0);
  522. }
  523. /**
  524. * Emits an error message and destroys the Peer.
  525. * The Peer is not destroyed if it's in a disconnected state, in which case
  526. * it retains its disconnected state and its existing connections.
  527. */
  528. private _abort(type: PeerErrorType, message: string | Error): void {
  529. logger.error("Aborting!");
  530. this.emitError(type, message);
  531. if (!this._lastServerId) {
  532. this.destroy();
  533. } else {
  534. this.disconnect();
  535. }
  536. }
  537. /** Emits a typed error message. */
  538. emitError(type: PeerErrorType, err: string | Error): void {
  539. logger.error("Error:", err);
  540. this.emit("error", new PeerError(type, err));
  541. }
  542. /**
  543. * Destroys the Peer: closes all active connections as well as the connection
  544. * to the server.
  545. *
  546. * :::caution
  547. * This cannot be undone; the respective peer object will no longer be able
  548. * to create or receive any connections, its ID will be forfeited on the server,
  549. * and all of its data and media connections will be closed.
  550. * :::
  551. */
  552. destroy(): void {
  553. if (this.destroyed) {
  554. return;
  555. }
  556. logger.log(`Destroy peer with ID:${this.id}`);
  557. this.disconnect();
  558. this._cleanup();
  559. this._destroyed = true;
  560. this.emit("close");
  561. }
  562. /** Disconnects every connection on this peer. */
  563. private _cleanup(): void {
  564. for (const peerId of this._connections.keys()) {
  565. this._cleanupPeer(peerId);
  566. this._connections.delete(peerId);
  567. }
  568. this.socket.removeAllListeners();
  569. }
  570. /** Closes all connections to this peer. */
  571. private _cleanupPeer(peerId: string): void {
  572. const connections = this._connections.get(peerId);
  573. if (!connections) return;
  574. for (const connection of connections) {
  575. connection.close();
  576. }
  577. }
  578. /**
  579. * Disconnects the Peer's connection to the PeerServer. Does not close any
  580. * active connections.
  581. * Warning: The peer can no longer create or accept connections after being
  582. * disconnected. It also cannot reconnect to the server.
  583. */
  584. disconnect(): void {
  585. if (this.disconnected) {
  586. return;
  587. }
  588. const currentId = this.id;
  589. logger.log(`Disconnect peer with ID:${currentId}`);
  590. this._disconnected = true;
  591. this._open = false;
  592. this.socket.close();
  593. this._lastServerId = currentId;
  594. this._id = null;
  595. this.emit("disconnected", currentId);
  596. }
  597. /** Attempts to reconnect with the same ID.
  598. *
  599. * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.
  600. * Destroyed peers cannot be reconnected.
  601. * If the connection fails (as an example, if the peer's old ID is now taken),
  602. * the peer's existing connections will not close, but any associated errors events will fire.
  603. */
  604. reconnect(): void {
  605. if (this.disconnected && !this.destroyed) {
  606. logger.log(
  607. `Attempting reconnection to server with ID ${this._lastServerId}`,
  608. );
  609. this._disconnected = false;
  610. this._initialize(this._lastServerId!);
  611. } else if (this.destroyed) {
  612. throw new Error(
  613. "This peer cannot reconnect to the server. It has already been destroyed.",
  614. );
  615. } else if (!this.disconnected && !this.open) {
  616. // Do nothing. We're still connecting the first time.
  617. logger.error(
  618. "In a hurry? We're still trying to make the initial connection!",
  619. );
  620. } else {
  621. throw new Error(
  622. `Peer ${this.id} cannot reconnect because it is not disconnected from the server!`,
  623. );
  624. }
  625. }
  626. /**
  627. * Get a list of available peer IDs. If you're running your own server, you'll
  628. * want to set allow_discovery: true in the PeerServer options. If you're using
  629. * the cloud server, email team@peerjs.com to get the functionality enabled for
  630. * your key.
  631. */
  632. listAllPeers(cb = (_: any[]) => {}): void {
  633. this._api
  634. .listAllPeers()
  635. .then((peers) => cb(peers))
  636. .catch((error) => this._abort(PeerErrorType.ServerError, error));
  637. }
  638. }