peer.ts 20 KB

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