peer.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 manually 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. // Initialize the 'socket' (which is actually a mix of XHR streaming and
  81. // websockets.)
  82. var self = this;
  83. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.path, this.options.key);
  84. this.socket.on('message', function(data) {
  85. self._handleMessage(data);
  86. });
  87. this.socket.on('error', function(error) {
  88. self._abort('socket-error', error);
  89. });
  90. this.socket.on('close', function() {
  91. if (!self.disconnected) { // If we haven't explicitly disconnected, emit error.
  92. self._abort('socket-closed', 'Underlying socket is already closed.');
  93. }
  94. });
  95. //
  96. // Start the connections
  97. if (id) {
  98. this._initialize(id);
  99. } else {
  100. this._retrieveId();
  101. }
  102. //
  103. };
  104. util.inherits(Peer, EventEmitter);
  105. /** Get a unique ID from the server via XHR. */
  106. Peer.prototype._retrieveId = function(cb) {
  107. var self = this;
  108. var http = new XMLHttpRequest();
  109. var protocol = this.options.secure ? 'https://' : 'http://';
  110. var url = protocol + this.options.host + ':' + this.options.port
  111. + this.options.path + this.options.key + '/id';
  112. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  113. url += queryString;
  114. // If there's no ID we need to wait for one before trying to init socket.
  115. http.open('get', url, true);
  116. http.onerror = function(e) {
  117. util.error('Error retrieving ID', e);
  118. var pathError = '';
  119. if (self.options.path === '/' && self.options.host !== util.CLOUD_HOST) {
  120. pathError = ' If you passed in a `path` to your self-hosted PeerServer, '
  121. + 'you\'ll also need to pass in that same path when creating a new'
  122. + ' Peer.';
  123. }
  124. self._abort('server-error', 'Could not get an ID from the server.' + pathError);
  125. }
  126. http.onreadystatechange = function() {
  127. if (http.readyState !== 4) {
  128. return;
  129. }
  130. if (http.status !== 200) {
  131. http.onerror();
  132. return;
  133. }
  134. self._initialize(http.responseText);
  135. };
  136. http.send(null);
  137. };
  138. /** Initialize a connection with the server. */
  139. Peer.prototype._initialize = function(id) {
  140. var self = this;
  141. this.id = id;
  142. this.socket.start(this.id, this.options.token);
  143. }
  144. /** Handles messages from the server. */
  145. Peer.prototype._handleMessage = function(message) {
  146. var type = message.type;
  147. var payload = message.payload;
  148. var peer = message.src;
  149. switch (type) {
  150. case 'OPEN': // The connection to the server is open.
  151. this.emit('open', this.id);
  152. this.open = true;
  153. break;
  154. case 'ERROR': // Server error.
  155. this._abort('server-error', payload.msg);
  156. break;
  157. case 'ID-TAKEN': // The selected ID is taken.
  158. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  159. break;
  160. case 'INVALID-KEY': // The given API key cannot be found.
  161. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  162. break;
  163. //
  164. case 'LEAVE': // Another peer has closed its connection to this peer.
  165. util.log('Received leave message from', peer);
  166. this._cleanupPeer(peer);
  167. break;
  168. case 'EXPIRE': // The offer sent to a peer has expired without response.
  169. this.emit('error', new Error('Could not connect to peer ' + peer));
  170. break;
  171. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  172. var connectionId = payload.connectionId;
  173. var connection = this.getConnection(peer, connectionId);
  174. if (connection) {
  175. util.warn('Offer received for existing Connection ID:', connectionId);
  176. //connection.handleMessage(message);
  177. } else {
  178. // Create a new connection.
  179. if (payload.type === 'media') {
  180. var connection = new MediaConnection(peer, this, {
  181. connectionId: connectionId,
  182. _payload: payload,
  183. metadata: payload.metadata
  184. });
  185. this._addConnection(peer, connection);
  186. this.emit('call', connection);
  187. } else if (payload.type === 'data') {
  188. connection = new DataConnection(peer, this, {
  189. connectionId: connectionId,
  190. _payload: payload,
  191. metadata: payload.metadata,
  192. label: payload.label,
  193. serialization: payload.serialization,
  194. reliable: payload.reliable
  195. });
  196. this._addConnection(peer, connection);
  197. this.emit('connection', connection);
  198. } else {
  199. util.warn('Received malformed connection type:', payload.type);
  200. return;
  201. }
  202. // Find messages.
  203. var messages = this._getMessages(connectionId);
  204. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  205. connection.handleMessage(messages[i]);
  206. }
  207. }
  208. break;
  209. default:
  210. if (!payload) {
  211. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  212. return;
  213. }
  214. var id = payload.connectionId;
  215. var connection = this.getConnection(peer, id);
  216. if (connection && connection.pc) {
  217. // Pass it on.
  218. connection.handleMessage(message);
  219. } else if (id) {
  220. // Store for possible later use
  221. this._storeMessage(id, message);
  222. } else {
  223. util.warn('You received an unrecognized message:', message);
  224. }
  225. break;
  226. }
  227. }
  228. /** Stores messages without a set up connection, to be claimed later. */
  229. Peer.prototype._storeMessage = function(connectionId, message) {
  230. if (!this._lostMessages[connectionId]) {
  231. this._lostMessages[connectionId] = [];
  232. }
  233. this._lostMessages[connectionId].push(message);
  234. }
  235. /** Retrieve messages from lost message store */
  236. Peer.prototype._getMessages = function(connectionId) {
  237. var messages = this._lostMessages[connectionId];
  238. if (messages) {
  239. delete this._lostMessages[connectionId];
  240. return messages;
  241. } else {
  242. return [];
  243. }
  244. }
  245. /**
  246. * Returns a DataConnection to the specified peer. See documentation for a
  247. * complete list of options.
  248. */
  249. Peer.prototype.connect = function(peer, options) {
  250. if (this.disconnected) {
  251. util.warn('You cannot connect to a new Peer because you called '
  252. + '.disconnect() on this Peer and ended your connection with the'
  253. + ' server. You can create a new Peer to reconnect.');
  254. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  255. return;
  256. }
  257. var connection = new DataConnection(peer, this, options);
  258. this._addConnection(peer, connection);
  259. return connection;
  260. }
  261. /**
  262. * Returns a MediaConnection to the specified peer. See documentation for a
  263. * complete list of options.
  264. */
  265. Peer.prototype.call = function(peer, stream, options) {
  266. if (this.disconnected) {
  267. util.warn('You cannot connect to a new Peer because you called '
  268. + '.disconnect() on this Peer and ended your connection with the'
  269. + ' server. You can create a new Peer to reconnect.');
  270. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  271. return;
  272. }
  273. if (!stream) {
  274. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  275. return;
  276. }
  277. options = options || {};
  278. options._stream = stream;
  279. var call = new MediaConnection(peer, this, options);
  280. this._addConnection(peer, call);
  281. return call;
  282. }
  283. /** Add a data/media connection to this peer. */
  284. Peer.prototype._addConnection = function(peer, connection) {
  285. if (!this.connections[peer]) {
  286. this.connections[peer] = [];
  287. }
  288. this.connections[peer].push(connection);
  289. }
  290. /** Retrieve a data/media connection for this peer. */
  291. Peer.prototype.getConnection = function(peer, id) {
  292. var connections = this.connections[peer];
  293. if (!connections) {
  294. return null;
  295. }
  296. for (var i = 0, ii = connections.length; i < ii; i++) {
  297. if (connections[i].id === id) {
  298. return connections[i];
  299. }
  300. }
  301. return null;
  302. }
  303. Peer.prototype._delayedAbort = function(type, message) {
  304. var self = this;
  305. util.setZeroTimeout(function(){
  306. self._abort(type, message);
  307. });
  308. }
  309. /** Destroys the Peer and emits an error message. */
  310. Peer.prototype._abort = function(type, message) {
  311. util.error('Aborting. Error:', message);
  312. var err = new Error(message);
  313. err.type = type;
  314. this.destroy();
  315. this.emit('error', err);
  316. };
  317. /**
  318. * Destroys the Peer: closes all active connections as well as the connection
  319. * to the server.
  320. * Warning: The peer can no longer create or accept connections after being
  321. * destroyed.
  322. */
  323. Peer.prototype.destroy = function() {
  324. if (!this.destroyed) {
  325. this._cleanup();
  326. this.disconnect();
  327. this.destroyed = true;
  328. }
  329. }
  330. /** Disconnects every connection on this peer. */
  331. Peer.prototype._cleanup = function() {
  332. if (this.connections) {
  333. var peers = Object.keys(this.connections);
  334. for (var i = 0, ii = peers.length; i < ii; i++) {
  335. this._cleanupPeer(peers[i]);
  336. }
  337. }
  338. this.emit('close');
  339. }
  340. /** Closes all connections to this peer. */
  341. Peer.prototype._cleanupPeer = function(peer) {
  342. var connections = this.connections[peer];
  343. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  344. connections[j].close();
  345. }
  346. }
  347. /**
  348. * Disconnects the Peer's connection to the PeerServer. Does not close any
  349. * active connections.
  350. * Warning: The peer can no longer create or accept connections after being
  351. * disconnected. It also cannot reconnect to the server.
  352. */
  353. Peer.prototype.disconnect = function() {
  354. var self = this;
  355. util.setZeroTimeout(function(){
  356. if (!self.disconnected) {
  357. self.disconnected = true;
  358. self.open = false;
  359. if (self.socket) {
  360. self.socket.close();
  361. }
  362. self.id = null;
  363. }
  364. });
  365. }
  366. /**
  367. * Get a list of available peer IDs. If you're running your own server, you'll
  368. * want to set allow_discovery: true in the PeerServer options. If you're using
  369. * the cloud server, email team@peerjs.com to get the functionality enabled for
  370. * your key.
  371. */
  372. Peer.prototype.listAllPeers = function(cb) {
  373. cb = cb || function() {};
  374. var self = this;
  375. var http = new XMLHttpRequest();
  376. var protocol = this.options.secure ? 'https://' : 'http://';
  377. var url = protocol + this.options.host + ':' + this.options.port
  378. + this.options.path + this.options.key + '/peers';
  379. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  380. url += queryString;
  381. // If there's no ID we need to wait for one before trying to init socket.
  382. http.open('get', url, true);
  383. http.onerror = function(e) {
  384. self._abort('server-error', 'Could not get peers from the server.');
  385. cb([]);
  386. }
  387. http.onreadystatechange = function() {
  388. if (http.readyState !== 4) {
  389. return;
  390. }
  391. if (http.status === 401) {
  392. var helpfulError = '';
  393. if (self.options.host !== util.CLOUD_HOST) {
  394. helpfulError = 'It looks like you\'re using the cloud server. You can email '
  395. + 'team@peerjs.com to enable peer listing for your API key.';
  396. } else {
  397. helpfulError = 'You need to enable `allow_discovery` on your self-hosted'
  398. + ' PeerServer to use this feature.';
  399. }
  400. throw new Error('It doesn\'t look like you have permission to list peers IDs. ' + helpfulError);
  401. cb([]);
  402. } else if (http.status !== 200) {
  403. cb([]);
  404. } else {
  405. cb(JSON.parse(http.responseText));
  406. }
  407. };
  408. http.send(null);
  409. }
  410. exports.Peer = Peer;