peer.ts 16 KB

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