peer.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. switch (type) {
  132. case 'OPEN':
  133. this._processQueue();
  134. this.emit('open', this.id);
  135. break;
  136. case 'ERROR':
  137. this._abort('server-error', payload.msg);
  138. break;
  139. case 'ID-TAKEN':
  140. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  141. break;
  142. case 'INVALID-KEY':
  143. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  144. break;
  145. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  146. var peer = message.src;
  147. var id = message.id;
  148. var connection = this._getConnection(peer, id);
  149. if (connection) {
  150. // Pass it on
  151. connection.handleMessage(message);
  152. } else {
  153. // Create a new connection.
  154. if (payload.type === 'call') {
  155. var call = new MediaConnection(peer, {
  156. id: id,
  157. offer: offer,
  158. sdp: payload.sdp
  159. });
  160. this._addConnection(peer, call);
  161. this.emit('call', call);
  162. } else if (payload.type === 'connect') {
  163. var connection = new DataConnection(peer, {
  164. id: id,
  165. offer: offer,
  166. sdp: payload.sdp,
  167. config: this.options.config
  168. });
  169. this._addConnection(peer, connection);
  170. this.emit('connection', connection);
  171. } else {
  172. util.warn('Received malformed connection type.');
  173. }
  174. }
  175. break;
  176. default:
  177. var peer = message.src;
  178. var id = message.id;
  179. var connection = this._getConnection(peer, id);
  180. if (connection) {
  181. connection.handleMessage(message);
  182. } else {
  183. util.warn('You aborted your connection to ' + peer + ' before it opened.');
  184. }
  185. break;
  186. }
  187. }
  188. Peer.prototype.connect = function(peer, options) {
  189. var connection = new DataConnection(peer, options);
  190. this._addConnection(peer, connection);
  191. return connection;
  192. }
  193. Peer.prototype.call = function(peer, stream, options) {
  194. if (!stream) {
  195. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  196. return;
  197. }
  198. options.stream = stream;
  199. var call = new MediaConnection(peer, options);
  200. this._addConnection(peer, call);
  201. return call;
  202. }
  203. Peer.prototype._addConnection = function(peer, connection) {
  204. if (!this.connections[peer]) {
  205. this.connections[peer] = [];
  206. }
  207. this.connections[peer].push(connection);
  208. }
  209. Peer.prototype._getConnection = function(peer, id) {
  210. var connections = this.connections[peer];
  211. if (!connections) {
  212. return null;
  213. }
  214. for (var i = 0, ii = connections.length; i < ii; i++) {
  215. if (connections[i].id === id) {
  216. return connections[i];
  217. }
  218. }
  219. return null;
  220. }
  221. Peer.prototype._delayedAbort = function(type, message) {
  222. var self = this;
  223. util.setZeroTimeout(function(){
  224. self._abort(type, message);
  225. });
  226. }
  227. /** Destroys the Peer and emits an error message. */
  228. Peer.prototype._abort = function(type, message) {
  229. util.error('Aborting. Error:', message);
  230. var err = new Error(message);
  231. err.type = type;
  232. this.destroy();
  233. this.emit('error', err);
  234. };
  235. /**
  236. * Destroys the Peer: closes all active connections as well as the connection
  237. * to the server.
  238. * Warning: The peer can no longer create or accept connections after being
  239. * destroyed.
  240. */
  241. Peer.prototype.destroy = function() {
  242. if (!this.destroyed) {
  243. this._cleanup();
  244. this.disconnect();
  245. this.destroyed = true;
  246. }
  247. }
  248. /* Disconnects every connection on this peer. */
  249. Peer.prototype._cleanup = function() {
  250. var peers = Object.keys(this.connections);
  251. for (var i = 0, ii = peers.length; i < ii; i++) {
  252. var connections = this.connections[peers[i]];
  253. for (var j = 0, jj = connections; j < jj; j++) {
  254. connections[j].close();
  255. }
  256. }
  257. this.emit('close');
  258. }
  259. /**
  260. * Disconnects the Peer's connection to the PeerServer. Does not close any
  261. * active connections.
  262. * Warning: The peer can no longer create or accept connections after being
  263. * disconnected. It also cannot reconnect to the server.
  264. */
  265. Peer.prototype.disconnect = function() {
  266. var self = this;
  267. util.setZeroTimeout(function(){
  268. if (!self.disconnected) {
  269. self.disconnected = true;
  270. if (self.socket) {
  271. self.socket.close();
  272. }
  273. self.id = null;
  274. }
  275. });
  276. }
  277. /** The current browser. */
  278. // TODO: maybe expose util.supports
  279. Peer.browser = util.browserisms;
  280. exports.Peer = Peer;