peer.ts 17 KB

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