peer.js 11 KB

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