peer.js 9.9 KB

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