peer.ts 15 KB

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