peer.js 13 KB

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