peer.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  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: '0.peerjs.com',
  20. port: 9000,
  21. key: 'peerjs',
  22. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  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) {
  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. //
  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. // TODO: apparently using ://something.com gives relative protocol?
  101. var protocol = this.options.secure ? 'https://' : 'http://';
  102. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  103. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  104. url += queryString;
  105. // If there's no ID we need to wait for one before trying to init socket.
  106. http.open('get', url, true);
  107. http.onerror = function(e) {
  108. util.error('Error retrieving ID', e);
  109. self._abort('server-error', 'Could not get an ID from the server');
  110. }
  111. http.onreadystatechange = function() {
  112. if (http.readyState !== 4) {
  113. return;
  114. }
  115. if (http.status !== 200) {
  116. http.onerror();
  117. return;
  118. }
  119. self._initialize(http.responseText);
  120. };
  121. http.send(null);
  122. };
  123. /** Initialize a connection with the server. */
  124. Peer.prototype._initialize = function(id) {
  125. var self = this;
  126. this.id = id;
  127. this.socket.start(this.id);
  128. }
  129. /** Handles messages from the server. */
  130. Peer.prototype._handleMessage = function(message) {
  131. var type = message.type;
  132. var payload = message.payload;
  133. var peer = message.src;
  134. switch (type) {
  135. case 'OPEN': // The connection to the server is open.
  136. this.emit('open', this.id);
  137. this.open = true;
  138. break;
  139. case 'ERROR': // Server error.
  140. this._abort('server-error', payload.msg);
  141. break;
  142. case 'ID-TAKEN': // The selected ID is taken.
  143. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  144. break;
  145. case 'INVALID-KEY': // The given API key cannot be found.
  146. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  147. break;
  148. //
  149. case 'LEAVE': // Another peer has closed its connection to this peer.
  150. this._cleanupPeer(peer);
  151. break;
  152. case 'EXPIRE': // The offer sent to a peer has expired without response.
  153. // TODO: should this be on the DataConnection? It's currently here but I'm not so sure it belongs.
  154. this.emit('error', new Error('Could not connect to peer ' + peer));
  155. break;
  156. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  157. var connectionId = payload.connectionId;
  158. var connection = this.getConnection(peer, connectionId);
  159. if (connection) {
  160. util.warn('Offer received for existing Connection ID:', connectionId);
  161. //connection.handleMessage(message);
  162. } else {
  163. // Create a new connection.
  164. if (payload.type === 'call') {
  165. var call = new MediaConnection(peer, this, {
  166. connectionId: connectionId,
  167. _payload: payload, // A regular *Connection would have no payload.
  168. metadata: payload.metadata,
  169. });
  170. this._addConnection(peer, call);
  171. this.emit('call', call);
  172. } else if (payload.type === 'data') {
  173. var connection = new DataConnection(peer, this, {
  174. connectionId: connectionId,
  175. _payload: payload,
  176. metadata: payload.metadata,
  177. label: payload.label,
  178. serialization: payload.serialization,
  179. reliable: payload.reliable
  180. });
  181. this._addConnection(peer, connection);
  182. this.emit('connection', connection);
  183. } else {
  184. util.warn('Received malformed connection type:', payload.type);
  185. }
  186. }
  187. break;
  188. default:
  189. // TODO: if out of order, must queue.
  190. if (!payload) {
  191. util.warn('You received a malformed message from ' + peer);
  192. return;
  193. }
  194. var id = payload.connectionId;
  195. var connection = this.getConnection(peer, id);
  196. if (connection) {
  197. // Pass it on.
  198. connection.handleMessage(message);
  199. } else {
  200. util.warn('You aborted your connection to ' + peer + ' before it opened.');
  201. }
  202. break;
  203. }
  204. }
  205. /**
  206. * Returns a DataConnection to the specified peer. See documentation for a
  207. * complete list of options.
  208. */
  209. Peer.prototype.connect = function(peer, options) {
  210. var connection = new DataConnection(peer, this, options);
  211. this._addConnection(peer, connection);
  212. return connection;
  213. }
  214. /**
  215. * Returns a MediaConnection to the specified peer. See documentation for a
  216. * complete list of options.
  217. */
  218. Peer.prototype.call = function(peer, stream, options) {
  219. if (!stream) {
  220. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  221. return;
  222. }
  223. options._stream = stream;
  224. var call = new MediaConnection(peer, this, options);
  225. this._addConnection(peer, call);
  226. return call;
  227. }
  228. /** Add a data/media connection to this peer. */
  229. Peer.prototype._addConnection = function(peer, connection) {
  230. if (!this.connections[peer]) {
  231. this.connections[peer] = [];
  232. }
  233. this.connections[peer].push(connection);
  234. }
  235. /** Retrieve a data/media connection for this peer. */
  236. Peer.prototype.getConnection = function(peer, id) {
  237. var connections = this.connections[peer];
  238. if (!connections) {
  239. return null;
  240. }
  241. for (var i = 0, ii = connections.length; i < ii; i++) {
  242. if (connections[i].id === id) {
  243. return connections[i];
  244. }
  245. }
  246. return null;
  247. }
  248. Peer.prototype._delayedAbort = function(type, message) {
  249. var self = this;
  250. util.setZeroTimeout(function(){
  251. self._abort(type, message);
  252. });
  253. }
  254. /** Destroys the Peer and emits an error message. */
  255. Peer.prototype._abort = function(type, message) {
  256. util.error('Aborting. Error:', message);
  257. var err = new Error(message);
  258. err.type = type;
  259. this.destroy();
  260. this.emit('error', err);
  261. };
  262. /**
  263. * Destroys the Peer: closes all active connections as well as the connection
  264. * to the server.
  265. * Warning: The peer can no longer create or accept connections after being
  266. * destroyed.
  267. */
  268. Peer.prototype.destroy = function() {
  269. if (!this.destroyed) {
  270. this._cleanup();
  271. this.disconnect();
  272. this.destroyed = true;
  273. }
  274. }
  275. /** Disconnects every connection on this peer. */
  276. Peer.prototype._cleanup = function() {
  277. var peers = Object.keys(this.connections);
  278. for (var i = 0, ii = peers.length; i < ii; i++) {
  279. this._cleanupPeer(peers[i]);
  280. }
  281. this.emit('close');
  282. }
  283. /** Closes all connections to this peer. */
  284. Peer.prototype._cleanupPeer = function(peer) {
  285. var connections = this.connections[peer];
  286. for (var j = 0, jj = connections.length; j < jj; j += 1) {
  287. connections[j].close();
  288. }
  289. }
  290. /**
  291. * Disconnects the Peer's connection to the PeerServer. Does not close any
  292. * active connections.
  293. * Warning: The peer can no longer create or accept connections after being
  294. * disconnected. It also cannot reconnect to the server.
  295. */
  296. Peer.prototype.disconnect = function() {
  297. var self = this;
  298. util.setZeroTimeout(function(){
  299. if (!self.disconnected) {
  300. self.disconnected = true;
  301. self.open = false;
  302. if (self.socket) {
  303. self.socket.close();
  304. }
  305. self.id = null;
  306. }
  307. });
  308. }
  309. /** The current browser. */
  310. // TODO: maybe expose util.supports
  311. Peer.browser = util.browserisms;
  312. exports.Peer = Peer;