peer.js 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  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. _id: 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 === 'connect') {
  173. var connection = new DataConnection(peer, this, {
  174. _id: 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.');
  185. }
  186. }
  187. break;
  188. default:
  189. var id = message.id;
  190. var connection = this.getConnection(peer, id);
  191. if (connection) {
  192. // Pass it on.
  193. connection.handleMessage(message);
  194. } else {
  195. util.warn('You aborted your connection to ' + peer + ' before it opened.');
  196. }
  197. break;
  198. }
  199. }
  200. /**
  201. * Returns a DataConnection to the specified peer. See documentation for a
  202. * complete list of options.
  203. */
  204. Peer.prototype.connect = function(peer, options) {
  205. var connection = new DataConnection(peer, this, options);
  206. this._addConnection(peer, connection);
  207. return connection;
  208. }
  209. /**
  210. * Returns a MediaConnection to the specified peer. See documentation for a
  211. * complete list of options.
  212. */
  213. Peer.prototype.call = function(peer, stream, options) {
  214. if (!stream) {
  215. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  216. return;
  217. }
  218. options._stream = stream;
  219. var call = new MediaConnection(peer, this, options);
  220. this._addConnection(peer, call);
  221. return call;
  222. }
  223. /** Add a data/media connection to this peer. */
  224. Peer.prototype._addConnection = function(peer, connection) {
  225. if (!this.connections[peer]) {
  226. this.connections[peer] = [];
  227. }
  228. this.connections[peer].push(connection);
  229. }
  230. /** Retrieve a data/media connection for this peer. */
  231. Peer.prototype.getConnection = function(peer, id) {
  232. var connections = this.connections[peer];
  233. if (!connections) {
  234. return null;
  235. }
  236. for (var i = 0, ii = connections.length; i < ii; i++) {
  237. if (connections[i].id === id) {
  238. return connections[i];
  239. }
  240. }
  241. return null;
  242. }
  243. Peer.prototype._delayedAbort = function(type, message) {
  244. var self = this;
  245. util.setZeroTimeout(function(){
  246. self._abort(type, message);
  247. });
  248. }
  249. /** Destroys the Peer and emits an error message. */
  250. Peer.prototype._abort = function(type, message) {
  251. util.error('Aborting. Error:', message);
  252. var err = new Error(message);
  253. err.type = type;
  254. this.destroy();
  255. this.emit('error', err);
  256. };
  257. /**
  258. * Destroys the Peer: closes all active connections as well as the connection
  259. * to the server.
  260. * Warning: The peer can no longer create or accept connections after being
  261. * destroyed.
  262. */
  263. Peer.prototype.destroy = function() {
  264. if (!this.destroyed) {
  265. this._cleanup();
  266. this.disconnect();
  267. this.destroyed = true;
  268. }
  269. }
  270. /** Disconnects every connection on this peer. */
  271. Peer.prototype._cleanup = function() {
  272. var peers = Object.keys(this.connections);
  273. for (var i = 0, ii = peers.length; i < ii; i++) {
  274. this._cleanupPeer(peers[i]);
  275. }
  276. this.emit('close');
  277. }
  278. /** Closes all connections to this peer. */
  279. Peer.prototype._cleanupPeer = function(peer) {
  280. var connections = this.connections[peer];
  281. for (var j = 0, jj = connections; j < jj; j += 1) {
  282. connections[j].close();
  283. }
  284. }
  285. /**
  286. * Disconnects the Peer's connection to the PeerServer. Does not close any
  287. * active connections.
  288. * Warning: The peer can no longer create or accept connections after being
  289. * disconnected. It also cannot reconnect to the server.
  290. */
  291. Peer.prototype.disconnect = function() {
  292. var self = this;
  293. util.setZeroTimeout(function(){
  294. if (!self.disconnected) {
  295. self.disconnected = true;
  296. self.open = false;
  297. if (self.socket) {
  298. self.socket.close();
  299. }
  300. self.id = null;
  301. }
  302. });
  303. }
  304. /** The current browser. */
  305. // TODO: maybe expose util.supports
  306. Peer.browser = util.browserisms;
  307. exports.Peer = Peer;