peer.ts 15 KB

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