peer.ts 20 KB

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