peer.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. import { util } from "./util";
  2. import { EventEmitter } from "eventemitter3";
  3. import { Socket } from "./socket";
  4. import { MediaConnection } from "./mediaconnection";
  5. import { DataConnection } from "./dataconnection";
  6. import {
  7. ConnectionType,
  8. PeerErrorType,
  9. PeerEventType,
  10. SocketEventType,
  11. ServerMessageType
  12. } from "./enums";
  13. import { BaseConnection } from "./baseconnection";
  14. import { ServerMessage } from "./servermessage";
  15. import { PeerConnectOption, PeerJSOption } from "..";
  16. import { API } from "./api";
  17. class PeerOptions implements PeerJSOption {
  18. debug: number; // 1: Errors, 2: Warnings, 3: All logs
  19. host: string;
  20. port: number;
  21. path: string;
  22. key: string;
  23. token: string;
  24. config: any;
  25. secure: boolean;
  26. logFunction: any;
  27. }
  28. /**
  29. * A peer who can initiate connections with other peers.
  30. */
  31. export class Peer extends EventEmitter {
  32. private static readonly DEFAULT_KEY = "peerjs";
  33. private readonly _options: PeerOptions;
  34. private _id: string;
  35. private _lastServerId: string;
  36. private _api: API;
  37. // States.
  38. private _destroyed = false; // Connections have been killed
  39. private _disconnected = false; // Connection to PeerServer killed but P2P connections still active
  40. private _open = false; // Sockets and such are not yet open.
  41. private readonly _connections: Map<string, BaseConnection[]> = new Map(); // All connections for this peer.
  42. private readonly _lostMessages: Map<string, ServerMessage[]> = new Map(); // src => [list of messages]
  43. private _socket: Socket;
  44. get id() {
  45. return this._id;
  46. }
  47. get options() {
  48. return this._options;
  49. }
  50. get open() {
  51. return this._open;
  52. }
  53. get socket() {
  54. return this._socket;
  55. }
  56. /**
  57. * @deprecated
  58. * Return type will change from Object to Map<string,[]>
  59. */
  60. get connections(): Object {
  61. const plainConnections = Object.create(null);
  62. for (let [k, v] of this._connections) {
  63. plainConnections[k] = v;
  64. }
  65. return plainConnections;
  66. }
  67. get destroyed() {
  68. return this._destroyed;
  69. }
  70. get disconnected() {
  71. return this._disconnected;
  72. }
  73. constructor(id?: any, options?: PeerOptions) {
  74. super();
  75. // Deal with overloading
  76. if (id && id.constructor == Object) {
  77. options = id;
  78. id = undefined;
  79. } else if (id) {
  80. // Ensure id is a string
  81. id = id.toString();
  82. }
  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. util.setLogFunction(options.logFunction);
  116. }
  117. util.setLogLevel(String(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. );
  153. this.socket.on(SocketEventType.Message, data => {
  154. this._handleMessage(data);
  155. });
  156. this.socket.on(SocketEventType.Error, error => {
  157. this._abort(PeerErrorType.SocketError, error);
  158. });
  159. this.socket.on(SocketEventType.Disconnected, () => {
  160. // If we haven't explicitly disconnected, emit error and disconnect.
  161. if (!this.disconnected) {
  162. this.emitError(PeerErrorType.Network, "Lost connection to server.");
  163. this.disconnect();
  164. }
  165. });
  166. this.socket.on(SocketEventType.Close, () => {
  167. // If we haven't explicitly disconnected, emit error.
  168. if (!this.disconnected) {
  169. this._abort(
  170. PeerErrorType.SocketClosed,
  171. "Underlying socket is already closed."
  172. );
  173. }
  174. });
  175. }
  176. /** Initialize a connection with the server. */
  177. private _initialize(id: string): void {
  178. this._id = id;
  179. this.socket.start(this.id, this._options.token);
  180. }
  181. /** Handles messages from the server. */
  182. private _handleMessage(message: ServerMessage): void {
  183. const type = message.type;
  184. const payload = message.payload;
  185. const peerId = message.src;
  186. switch (type) {
  187. case ServerMessageType.Open: // The connection to the server is open.
  188. this.emit(PeerEventType.Open, this.id);
  189. this._open = true;
  190. break;
  191. case ServerMessageType.Error: // Server error.
  192. this._abort(PeerErrorType.ServerError, payload.msg);
  193. break;
  194. case ServerMessageType.IdTaken: // The selected ID is taken.
  195. this._abort(PeerErrorType.UnavailableID, `ID "${this.id}" is taken`);
  196. break;
  197. case ServerMessageType.InvalidKey: // The given API key cannot be found.
  198. this._abort(
  199. PeerErrorType.InvalidKey,
  200. `API KEY "${this._options.key}" is invalid`
  201. );
  202. break;
  203. case ServerMessageType.Leave: // Another peer has closed its connection to this peer.
  204. util.log("Received leave message from", peerId);
  205. this._cleanupPeer(peerId);
  206. this._connections.delete(peerId);
  207. break;
  208. case ServerMessageType.Expire: // The offer sent to a peer has expired without response.
  209. this.emitError(
  210. PeerErrorType.PeerUnavailable,
  211. "Could not connect to peer " + peerId
  212. );
  213. break;
  214. case ServerMessageType.Offer: {
  215. // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  216. const connectionId = payload.connectionId;
  217. let connection = this.getConnection(peerId, connectionId);
  218. if (connection) {
  219. connection.close();
  220. util.warn("Offer received for existing Connection ID:", connectionId);
  221. }
  222. // Create a new connection.
  223. if (payload.type === ConnectionType.Media) {
  224. connection = new MediaConnection(peerId, this, {
  225. connectionId: connectionId,
  226. _payload: payload,
  227. metadata: payload.metadata
  228. });
  229. this._addConnection(peerId, connection);
  230. this.emit(PeerEventType.Call, connection);
  231. } else if (payload.type === ConnectionType.Data) {
  232. connection = new DataConnection(peerId, this, {
  233. connectionId: connectionId,
  234. _payload: payload,
  235. metadata: payload.metadata,
  236. label: payload.label,
  237. serialization: payload.serialization,
  238. reliable: payload.reliable
  239. });
  240. this._addConnection(peerId, connection);
  241. this.emit(PeerEventType.Connection, connection);
  242. } else {
  243. util.warn("Received malformed connection type:", payload.type);
  244. return;
  245. }
  246. // Find messages.
  247. const messages = this._getMessages(connectionId);
  248. for (let message of messages) {
  249. connection.handleMessage(message);
  250. }
  251. break;
  252. }
  253. default: {
  254. if (!payload) {
  255. util.warn(
  256. `You received a malformed message from ${peerId} of type ${type}`
  257. );
  258. return;
  259. }
  260. const connectionId = payload.connectionId;
  261. const connection = this.getConnection(peerId, connectionId);
  262. if (connection && connection.peerConnection) {
  263. // Pass it on.
  264. connection.handleMessage(message);
  265. } else if (connectionId) {
  266. // Store for possible later use
  267. this._storeMessage(connectionId, message);
  268. } else {
  269. util.warn("You received an unrecognized message:", message);
  270. }
  271. break;
  272. }
  273. }
  274. }
  275. /** Stores messages without a set up connection, to be claimed later. */
  276. private _storeMessage(connectionId: string, message: ServerMessage): void {
  277. if (!this._lostMessages.has(connectionId)) {
  278. this._lostMessages.set(connectionId, []);
  279. }
  280. this._lostMessages.get(connectionId).push(message);
  281. }
  282. /** Retrieve messages from lost message store */
  283. //TODO Change it to private
  284. public _getMessages(connectionId: string): ServerMessage[] {
  285. const messages = this._lostMessages.get(connectionId);
  286. if (messages) {
  287. this._lostMessages.delete(connectionId);
  288. return messages;
  289. }
  290. return [];
  291. }
  292. /**
  293. * Returns a DataConnection to the specified peer. See documentation for a
  294. * complete list of options.
  295. */
  296. connect(peer: string, options?: PeerConnectOption): DataConnection {
  297. if (this.disconnected) {
  298. util.warn(
  299. "You cannot connect to a new Peer because you called " +
  300. ".disconnect() on this Peer and ended your connection with the " +
  301. "server. You can create a new Peer to reconnect, or call reconnect " +
  302. "on this peer if you believe its ID to still be available."
  303. );
  304. this.emitError(
  305. PeerErrorType.Disconnected,
  306. "Cannot connect to new Peer after disconnecting from server."
  307. );
  308. return;
  309. }
  310. const dataConnection = new DataConnection(peer, this, options);
  311. this._addConnection(peer, dataConnection);
  312. return dataConnection;
  313. }
  314. /**
  315. * Returns a MediaConnection to the specified peer. See documentation for a
  316. * complete list of options.
  317. */
  318. call(peer: string, stream: MediaStream, options: any = {}): MediaConnection {
  319. if (this.disconnected) {
  320. util.warn(
  321. "You cannot connect to a new Peer because you called " +
  322. ".disconnect() on this Peer and ended your connection with the " +
  323. "server. You can create a new Peer to reconnect."
  324. );
  325. this.emitError(
  326. PeerErrorType.Disconnected,
  327. "Cannot connect to new Peer after disconnecting from server."
  328. );
  329. return;
  330. }
  331. if (!stream) {
  332. util.error(
  333. "To call a peer, you must provide a stream from your browser's `getUserMedia`."
  334. );
  335. return;
  336. }
  337. options._stream = stream;
  338. const mediaConnection = new MediaConnection(peer, this, options);
  339. this._addConnection(peer, mediaConnection);
  340. return mediaConnection;
  341. }
  342. /** Add a data/media connection to this peer. */
  343. private _addConnection(peerId: string, connection: BaseConnection): void {
  344. util.log(
  345. `add connection ${connection.type}:${connection.connectionId}
  346. to peerId:${peerId}`
  347. );
  348. if (!this._connections.has(peerId)) {
  349. this._connections.set(peerId, []);
  350. }
  351. this._connections.get(peerId).push(connection);
  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): void {
  367. setTimeout(() => {
  368. this._abort(type, message);
  369. }, 0);
  370. }
  371. /**
  372. * Destroys the Peer and emits an error message.
  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): void {
  377. util.error("Aborting!");
  378. if (!this._lastServerId) {
  379. this.destroy();
  380. } else {
  381. this.disconnect();
  382. }
  383. this.emitError(type, message);
  384. }
  385. /** Emits a typed error message. */
  386. emitError(type: PeerErrorType, err): void {
  387. util.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. this._cleanup();
  403. this.disconnect();
  404. this._destroyed = true;
  405. }
  406. }
  407. /** Disconnects every connection on this peer. */
  408. private _cleanup(): void {
  409. for (let peerId of this._connections.keys()) {
  410. this._cleanupPeer(peerId);
  411. this._connections.delete(peerId);
  412. }
  413. this.emit(PeerEventType.Close);
  414. }
  415. /** Closes all connections to this peer. */
  416. private _cleanupPeer(peerId: string): void {
  417. const connections = this._connections.get(peerId);
  418. if (!connections) return;
  419. for (let connection of connections) {
  420. connection.close();
  421. }
  422. }
  423. /**
  424. * Disconnects the Peer's connection to the PeerServer. Does not close any
  425. * active connections.
  426. * Warning: The peer can no longer create or accept connections after being
  427. * disconnected. It also cannot reconnect to the server.
  428. */
  429. disconnect(): void {
  430. setTimeout(() => {
  431. if (!this.disconnected) {
  432. this._disconnected = true;
  433. this._open = false;
  434. if (this.socket) {
  435. this.socket.close();
  436. }
  437. this.emit(PeerEventType.Disconnected, this.id);
  438. this._lastServerId = this.id;
  439. this._id = null;
  440. }
  441. }, 0);
  442. }
  443. /** Attempts to reconnect with the same ID. */
  444. reconnect(): void {
  445. if (this.disconnected && !this.destroyed) {
  446. util.log(
  447. "Attempting reconnection to server with ID " + this._lastServerId
  448. );
  449. this._disconnected = false;
  450. this._initializeServerConnection();
  451. this._initialize(this._lastServerId);
  452. } else if (this.destroyed) {
  453. throw new Error(
  454. "This peer cannot reconnect to the server. It has already been destroyed."
  455. );
  456. } else if (!this.disconnected && !this.open) {
  457. // Do nothing. We're still connecting the first time.
  458. util.error(
  459. "In a hurry? We're still trying to make the initial connection!"
  460. );
  461. } else {
  462. throw new Error(
  463. "Peer " +
  464. this.id +
  465. " cannot reconnect because it is not disconnected from the server!"
  466. );
  467. }
  468. }
  469. /**
  470. * Get a list of available peer IDs. If you're running your own server, you'll
  471. * want to set allow_discovery: true in the PeerServer options. If you're using
  472. * the cloud server, email team@peerjs.com to get the functionality enabled for
  473. * your key.
  474. */
  475. listAllPeers(cb = (arg: any[]) => { }): void {
  476. this._api.listAllPeers()
  477. .then(peers => cb(peers))
  478. .catch(error => this._abort(PeerErrorType.ServerError, error));
  479. }
  480. }