peer.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  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. } 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. wsport: 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. this._options.wsport
  146. );
  147. const self = this;
  148. this.socket.on(SocketEventType.Message, data => {
  149. self._handleMessage(data);
  150. });
  151. this.socket.on(SocketEventType.Error, error => {
  152. self._abort(PeerErrorType.SocketError, error);
  153. });
  154. this.socket.on(SocketEventType.Disconnected, () => {
  155. // If we haven't explicitly disconnected, emit error and disconnect.
  156. if (!self.disconnected) {
  157. self.emitError(PeerErrorType.Network, "Lost connection to server.");
  158. self.disconnect();
  159. }
  160. });
  161. this.socket.on(SocketEventType.Close, function () {
  162. // If we haven't explicitly disconnected, emit error.
  163. if (!self.disconnected) {
  164. self._abort(
  165. PeerErrorType.SocketClosed,
  166. "Underlying socket is already closed."
  167. );
  168. }
  169. });
  170. }
  171. /** Initialize a connection with the server. */
  172. private _initialize(id: string): void {
  173. this._id = id;
  174. this.socket.start(this.id, this._options.token);
  175. }
  176. /** Handles messages from the server. */
  177. private _handleMessage(message: ServerMessage): void {
  178. const type = message.type;
  179. const payload = message.payload;
  180. const peerId = message.src;
  181. switch (type) {
  182. case "OPEN": // The connection to the server is open.
  183. this.emit(PeerEventType.Open, this.id);
  184. this._open = true;
  185. break;
  186. case "ERROR": // Server error.
  187. this._abort(PeerErrorType.ServerError, payload.msg);
  188. break;
  189. case "ID-TAKEN": // The selected ID is taken.
  190. this._abort(PeerErrorType.UnavailableID, `ID "${this.id}" is taken`);
  191. break;
  192. case "INVALID-KEY": // The given API key cannot be found.
  193. this._abort(
  194. PeerErrorType.InvalidKey,
  195. `API KEY "${this._options.key}" is invalid`
  196. );
  197. break;
  198. //
  199. case "LEAVE": // Another peer has closed its connection to this peer.
  200. util.log("Received leave message from", peerId);
  201. this._cleanupPeer(peerId);
  202. break;
  203. case "EXPIRE": // The offer sent to a peer has expired without response.
  204. this.emitError(
  205. PeerErrorType.PeerUnavailable,
  206. "Could not connect to peer " + peerId
  207. );
  208. break;
  209. case "OFFER": {
  210. // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  211. const connectionId = payload.connectionId;
  212. let connection = this.getConnection(peerId, connectionId);
  213. if (connection) {
  214. connection.close();
  215. util.warn("Offer received for existing Connection ID:", connectionId);
  216. }
  217. // Create a new connection.
  218. if (payload.type === ConnectionType.Media) {
  219. connection = new MediaConnection(peerId, this, {
  220. connectionId: connectionId,
  221. _payload: payload,
  222. metadata: payload.metadata
  223. });
  224. this._addConnection(peerId, connection);
  225. this.emit(PeerEventType.Call, connection);
  226. } else if (payload.type === ConnectionType.Data) {
  227. connection = new DataConnection(peerId, this, {
  228. connectionId: connectionId,
  229. _payload: payload,
  230. metadata: payload.metadata,
  231. label: payload.label,
  232. serialization: payload.serialization,
  233. reliable: payload.reliable
  234. });
  235. this._addConnection(peerId, connection);
  236. this.emit(PeerEventType.Connection, connection);
  237. } else {
  238. util.warn("Received malformed connection type:", payload.type);
  239. return;
  240. }
  241. // Find messages.
  242. const messages = this._getMessages(connectionId);
  243. for (let message of messages) {
  244. connection.handleMessage(message);
  245. }
  246. break;
  247. }
  248. default: {
  249. if (!payload) {
  250. util.warn(
  251. `You received a malformed message from ${peerId} of type ${type}`
  252. );
  253. return;
  254. }
  255. const connectionId = payload.connectionId;
  256. const connection = this.getConnection(peerId, connectionId);
  257. if (connection && connection.peerConnection) {
  258. // Pass it on.
  259. connection.handleMessage(message);
  260. } else if (connectionId) {
  261. // Store for possible later use
  262. this._storeMessage(connectionId, message);
  263. } else {
  264. util.warn("You received an unrecognized message:", message);
  265. }
  266. break;
  267. }
  268. }
  269. }
  270. /** Stores messages without a set up connection, to be claimed later. */
  271. private _storeMessage(connectionId: string, message: ServerMessage): void {
  272. if (!this._lostMessages.has(connectionId)) {
  273. this._lostMessages.set(connectionId, []);
  274. }
  275. this._lostMessages.get(connectionId).push(message);
  276. }
  277. /** Retrieve messages from lost message store */
  278. private _getMessages(connectionId: string): ServerMessage[] {
  279. const messages = this._lostMessages.get(connectionId);
  280. if (messages) {
  281. this._lostMessages.delete(connectionId);
  282. return messages;
  283. }
  284. return [];
  285. }
  286. /**
  287. * Returns a DataConnection to the specified peer. See documentation for a
  288. * complete list of options.
  289. */
  290. connect(peer: string, options?: PeerConnectOption): DataConnection {
  291. if (this.disconnected) {
  292. util.warn(
  293. "You cannot connect to a new Peer because you called " +
  294. ".disconnect() on this Peer and ended your connection with the " +
  295. "server. You can create a new Peer to reconnect, or call reconnect " +
  296. "on this peer if you believe its ID to still be available."
  297. );
  298. this.emitError(
  299. PeerErrorType.Disconnected,
  300. "Cannot connect to new Peer after disconnecting from server."
  301. );
  302. return;
  303. }
  304. const connection = new DataConnection(peer, this, options);
  305. this._addConnection(peer, connection);
  306. return connection;
  307. }
  308. /**
  309. * Returns a MediaConnection to the specified peer. See documentation for a
  310. * complete list of options.
  311. */
  312. call(peer: string, stream: MediaStream, options: any = {}): MediaConnection {
  313. if (this.disconnected) {
  314. util.warn(
  315. "You cannot connect to a new Peer because you called " +
  316. ".disconnect() on this Peer and ended your connection with the " +
  317. "server. You can create a new Peer to reconnect."
  318. );
  319. this.emitError(
  320. PeerErrorType.Disconnected,
  321. "Cannot connect to new Peer after disconnecting from server."
  322. );
  323. return;
  324. }
  325. if (!stream) {
  326. util.error(
  327. "To call a peer, you must provide a stream from your browser's `getUserMedia`."
  328. );
  329. return;
  330. }
  331. options._stream = stream;
  332. const call = new MediaConnection(peer, this, options);
  333. this._addConnection(peer, call);
  334. return call;
  335. }
  336. /** Add a data/media connection to this peer. */
  337. private _addConnection(peerId: string, connection: BaseConnection): void {
  338. util.log(
  339. `add connection ${connection.type}:${connection.connectionId}
  340. to peerId:${peerId}`
  341. );
  342. if (!this.connections.has(peerId)) {
  343. this.connections.set(peerId, []);
  344. }
  345. this.connections.get(peerId).push(connection);
  346. }
  347. /** Retrieve a data/media connection for this peer. */
  348. getConnection(peerId: string, connectionId: string): null | BaseConnection {
  349. const connections = this.connections.get(peerId);
  350. if (!connections) {
  351. return null;
  352. }
  353. for (let connection of connections) {
  354. if (connection.connectionId === connectionId) {
  355. return connection;
  356. }
  357. }
  358. return null;
  359. }
  360. private _delayedAbort(type: PeerErrorType, message): void {
  361. const self = this;
  362. util.setZeroTimeout(function () {
  363. self._abort(type, message);
  364. });
  365. }
  366. /**
  367. * Destroys the Peer and emits an error message.
  368. * The Peer is not destroyed if it's in a disconnected state, in which case
  369. * it retains its disconnected state and its existing connections.
  370. */
  371. private _abort(type: PeerErrorType, message): void {
  372. util.error("Aborting!");
  373. if (!this._lastServerId) {
  374. this.destroy();
  375. } else {
  376. this.disconnect();
  377. }
  378. this.emitError(type, message);
  379. }
  380. /** Emits a typed error message. */
  381. emitError(type: PeerErrorType, err): void {
  382. util.error("Error:", err);
  383. if (typeof err === "string") {
  384. err = new Error(err);
  385. }
  386. err.type = type;
  387. this.emit(PeerEventType.Error, err);
  388. }
  389. /**
  390. * Destroys the Peer: closes all active connections as well as the connection
  391. * to the server.
  392. * Warning: The peer can no longer create or accept connections after being
  393. * destroyed.
  394. */
  395. destroy(): void {
  396. if (!this.destroyed) {
  397. this._cleanup();
  398. this.disconnect();
  399. this._destroyed = true;
  400. }
  401. }
  402. /** Disconnects every connection on this peer. */
  403. private _cleanup(): void {
  404. for (let peerId of this.connections.keys()) {
  405. this._cleanupPeer(peerId);
  406. this.connections.delete(peerId);
  407. }
  408. this.emit(PeerEventType.Close);
  409. }
  410. /** Closes all connections to this peer. */
  411. private _cleanupPeer(peerId: string): void {
  412. const connections = this.connections.get(peerId);
  413. if (!connections) return;
  414. for (let connection of connections) {
  415. connection.close();
  416. }
  417. }
  418. /**
  419. * Disconnects the Peer's connection to the PeerServer. Does not close any
  420. * active connections.
  421. * Warning: The peer can no longer create or accept connections after being
  422. * disconnected. It also cannot reconnect to the server.
  423. */
  424. disconnect(): void {
  425. const self = this;
  426. util.setZeroTimeout(function () {
  427. if (!self.disconnected) {
  428. self._disconnected = true;
  429. self._open = false;
  430. if (self.socket) {
  431. self.socket.close();
  432. }
  433. self.emit(PeerEventType.Disconnected, self.id);
  434. self._lastServerId = self.id;
  435. self._id = null;
  436. }
  437. });
  438. }
  439. /** Attempts to reconnect with the same ID. */
  440. reconnect(): void {
  441. if (this.disconnected && !this.destroyed) {
  442. util.log(
  443. "Attempting reconnection to server with ID " + this._lastServerId
  444. );
  445. this._disconnected = false;
  446. this._initializeServerConnection();
  447. this._initialize(this._lastServerId);
  448. } else if (this.destroyed) {
  449. throw new Error(
  450. "This peer cannot reconnect to the server. It has already been destroyed."
  451. );
  452. } else if (!this.disconnected && !this.open) {
  453. // Do nothing. We're still connecting the first time.
  454. util.error(
  455. "In a hurry? We're still trying to make the initial connection!"
  456. );
  457. } else {
  458. throw new Error(
  459. "Peer " +
  460. this.id +
  461. " cannot reconnect because it is not disconnected from the server!"
  462. );
  463. }
  464. }
  465. /**
  466. * Get a list of available peer IDs. If you're running your own server, you'll
  467. * want to set allow_discovery: true in the PeerServer options. If you're using
  468. * the cloud server, email team@peerjs.com to get the functionality enabled for
  469. * your key.
  470. */
  471. listAllPeers(cb = (arg: any[]) => { }): void {
  472. this._api.listAllPeers()
  473. .then(peers => cb(peers))
  474. .catch(error => this._abort(PeerErrorType.ServerError, error));
  475. }
  476. }