peer.ts 16 KB

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