peer.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723
  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 };
  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. get socket() {
  141. return this._socket;
  142. }
  143. /**
  144. * A hash of all connections associated with this peer, keyed by the remote peer's ID.
  145. * @deprecated
  146. * Return type will change from Object to Map<string,[]>
  147. */
  148. get connections(): Object {
  149. const plainConnections = Object.create(null);
  150. for (const [k, v] of this._connections) {
  151. plainConnections[k] = v;
  152. }
  153. return plainConnections;
  154. }
  155. /**
  156. * true if this peer and all of its connections can no longer be used.
  157. */
  158. get destroyed() {
  159. return this._destroyed;
  160. }
  161. /**
  162. * false if there is an active connection to the PeerServer.
  163. */
  164. get disconnected() {
  165. return this._disconnected;
  166. }
  167. /**
  168. * A peer can connect to other peers and listen for connections.
  169. */
  170. constructor();
  171. /**
  172. * A peer can connect to other peers and listen for connections.
  173. * @param options for specifying details about PeerServer
  174. */
  175. constructor(options: PeerOptions);
  176. /**
  177. * A peer can connect to other peers and listen for connections.
  178. * @param id Other peers can connect to this peer using the provided ID.
  179. * If no ID is given, one will be generated by the brokering server.
  180. * 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.
  181. * @param options for specifying details about PeerServer
  182. */
  183. constructor(id: string, options?: PeerOptions);
  184. constructor(id?: string | PeerOptions, options?: PeerOptions) {
  185. super();
  186. let userId: string | undefined;
  187. // Deal with overloading
  188. if (id && id.constructor == Object) {
  189. options = id as PeerOptions;
  190. } else if (id) {
  191. userId = id.toString();
  192. }
  193. // Configurize options
  194. options = {
  195. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  196. host: util.CLOUD_HOST,
  197. port: util.CLOUD_PORT,
  198. path: "/",
  199. key: Peer.DEFAULT_KEY,
  200. token: util.randomToken(),
  201. config: util.defaultConfig,
  202. referrerPolicy: "strict-origin-when-cross-origin",
  203. ...options,
  204. };
  205. this._options = options;
  206. // Detect relative URL host.
  207. if (this._options.host === "/") {
  208. this._options.host = window.location.hostname;
  209. }
  210. // Set path correctly.
  211. if (this._options.path) {
  212. if (this._options.path[0] !== "/") {
  213. this._options.path = "/" + this._options.path;
  214. }
  215. if (this._options.path[this._options.path.length - 1] !== "/") {
  216. this._options.path += "/";
  217. }
  218. }
  219. // Set whether we use SSL to same as current host
  220. if (
  221. this._options.secure === undefined &&
  222. this._options.host !== util.CLOUD_HOST
  223. ) {
  224. this._options.secure = util.isSecure();
  225. } else if (this._options.host == util.CLOUD_HOST) {
  226. this._options.secure = true;
  227. }
  228. // Set a custom log function if present
  229. if (this._options.logFunction) {
  230. logger.setLogFunction(this._options.logFunction);
  231. }
  232. logger.logLevel = this._options.debug || 0;
  233. this._api = new API(options);
  234. this._socket = this._createServerConnection();
  235. // Sanity checks
  236. // Ensure WebRTC supported
  237. if (!util.supports.audioVideo && !util.supports.data) {
  238. this._delayedAbort(
  239. PeerErrorType.BrowserIncompatible,
  240. "The current browser does not support WebRTC",
  241. );
  242. return;
  243. }
  244. // Ensure alphanumeric id
  245. if (!!userId && !util.validateId(userId)) {
  246. this._delayedAbort(PeerErrorType.InvalidID, `ID "${userId}" is invalid`);
  247. return;
  248. }
  249. if (userId) {
  250. this._initialize(userId);
  251. } else {
  252. this._api
  253. .retrieveId()
  254. .then((id) => this._initialize(id))
  255. .catch((error) => this._abort(PeerErrorType.ServerError, error));
  256. }
  257. }
  258. private _createServerConnection(): Socket {
  259. const socket = new Socket(
  260. this._options.secure,
  261. this._options.host!,
  262. this._options.port!,
  263. this._options.path!,
  264. this._options.key!,
  265. this._options.pingInterval,
  266. );
  267. socket.on(SocketEventType.Message, (data: ServerMessage) => {
  268. this._handleMessage(data);
  269. });
  270. socket.on(SocketEventType.Error, (error: string) => {
  271. this._abort(PeerErrorType.SocketError, error);
  272. });
  273. socket.on(SocketEventType.Disconnected, () => {
  274. if (this.disconnected) {
  275. return;
  276. }
  277. this.emitError(PeerErrorType.Network, "Lost connection to server.");
  278. this.disconnect();
  279. });
  280. socket.on(SocketEventType.Close, () => {
  281. if (this.disconnected) {
  282. return;
  283. }
  284. this._abort(
  285. PeerErrorType.SocketClosed,
  286. "Underlying socket is already closed.",
  287. );
  288. });
  289. return socket;
  290. }
  291. /** Initialize a connection with the server. */
  292. private _initialize(id: string): void {
  293. this._id = id;
  294. this.socket.start(id, this._options.token!);
  295. }
  296. /** Handles messages from the server. */
  297. private _handleMessage(message: ServerMessage): void {
  298. const type = message.type;
  299. const payload = message.payload;
  300. const peerId = message.src;
  301. switch (type) {
  302. case ServerMessageType.Open: // The connection to the server is open.
  303. this._lastServerId = this.id;
  304. this._open = true;
  305. this.emit("open", this.id);
  306. break;
  307. case ServerMessageType.Error: // Server error.
  308. this._abort(PeerErrorType.ServerError, payload.msg);
  309. break;
  310. case ServerMessageType.IdTaken: // The selected ID is taken.
  311. this._abort(PeerErrorType.UnavailableID, `ID "${this.id}" is taken`);
  312. break;
  313. case ServerMessageType.InvalidKey: // The given API key cannot be found.
  314. this._abort(
  315. PeerErrorType.InvalidKey,
  316. `API KEY "${this._options.key}" is invalid`,
  317. );
  318. break;
  319. case ServerMessageType.Leave: // Another peer has closed its connection to this peer.
  320. logger.log(`Received leave message from ${peerId}`);
  321. this._cleanupPeer(peerId);
  322. this._connections.delete(peerId);
  323. break;
  324. case ServerMessageType.Expire: // The offer sent to a peer has expired without response.
  325. this.emitError(
  326. PeerErrorType.PeerUnavailable,
  327. `Could not connect to peer ${peerId}`,
  328. );
  329. break;
  330. case ServerMessageType.Offer: {
  331. // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  332. const connectionId = payload.connectionId;
  333. let connection = this.getConnection(peerId, connectionId);
  334. if (connection) {
  335. connection.close();
  336. logger.warn(
  337. `Offer received for existing Connection ID:${connectionId}`,
  338. );
  339. }
  340. // Create a new connection.
  341. if (payload.type === ConnectionType.Media) {
  342. const mediaConnection = new MediaConnection(peerId, this, {
  343. connectionId: connectionId,
  344. _payload: payload,
  345. metadata: payload.metadata,
  346. });
  347. connection = mediaConnection;
  348. this._addConnection(peerId, connection);
  349. this.emit("call", mediaConnection);
  350. } else if (payload.type === ConnectionType.Data) {
  351. const dataConnection = new DataConnection(peerId, this, {
  352. connectionId: connectionId,
  353. _payload: payload,
  354. metadata: payload.metadata,
  355. label: payload.label,
  356. serialization: payload.serialization,
  357. reliable: payload.reliable,
  358. });
  359. connection = dataConnection;
  360. this._addConnection(peerId, connection);
  361. this.emit("connection", dataConnection);
  362. } else {
  363. logger.warn(`Received malformed connection type:${payload.type}`);
  364. return;
  365. }
  366. // Find messages.
  367. const messages = this._getMessages(connectionId);
  368. for (const message of messages) {
  369. connection.handleMessage(message);
  370. }
  371. break;
  372. }
  373. default: {
  374. if (!payload) {
  375. logger.warn(
  376. `You received a malformed message from ${peerId} of type ${type}`,
  377. );
  378. return;
  379. }
  380. const connectionId = payload.connectionId;
  381. const connection = this.getConnection(peerId, connectionId);
  382. if (connection && connection.peerConnection) {
  383. // Pass it on.
  384. connection.handleMessage(message);
  385. } else if (connectionId) {
  386. // Store for possible later use
  387. this._storeMessage(connectionId, message);
  388. } else {
  389. logger.warn("You received an unrecognized message:", message);
  390. }
  391. break;
  392. }
  393. }
  394. }
  395. /** Stores messages without a set up connection, to be claimed later. */
  396. private _storeMessage(connectionId: string, message: ServerMessage): void {
  397. if (!this._lostMessages.has(connectionId)) {
  398. this._lostMessages.set(connectionId, []);
  399. }
  400. this._lostMessages.get(connectionId).push(message);
  401. }
  402. /** Retrieve messages from lost message store */
  403. //TODO Change it to private
  404. public _getMessages(connectionId: string): ServerMessage[] {
  405. const messages = this._lostMessages.get(connectionId);
  406. if (messages) {
  407. this._lostMessages.delete(connectionId);
  408. return messages;
  409. }
  410. return [];
  411. }
  412. /**
  413. * Connects to the remote peer specified by id and returns a data connection.
  414. * @param peer The brokering ID of the remote peer (their {@apilink Peer.id}).
  415. * @param options for specifying details about Peer Connection
  416. */
  417. connect(peer: string, options: PeerConnectOption = {}): DataConnection {
  418. if (this.disconnected) {
  419. logger.warn(
  420. "You cannot connect to a new Peer because you called " +
  421. ".disconnect() on this Peer and ended your connection with the " +
  422. "server. You can create a new Peer to reconnect, or call reconnect " +
  423. "on this peer if you believe its ID to still be available.",
  424. );
  425. this.emitError(
  426. PeerErrorType.Disconnected,
  427. "Cannot connect to new Peer after disconnecting from server.",
  428. );
  429. return;
  430. }
  431. const dataConnection = new DataConnection(peer, this, options);
  432. this._addConnection(peer, dataConnection);
  433. return dataConnection;
  434. }
  435. /**
  436. * Calls the remote peer specified by id and returns a media connection.
  437. * @param peer The brokering ID of the remote peer (their peer.id).
  438. * @param stream The caller's media stream
  439. * @param options Metadata associated with the connection, passed in by whoever initiated the connection.
  440. */
  441. call(
  442. peer: string,
  443. stream: MediaStream,
  444. options: CallOption = {},
  445. ): MediaConnection {
  446. if (this.disconnected) {
  447. logger.warn(
  448. "You cannot connect to a new Peer because you called " +
  449. ".disconnect() on this Peer and ended your connection with the " +
  450. "server. You can create a new Peer to reconnect.",
  451. );
  452. this.emitError(
  453. PeerErrorType.Disconnected,
  454. "Cannot connect to new Peer after disconnecting from server.",
  455. );
  456. return;
  457. }
  458. if (!stream) {
  459. logger.error(
  460. "To call a peer, you must provide a stream from your browser's `getUserMedia`.",
  461. );
  462. return;
  463. }
  464. const mediaConnection = new MediaConnection(peer, this, {
  465. ...options,
  466. _stream: stream,
  467. });
  468. this._addConnection(peer, mediaConnection);
  469. return mediaConnection;
  470. }
  471. /** Add a data/media connection to this peer. */
  472. private _addConnection(
  473. peerId: string,
  474. connection: MediaConnection | DataConnection,
  475. ): void {
  476. logger.log(
  477. `add connection ${connection.type}:${connection.connectionId} to peerId:${peerId}`,
  478. );
  479. if (!this._connections.has(peerId)) {
  480. this._connections.set(peerId, []);
  481. }
  482. this._connections.get(peerId).push(connection);
  483. }
  484. //TODO should be private
  485. _removeConnection(connection: DataConnection | MediaConnection): void {
  486. const connections = this._connections.get(connection.peer);
  487. if (connections) {
  488. const index = connections.indexOf(connection);
  489. if (index !== -1) {
  490. connections.splice(index, 1);
  491. }
  492. }
  493. //remove from lost messages
  494. this._lostMessages.delete(connection.connectionId);
  495. }
  496. /** Retrieve a data/media connection for this peer. */
  497. getConnection(
  498. peerId: string,
  499. connectionId: string,
  500. ): null | DataConnection | MediaConnection {
  501. const connections = this._connections.get(peerId);
  502. if (!connections) {
  503. return null;
  504. }
  505. for (const connection of connections) {
  506. if (connection.connectionId === connectionId) {
  507. return connection;
  508. }
  509. }
  510. return null;
  511. }
  512. private _delayedAbort(type: PeerErrorType, message: string | Error): void {
  513. setTimeout(() => {
  514. this._abort(type, message);
  515. }, 0);
  516. }
  517. /**
  518. * Emits an error message and destroys the Peer.
  519. * The Peer is not destroyed if it's in a disconnected state, in which case
  520. * it retains its disconnected state and its existing connections.
  521. */
  522. private _abort(type: PeerErrorType, message: string | Error): void {
  523. logger.error("Aborting!");
  524. this.emitError(type, message);
  525. if (!this._lastServerId) {
  526. this.destroy();
  527. } else {
  528. this.disconnect();
  529. }
  530. }
  531. /** Emits a typed error message. */
  532. emitError(type: PeerErrorType, err: string | Error): void {
  533. logger.error("Error:", err);
  534. this.emit("error", new PeerError(type, err));
  535. }
  536. /**
  537. * Destroys the Peer: closes all active connections as well as the connection
  538. * to the server.
  539. *
  540. * :::caution
  541. * This cannot be undone; the respective peer object will no longer be able
  542. * to create or receive any connections, its ID will be forfeited on the server,
  543. * and all of its data and media connections will be closed.
  544. * :::
  545. */
  546. destroy(): void {
  547. if (this.destroyed) {
  548. return;
  549. }
  550. logger.log(`Destroy peer with ID:${this.id}`);
  551. this.disconnect();
  552. this._cleanup();
  553. this._destroyed = true;
  554. this.emit("close");
  555. }
  556. /** Disconnects every connection on this peer. */
  557. private _cleanup(): void {
  558. for (const peerId of this._connections.keys()) {
  559. this._cleanupPeer(peerId);
  560. this._connections.delete(peerId);
  561. }
  562. this.socket.removeAllListeners();
  563. }
  564. /** Closes all connections to this peer. */
  565. private _cleanupPeer(peerId: string): void {
  566. const connections = this._connections.get(peerId);
  567. if (!connections) return;
  568. for (const connection of connections) {
  569. connection.close();
  570. }
  571. }
  572. /**
  573. * Disconnects the Peer's connection to the PeerServer. Does not close any
  574. * active connections.
  575. * Warning: The peer can no longer create or accept connections after being
  576. * disconnected. It also cannot reconnect to the server.
  577. */
  578. disconnect(): void {
  579. if (this.disconnected) {
  580. return;
  581. }
  582. const currentId = this.id;
  583. logger.log(`Disconnect peer with ID:${currentId}`);
  584. this._disconnected = true;
  585. this._open = false;
  586. this.socket.close();
  587. this._lastServerId = currentId;
  588. this._id = null;
  589. this.emit("disconnected", currentId);
  590. }
  591. /** Attempts to reconnect with the same ID.
  592. *
  593. * Only {@apilink Peer.disconnect | disconnected peers} can be reconnected.
  594. * Destroyed peers cannot be reconnected.
  595. * If the connection fails (as an example, if the peer's old ID is now taken),
  596. * the peer's existing connections will not close, but any associated errors events will fire.
  597. */
  598. reconnect(): void {
  599. if (this.disconnected && !this.destroyed) {
  600. logger.log(
  601. `Attempting reconnection to server with ID ${this._lastServerId}`,
  602. );
  603. this._disconnected = false;
  604. this._initialize(this._lastServerId!);
  605. } else if (this.destroyed) {
  606. throw new Error(
  607. "This peer cannot reconnect to the server. It has already been destroyed.",
  608. );
  609. } else if (!this.disconnected && !this.open) {
  610. // Do nothing. We're still connecting the first time.
  611. logger.error(
  612. "In a hurry? We're still trying to make the initial connection!",
  613. );
  614. } else {
  615. throw new Error(
  616. `Peer ${this.id} cannot reconnect because it is not disconnected from the server!`,
  617. );
  618. }
  619. }
  620. /**
  621. * Get a list of available peer IDs. If you're running your own server, you'll
  622. * want to set allow_discovery: true in the PeerServer options. If you're using
  623. * the cloud server, email team@peerjs.com to get the functionality enabled for
  624. * your key.
  625. */
  626. listAllPeers(cb = (_: any[]) => {}): void {
  627. this._api
  628. .listAllPeers()
  629. .then((peers) => cb(peers))
  630. .catch((error) => this._abort(PeerErrorType.ServerError, error));
  631. }
  632. }