peer.js 11 KB

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