peer.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 {
  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. Peer.prototype._retrieveId = function(cb) {
  81. var self = this;
  82. var http = new XMLHttpRequest();
  83. var protocol = this.options.secure ? 'https://' : 'http://';
  84. var url = protocol + this.options.host + ':' + this.options.port + '/' + this.options.key + '/id';
  85. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  86. url += queryString;
  87. // If there's no ID we need to wait for one before trying to init socket.
  88. http.open('get', url, true);
  89. http.onerror = function(e) {
  90. util.error('Error retrieving ID', e);
  91. self._abort('server-error', 'Could not get an ID from the server');
  92. }
  93. http.onreadystatechange = function() {
  94. if (http.readyState !== 4) {
  95. return;
  96. }
  97. if (http.status !== 200) {
  98. http.onerror();
  99. return;
  100. }
  101. self._initialize(http.responseText);
  102. };
  103. http.send(null);
  104. };
  105. Peer.prototype._initialize = function(id) {
  106. var self = this;
  107. this.id = id;
  108. this.socket = new Socket(this.options.secure, this.options.host, this.options.port, this.options.key, this.id);
  109. this.socket.on('server-message', function(data) {
  110. self._handleMessage(data);
  111. });
  112. this.socket.on('error', function(error) {
  113. self._abort('socket-error', error);
  114. });
  115. this.socket.on('close', function() {
  116. // TODO: What if we disconnected on purpose?
  117. self._abort('socket-closed', 'Underlying socket has closed');
  118. });
  119. this.socket.start();
  120. }
  121. /** Handles messages from the server. */
  122. Peer.prototype._handleMessage = function(message) {
  123. var type = message.type;
  124. var payload = message.payload
  125. switch (type) {
  126. case 'OPEN':
  127. this._processQueue();
  128. this.emit('open', this.id);
  129. break;
  130. case 'ERROR':
  131. this._abort('server-error', payload.msg);
  132. break;
  133. case 'ID-TAKEN':
  134. this._abort('unavailable-id', 'ID `' + this.id + '` is taken');
  135. break;
  136. case 'INVALID-KEY':
  137. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  138. break;
  139. case 'OFFER': // we should consider switching this to CALL/CONNECT, but this is the least breaking option.
  140. var peer = message.src;
  141. var id = message.id;
  142. var connection = this._getConnection(peer, id);
  143. if (connection) {
  144. // Pass it on
  145. connection.handleMessage(message);
  146. } else {
  147. // Create a new connection.
  148. if (payload.type === 'call') {
  149. var call = new MediaConnection(peer, {
  150. id: id,
  151. offer: offer,
  152. sdp: payload.sdp
  153. });
  154. this._addConnection(peer, call);
  155. this.emit('call', call);
  156. } else if (payload.type === 'connect') {
  157. var connection = new DataConnection(peer, {
  158. id: id,
  159. offer: offer,
  160. sdp: payload.sdp
  161. });
  162. this._addConnection(peer, connection);
  163. this.emit('connection', connection);
  164. } else {
  165. util.warn('Received malformed connection type.');
  166. }
  167. }
  168. break;
  169. default:
  170. var peer = message.src;
  171. var id = message.id;
  172. var connection = this._getConnection(peer, id);
  173. if (connection) {
  174. connection.handleMessage(message);
  175. } else {
  176. util.warn('You aborted your connection to ' + peer + ' before it opened.');
  177. }
  178. break;
  179. }
  180. }
  181. Peer.prototype.connect = function(peer, options) {
  182. var connection = new DataConnection(peer, options);
  183. this._addConnection(peer, connection);
  184. return connection;
  185. }
  186. Peer.prototype.call = function(peer, stream, options) {
  187. if (!stream) {
  188. util.error('To call a peer, you must provide a stream from your browser\'s `getUserMedia`.');
  189. return;
  190. }
  191. options.stream = stream;
  192. var call = new MediaConnection(peer, options);
  193. this._addConnection(peer, call);
  194. return call;
  195. }
  196. Peer.prototype._addConnection = function(peer, connection) {
  197. if (!this.connections[peer]) {
  198. this.connections[peer] = [];
  199. }
  200. this.connections[peer].push(connection);
  201. }
  202. Peer.prototype._getConnection = function(peer, id) {
  203. var connections = this.connections[peer];
  204. if (!connections) {
  205. return null;
  206. }
  207. for (var i = 0, ii = connections.length; i < ii; i++) {
  208. if (connections[i].id === id) {
  209. return connections[i];
  210. }
  211. }
  212. return null;
  213. }
  214. Peer.prototype._delayedAbort = function(type, message) {
  215. var self = this;
  216. util.setZeroTimeout(function(){
  217. self._abort(type, message);
  218. });
  219. }
  220. /** Destroys the Peer and emits an error message. */
  221. Peer.prototype._abort = function(type, message) {
  222. util.error('Aborting. Error:', message);
  223. var err = new Error(message);
  224. err.type = type;
  225. this.destroy();
  226. this.emit('error', err);
  227. };
  228. /**
  229. * Destroys the Peer: closes all active connections as well as the connection
  230. * to the server.
  231. * Warning: The peer can no longer create or accept connections after being
  232. * destroyed.
  233. */
  234. Peer.prototype.destroy = function() {
  235. if (!this.destroyed) {
  236. this._cleanup();
  237. this.disconnect();
  238. this.destroyed = true;
  239. }
  240. }
  241. /* Disconnects every connection on this peer. */
  242. Peer.prototype._cleanup = function() {
  243. var peers = Object.keys(this.connections);
  244. for (var i = 0, ii = peers.length; i < ii; i++) {
  245. var connections = this.connections[peers[i]];
  246. for (var j = 0, jj = connections; j < jj; j++) {
  247. connections[j].close();
  248. }
  249. }
  250. this.emit('close');
  251. }
  252. /**
  253. * Disconnects the Peer's connection to the PeerServer. Does not close any
  254. * active connections.
  255. * Warning: The peer can no longer create or accept connections after being
  256. * disconnected. It also cannot reconnect to the server.
  257. */
  258. Peer.prototype.disconnect = function() {
  259. var self = this;
  260. util.setZeroTimeout(function(){
  261. if (!self.disconnected) {
  262. if (self.socket) {
  263. self.socket.close();
  264. }
  265. self.id = null;
  266. self.disconnected = true;
  267. }
  268. });
  269. }
  270. /** The current browser. */
  271. // TODO: maybe expose util.supports
  272. Peer.browser = util.browserisms;
  273. exports.Peer = Peer;