peer.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 + '/' + this._fullPath() + this.options.key + '/id';
  110. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  111. url += queryString;
  112. // If there's no ID we need to wait for one before trying to init socket.
  113. http.open('get', url, true);
  114. http.onerror = function(e) {
  115. util.error('Error retrieving ID', e);
  116. self._abort('server-error', 'Could not get an ID from the server');
  117. }
  118. http.onreadystatechange = function() {
  119. if (http.readyState !== 4) {
  120. return;
  121. }
  122. if (http.status !== 200) {
  123. http.onerror();
  124. return;
  125. }
  126. self._initialize(http.responseText);
  127. };
  128. http.send(null);
  129. };
  130. /** Initialize a connection with the server. */
  131. Peer.prototype._initialize = function(id) {
  132. var self = this;
  133. this.id = id;
  134. this.socket.start(this.id);
  135. }
  136. /** Handles messages from the server. */
  137. Peer.prototype._handleMessage = function(message) {
  138. var type = message.type;
  139. var payload = message.payload;
  140. var peer = message.src;
  141. switch (type) {
  142. case 'OPEN': // The connection to the server is open.
  143. this.emit('open', this.id);
  144. this.open = true;
  145. break;
  146. case 'ERROR': // Server error.
  147. this._abort('server-error', payload.msg);
  148. break;
  149. case 'ID-TAKEN': // The selected ID is taken.
  150. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  151. break;
  152. case 'INVALID-KEY': // The given API key cannot be found.
  153. this._abort('invalid-key', 'API KEY "' + this.options.key + '" is invalid');
  154. break;
  155. //
  156. case 'LEAVE': // Another peer has closed its connection to this peer.
  157. util.log('Received leave message from', peer);
  158. this._cleanupPeer(peer);
  159. break;
  160. case 'EXPIRE': // The offer sent to a peer has expired without response.
  161. this.emit('error', new Error('Could not connect to peer ' + peer));
  162. break;
  163. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  164. var connectionId = payload.connectionId;
  165. var connection = this.getConnection(peer, connectionId);
  166. if (connection) {
  167. util.warn('Offer received for existing Connection ID:', connectionId);
  168. //connection.handleMessage(message);
  169. } else {
  170. // Create a new connection.
  171. if (payload.type === 'media') {
  172. var connection = new MediaConnection(peer, this, {
  173. connectionId: connectionId,
  174. _payload: payload,
  175. metadata: payload.metadata
  176. });
  177. this._addConnection(peer, connection);
  178. this.emit('call', connection);
  179. } else if (payload.type === 'data') {
  180. connection = new DataConnection(peer, this, {
  181. connectionId: connectionId,
  182. _payload: payload,
  183. metadata: payload.metadata,
  184. label: payload.label,
  185. serialization: payload.serialization,
  186. reliable: payload.reliable
  187. });
  188. this._addConnection(peer, connection);
  189. this.emit('connection', connection);
  190. } else {
  191. util.warn('Received malformed connection type:', payload.type);
  192. return;
  193. }
  194. // Find messages.
  195. var messages = this._getMessages(connectionId);
  196. for (var i = 0, ii = messages.length; i < ii; i += 1) {
  197. connection.handleMessage(messages[i]);
  198. }
  199. }
  200. break;
  201. default:
  202. if (!payload) {
  203. util.warn('You received a malformed message from ' + peer + ' of type ' + type);
  204. return;
  205. }
  206. var id = payload.connectionId;
  207. var connection = this.getConnection(peer, id);
  208. if (connection && connection.pc) {
  209. // Pass it on.
  210. connection.handleMessage(message);
  211. } else if (id) {
  212. // Store for possible later use
  213. this._storeMessage(id, message);
  214. } else {
  215. util.warn('You received an unrecognized message:', message);
  216. }
  217. break;
  218. }
  219. }
  220. Peer.prototype._fullPath = function() {
  221. return this.options.path ? this.options.path + '/' : '';
  222. }
  223. /** Stores messages without a set up connection, to be claimed later. */
  224. Peer.prototype._storeMessage = function(connectionId, message) {
  225. if (!this._lostMessages[connectionId]) {
  226. this._lostMessages[connectionId] = [];
  227. }
  228. this._lostMessages[connectionId].push(message);
  229. }
  230. /** Retrieve messages from lost message store */
  231. Peer.prototype._getMessages = function(connectionId) {
  232. var messages = this._lostMessages[connectionId];
  233. if (messages) {
  234. delete this._lostMessages[connectionId];
  235. return messages;
  236. } else {
  237. return [];
  238. }
  239. }
  240. /**
  241. * Returns a DataConnection to the specified peer. See documentation for a
  242. * complete list of options.
  243. */
  244. Peer.prototype.connect = function(peer, options) {
  245. if (this.disconnected) {
  246. util.warn('You cannot connect to a new Peer because you called '
  247. + '.disconnect() on this Peer and ended your connection with the'
  248. + ' server. You can create a new Peer to reconnect.');
  249. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  250. return;
  251. }
  252. var connection = new DataConnection(peer, this, options);
  253. this._addConnection(peer, connection);
  254. return connection;
  255. }
  256. /**
  257. * Returns a MediaConnection to the specified peer. See documentation for a
  258. * complete list of options.
  259. */
  260. Peer.prototype.call = function(peer, stream, options) {
  261. if (this.disconnected) {
  262. util.warn('You cannot connect to a new Peer because you called '
  263. + '.disconnect() on this Peer and ended your connection with the'
  264. + ' server. You can create a new Peer to reconnect.');
  265. this.emit('error', new Error('Cannot connect to new Peer after disconnecting from server.'));
  266. return;
  267. }
  268. if (!stream) {
  269. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  270. return;
  271. }
  272. options = options || {};
  273. options._stream = stream;
  274. var call = new MediaConnection(peer, this, options);
  275. this._addConnection(peer, call);
  276. return call;
  277. }
  278. /** Add a data/media connection to this peer. */
  279. Peer.prototype._addConnection = function(peer, connection) {
  280. if (!this.connections[peer]) {
  281. this.connections[peer] = [];
  282. }
  283. this.connections[peer].push(connection);
  284. }
  285. /** Retrieve a data/media connection for this peer. */
  286. Peer.prototype.getConnection = function(peer, id) {
  287. var connections = this.connections[peer];
  288. if (!connections) {
  289. return null;
  290. }
  291. for (var i = 0, ii = connections.length; i < ii; i++) {
  292. if (connections[i].id === id) {
  293. return connections[i];
  294. }
  295. }
  296. return null;
  297. }
  298. Peer.prototype._delayedAbort = function(type, message) {
  299. var self = this;
  300. util.setZeroTimeout(function(){
  301. self._abort(type, message);
  302. });
  303. }
  304. /** Destroys the Peer and emits an error message. */
  305. Peer.prototype._abort = function(type, message) {
  306. util.error('Aborting. Error:', message);
  307. var err = new Error(message);
  308. err.type = type;
  309. this.destroy();
  310. this.emit('error', err);
  311. };
  312. /**
  313. * Destroys the Peer: closes all active connections as well as the connection
  314. * to the server.
  315. * Warning: The peer can no longer create or accept connections after being
  316. * destroyed.
  317. */
  318. Peer.prototype.destroy = function() {
  319. if (!this.destroyed) {
  320. this._cleanup();
  321. this.disconnect();
  322. this.destroyed = true;
  323. }
  324. }
  325. /** Disconnects every connection on this peer. */
  326. Peer.prototype._cleanup = function() {
  327. if (this.connections) {
  328. var peers = Object.keys(this.connections);
  329. for (var i = 0, ii = peers.length; i < ii; i++) {
  330. this._cleanupPeer(peers[i]);
  331. }
  332. }
  333. this.emit('close');
  334. }
  335. /** Closes all connections to this peer. */
  336. Peer.prototype._cleanupPeer = function(peer) {
  337. var connections = this.connections[peer];
  338. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  339. connections[j].close();
  340. }
  341. }
  342. /**
  343. * Disconnects the Peer's connection to the PeerServer. Does not close any
  344. * active connections.
  345. * Warning: The peer can no longer create or accept connections after being
  346. * disconnected. It also cannot reconnect to the server.
  347. */
  348. Peer.prototype.disconnect = function() {
  349. var self = this;
  350. util.setZeroTimeout(function(){
  351. if (!self.disconnected) {
  352. self.disconnected = true;
  353. self.open = false;
  354. if (self.socket) {
  355. self.socket.close();
  356. }
  357. self.id = null;
  358. }
  359. });
  360. }
  361. exports.Peer = Peer;