peer.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(id, options) {
  5. if (!(this instanceof Peer)) return new Peer(id, options);
  6. EventEmitter.call(this);
  7. // Deal with overloading
  8. if (id && id.constructor == Object) {
  9. options = id;
  10. id = undefined;
  11. } else if (id) {
  12. // Ensure id is a string
  13. id = id.toString();
  14. }
  15. //
  16. // Configurize options
  17. options = util.extend({
  18. debug: 0, // 1: Errors, 2: Warnings, 3: All logs
  19. host: util.CLOUD_HOST,
  20. port: util.CLOUD_PORT,
  21. key: 'peerjs',
  22. path: '/',
  23. token: util.randomToken(),
  24. config: util.defaultConfig
  25. }, options);
  26. this.options = options;
  27. // Detect relative URL host.
  28. if (options.host === '/') {
  29. options.host = window.location.hostname;
  30. }
  31. // Set path correctly.
  32. if (options.path[0] !== '/') {
  33. options.path = '/' + options.path;
  34. }
  35. if (options.path[options.path.length - 1] !== '/') {
  36. options.path += '/';
  37. }
  38. // Set whether we use SSL to same as current host
  39. if (options.secure === undefined && options.host !== util.CLOUD_HOST) {
  40. options.secure = util.isSecure();
  41. }
  42. // Set a custom log function if present
  43. if (options.logFunction) {
  44. util.setLogFunction(options.logFunction);
  45. }
  46. util.setLogLevel(options.debug);
  47. //
  48. // Sanity checks
  49. // Ensure WebRTC supported
  50. if (!util.supports.audioVideo && !util.supports.data ) {
  51. this._delayedAbort('browser-incompatible', 'The current browser does not support WebRTC');
  52. return;
  53. }
  54. // Ensure alphanumeric id
  55. if (!util.validateId(id)) {
  56. this._delayedAbort('invalid-id', 'ID "' + id + '" is invalid');
  57. return;
  58. }
  59. // Ensure valid key
  60. if (!util.validateKey(options.key)) {
  61. this._delayedAbort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  62. return;
  63. }
  64. // Ensure not using unsecure cloud server on SSL page
  65. if (options.secure && options.host === '0.peerjs.com') {
  66. this._delayedAbort('ssl-unavailable',
  67. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  68. return;
  69. }
  70. //
  71. // States.
  72. this.destroyed = false; // Connections have been killed
  73. this.disconnected = false; // Connection to PeerServer killed but P2P connections still active
  74. this.open = false; // Sockets and such are not yet open.
  75. //
  76. // References
  77. this.connections = {}; // DataConnections for this peer.
  78. this._lostMessages = {}; // src => [list of messages]
  79. //
  80. // Start the server connection
  81. this._initializeServerConnection();
  82. if (id) {
  83. this._initialize(id);
  84. } else {
  85. this._retrieveId();
  86. }
  87. //
  88. };
  89. util.inherits(Peer, EventEmitter);
  90. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  91. // websockets.)
  92. Peer.prototype._initializeServerConnection = function() {
  93. var self = this;
  94. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key);
  95. this.socket.on('message', function(data) {
  96. self._handleMessage(data);
  97. });
  98. this.socket.on('error', function(error) {
  99. self._abort('socket-error', error);
  100. });
  101. this.socket.on('close', function() {
  102. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  103. self._abort('socket-closed', 'Underlying socket is already closed.');
  104. }
  105. });
  106. };
  107. Peer.prototype.reconnect = function() {
  108. if (this.disconnected && !this.destroyed) {
  109. this._initializeServerConnection();
  110. this._initialize(this._lastServerId);
  111. } else if (this.destroyed) {
  112. throw new Error('This peer cannot reconnect to the server. It has already been destroyed.');
  113. } else if (!this.disconnected && !this.open) {
  114. // Do nothing. We're still connecting the first time.
  115. util.error('In a hurry? We\'re still trying to make the initial connection!');
  116. } else {
  117. throw new Error('Peer ' + this.id + ' cannot reconnect because it is not disconnected from the server!');
  118. }
  119. };
  120. /** Get a unique ID from the server via XHR. */
  121. Peer.prototype._retrieveId = function(cb) {
  122. var self = this;
  123. var http = new XMLHttpRequest();
  124. var protocol = this.options.secure ? 'https://' : 'http://';
  125. var url = protocol + this.options.host + ':' + this.options.port
  126. + this.options.path + this.options.key + '/id';
  127. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  128. url += queryString;
  129. // If there's no ID we need to wait for one before trying to init socket.
  130. http.open('get', url, true);
  131. http.onerror = function(e) {
  132. util.error('Error retrieving ID', e);
  133. var pathError = '';
  134. if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) {
  135. pathError = ' If you passed in a `path` to your self-hosted PeerServer, '
  136. + 'you\'ll also need to pass in that same path when creating a new'
  137. + ' Peer.';
  138. }
  139. self._abort('server-error', 'Could not get an ID from the server.' + pathError);
  140. }
  141. http.onreadystatechange = function() {
  142. if (http.readyState !== 4) {
  143. return;
  144. }
  145. if (http.status !== 200) {
  146. http.onerror();
  147. return;
  148. }
  149. self._initialize(http.responseText);
  150. };
  151. http.send(null);
  152. };
  153. /** Initialize a connection with the server. */
  154. Peer.prototype._initialize = function(id) {
  155. this.id = id;
  156. this.socket.start(this.id, this.options.token);
  157. }
  158. /** Handles messages from the server. */
  159. Peer.prototype._handleMessage = function(message) {
  160. var type = message.type;
  161. var payload = message.payload;
  162. var peer = message.src;
  163. switch (type) {
  164. case 'OPEN': // The connection to the server is open.
  165. this.emit('open', this.id);
  166. this.open = true;
  167. break;
  168. case 'ERROR': // Server error.
  169. this._abort('server-error', payload.msg);
  170. break;
  171. case 'ID-TAKEN': // The selected ID is taken.
  172. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  173. break;
  174. case 'INVALID-KEY': // The given API key cannot be found.
  175. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  176. break;
  177. //
  178. case 'LEAVE': // Another peer has closed its connection to this peer.
  179. util.log('Received leave message from', peer);
  180. this._cleanupPeer(peer);
  181. break;
  182. case 'EXPIRE': // The offer sent to a peer has expired without response.
  183. this.emitError('peer-unavailable', 'Could not connect to peer ' + peer);
  184. break;
  185. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  186. var connectionId = payload.connectionId;
  187. var connection = this.getConnection(peer, connectionId);
  188. if (connection) {
  189. util.warn('Offer received for existing Connection ID:', connectionId);
  190. //connection.handleMessage(message);
  191. } else {
  192. // Create a new connection.
  193. if (payload.type === 'media') {
  194. var connection = new MediaConnection(peer, this, {
  195. connectionId: connectionId,
  196. _payload: payload,
  197. metadata: payload.metadata
  198. });
  199. this._addConnection(peer, connection);
  200. this.emit('call', connection);
  201. } else if (payload.type === 'data') {
  202. connection = new DataConnection(peer, this, {
  203. connectionId: connectionId,
  204. _payload: payload,
  205. metadata: payload.metadata,
  206. label: payload.label,
  207. serialization: payload.serialization,
  208. reliable: payload.reliable
  209. });
  210. this._addConnection(peer, connection);
  211. this.emit('connection', connection);
  212. } else {
  213. util.warn('Received malformed connection type:', payload.type);
  214. return;
  215. }
  216. // Find messages.
  217. var messages = this._getMessages(connectionId);
  218. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  219. connection.handleMessage(messages[i]);
  220. }
  221. }
  222. break;
  223. default:
  224. if (!payload) {
  225. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  226. return;
  227. }
  228. var id = payload.connectionId;
  229. var connection = this.getConnection(peer, id);
  230. if (connection && connection.pc) {
  231. // Pass it on.
  232. connection.handleMessage(message);
  233. } else if (id) {
  234. // Store for possible later use
  235. this._storeMessage(id, message);
  236. } else {
  237. util.warn('You received an unrecognized message:', message);
  238. }
  239. break;
  240. }
  241. }
  242. /** Stores messages without a set up connection, to be claimed later. */
  243. Peer.prototype._storeMessage = function(connectionId, message) {
  244. if (!this._lostMessages[connectionId]) {
  245. this._lostMessages[connectionId] = [];
  246. }
  247. this._lostMessages[connectionId].push(message);
  248. }
  249. /** Retrieve messages from lost message store */
  250. Peer.prototype._getMessages = function(connectionId) {
  251. var messages = this._lostMessages[connectionId];
  252. if (messages) {
  253. delete this._lostMessages[connectionId];
  254. return messages;
  255. } else {
  256. return [];
  257. }
  258. }
  259. /**
  260. * Returns a DataConnection to the specified peer. See documentation for a
  261. * complete list of options.
  262. */
  263. Peer.prototype.connect = function(peer, options) {
  264. if (this.disconnected) {
  265. util.warn('You cannot connect to a new Peer because you called '
  266. + '.disconnect() on this Peer and ended your connection with the'
  267. + ' server. You can create a new Peer to reconnect.');
  268. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  269. return;
  270. }
  271. var connection = new DataConnection(peer, this, options);
  272. this._addConnection(peer, connection);
  273. return connection;
  274. }
  275. /**
  276. * Returns a MediaConnection to the specified peer. See documentation for a
  277. * complete list of options.
  278. */
  279. Peer.prototype.call = function(peer, stream, options) {
  280. if (this.disconnected) {
  281. util.warn('You cannot connect to a new Peer because you called '
  282. + '.disconnect() on this Peer and ended your connection with the'
  283. + ' server. You can create a new Peer to reconnect.');
  284. this.emitError('disconnected', 'Cannot connect to new Peer after disconnecting from server.');
  285. return;
  286. }
  287. if (!stream) {
  288. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  289. return;
  290. }
  291. options = options || {};
  292. options._stream = stream;
  293. var call = new MediaConnection(peer, this, options);
  294. this._addConnection(peer, call);
  295. return call;
  296. }
  297. /** Add a data/media connection to this peer. */
  298. Peer.prototype._addConnection = function(peer, connection) {
  299. if (!this.connections[peer]) {
  300. this.connections[peer] = [];
  301. }
  302. this.connections[peer].push(connection);
  303. }
  304. /** Retrieve a data/media connection for this peer. */
  305. Peer.prototype.getConnection = function(peer, id) {
  306. var connections = this.connections[peer];
  307. if (!connections) {
  308. return null;
  309. }
  310. for (var i = 0, ii = connections.length; i < ii; i++) {
  311. if (connections[i].id === id) {
  312. return connections[i];
  313. }
  314. }
  315. return null;
  316. }
  317. Peer.prototype._delayedAbort = function(type, message) {
  318. var self = this;
  319. util.setZeroTimeout(function(){
  320. self._abort(type, message);
  321. });
  322. }
  323. /** Destroys the Peer and emits an error message. */
  324. Peer.prototype._abort = function(type, message) {
  325. util.error('Aborting!');
  326. this.emitError(type, message);
  327. };
  328. /** Emits a typed error message. */
  329. Peer.prototype.emitError = function(type, err) {
  330. util.error('Error:', err);
  331. if (typeof err === 'string') {
  332. err = new Error(err);
  333. }
  334. err.type = type;
  335. this.emit('error', err);
  336. };
  337. /**
  338. * Destroys the Peer: closes all active connections as well as the connection
  339. * to the server.
  340. * Warning: The peer can no longer create or accept connections after being
  341. * destroyed.
  342. */
  343. Peer.prototype.destroy = function() {
  344. if (!this.destroyed) {
  345. this._cleanup();
  346. this.disconnect();
  347. this.destroyed = true;
  348. }
  349. }
  350. /** Disconnects every connection on this peer. */
  351. Peer.prototype._cleanup = function() {
  352. if (this.connections) {
  353. var peers = Object.keys(this.connections);
  354. for (var i = 0, ii = peers.length; i < ii; i++) {
  355. this._cleanupPeer(peers[i]);
  356. }
  357. }
  358. this.emit('close');
  359. }
  360. /** Closes all connections to this peer. */
  361. Peer.prototype._cleanupPeer = function(peer) {
  362. var connections = this.connections[peer];
  363. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  364. connections[j].close();
  365. }
  366. }
  367. /**
  368. * Disconnects the Peer's connection to the PeerServer. Does not close any
  369. * active connections.
  370. * Warning: The peer can no longer create or accept connections after being
  371. * disconnected. It also cannot reconnect to the server.
  372. */
  373. Peer.prototype.disconnect = function() {
  374. var self = this;
  375. util.setZeroTimeout(function(){
  376. if (!self.disconnected) {
  377. self.disconnected = true;
  378. self.open = false;
  379. if (self.socket) {
  380. self.socket.close();
  381. }
  382. self.emit('disconnected', self.id);
  383. self._lastServerId = self.id;
  384. self.id = null;
  385. }
  386. });
  387. }
  388. /**
  389. * Get a list of available peer IDs. If you're running your own server, you'll
  390. * want to set allow_discovery: true in the PeerServer options. If you're using
  391. * the cloud server, email team@peerjs.com to get the functionality enabled for
  392. * your key.
  393. */
  394. Peer.prototype.listAllPeers = function(cb) {
  395. cb = cb || function() {};
  396. var self = this;
  397. var http = new XMLHttpRequest();
  398. var protocol = this.options.secure ? 'https://' : 'http://';
  399. var url = protocol + this.options.host + ':' + this.options.port
  400. + this.options.path + this.options.key + '/peers';
  401. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  402. url += queryString;
  403. // If there's no ID we need to wait for one before trying to init socket.
  404. http.open('get', url, true);
  405. http.onerror = function(e) {
  406. self._abort('server-error', 'Could not get peers from the server.');
  407. cb([]);
  408. }
  409. http.onreadystatechange = function() {
  410. if (http.readyState !== 4) {
  411. return;
  412. }
  413. if (http.status === 401) {
  414. var helpfulError = '';
  415. if (self.options.host !== util.CLOUD_HOST) {
  416. helpfulError = 'It looks like you\'re using the cloud server. You can email '
  417. + 'team@peerjs.com to enable peer listing for your API key.';
  418. } else {
  419. helpfulError = 'You need to enable `allow_discovery` on your self-hosted'
  420. + ' PeerServer to use this feature.';
  421. }
  422. throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError);
  423. cb([]);
  424. } else if (http.status !== 200) {
  425. cb([]);
  426. } else {
  427. cb(JSON.parse(http.responseText));
  428. }
  429. };
  430. http.send(null);
  431. }
  432. exports.Peer = Peer;