peer.js 9.4 KB

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