peer.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(id, options) {
  5. if (id && id.constructor == Object) {
  6. options = id;
  7. id = undefined;
  8. }
  9. if (!(this instanceof Peer)) return new Peer(id, options);
  10. EventEmitter.call(this);
  11. options = util.extend({
  12. debug: false,
  13. host: '0.peerjs.com',
  14. port: 9000,
  15. key: 'peerjs',
  16. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  17. }, options);
  18. this._options = options;
  19. util.debug = options.debug;
  20. // First check if browser can use PeerConnection/DataChannels.
  21. // TODO: when media is supported, lower browser version limit and move DC
  22. // check to where`connect` is called.
  23. var self = this;
  24. if (!util.isBrowserCompatible()) {
  25. util.setZeroTimeout(function() {
  26. self._abort('browser-incompatible', 'The current browser does not support WebRTC DataChannels');
  27. });
  28. return;
  29. }
  30. // Detect relative URL host.
  31. if (options.host === '/') {
  32. options.host = window.location.hostname;
  33. }
  34. // Ensure alphanumeric_-
  35. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  36. util.setZeroTimeout(function() {
  37. self._abort('invalid-id', 'ID "' + id + '" is invalid');
  38. });
  39. return;
  40. }
  41. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  42. util.setZeroTimeout(function() {
  43. self._abort('invalid-key', 'API KEY "' + options.key + '" is invalid');
  44. });
  45. return;
  46. }
  47. this._secure = util.isSecure();
  48. // Errors for now because no support for SSL on cloud server.
  49. if (this._secure && options.host === '0.peerjs.com') {
  50. util.setZeroTimeout(function() {
  51. self._abort('ssl-unavailable',
  52. 'The cloud server currently does not support HTTPS. Please run your own PeerServer to use HTTPS.');
  53. });
  54. return;
  55. }
  56. // States.
  57. this.destroyed = false;
  58. this.disconnected = false;
  59. // Connections for this peer.
  60. this.connections = {};
  61. // Connection managers.
  62. this.managers = {};
  63. // Queued connections to make.
  64. this._queued = [];
  65. // Init immediately if ID is given, otherwise ask server for ID
  66. if (id) {
  67. this.id = id;
  68. this._init();
  69. } else {
  70. this.id = null;
  71. this._retrieveId();
  72. }
  73. };
  74. util.inherits(Peer, EventEmitter);
  75. Peer.prototype._retrieveId = function(cb) {
  76. var self = this;
  77. try {
  78. var http = new XMLHttpRequest();
  79. var protocol = this._secure ? 'https://' : 'http://';
  80. var url = protocol + this._options.host + ':' + this._options.port + '/' + this._options.key + '/id';
  81. var queryString = '?ts=' + new Date().getTime() + '' + Math.random();
  82. url += queryString;
  83. // If there's no ID we need to wait for one before trying to init socket.
  84. http.open('get', url, true);
  85. http.onreadystatechange = function() {
  86. if (http.readyState === 4) {
  87. if (http.status !== 200) {
  88. throw 'Retrieve ID response not 200';
  89. return;
  90. }
  91. self.id = http.responseText;
  92. self._init();
  93. }
  94. };
  95. http.send(null);
  96. } catch(e) {
  97. this._abort('server-error', 'Could not get an ID from the server');
  98. }
  99. };
  100. Peer.prototype._init = function() {
  101. var self = this;
  102. this._socket = new Socket(this._options.host, this._options.port, this._options.key, this.id);
  103. this._socket.on('message', function(data) {
  104. self._handleServerJSONMessage(data);
  105. });
  106. this._socket.on('error', function(error) {
  107. util.log(error);
  108. self._abort('socket-error', error);
  109. });
  110. this._socket.on('close', function() {
  111. var msg = 'Underlying socket has closed';
  112. util.log('error', msg);
  113. self._abort('socket-closed', msg);
  114. });
  115. this._socket.start();
  116. }
  117. Peer.prototype._handleServerJSONMessage = function(message) {
  118. var peer = message.src;
  119. var manager = this.managers[peer];
  120. var payload = message.payload;
  121. switch (message.type) {
  122. case 'OPEN':
  123. this._processQueue();
  124. this.emit('open', this.id);
  125. break;
  126. case 'ERROR':
  127. this._abort('server-error', payload.msg);
  128. break;
  129. case 'ID-TAKEN':
  130. this._abort('unavailable-id', 'ID `'+this.id+'` is taken');
  131. break;
  132. case 'OFFER':
  133. var options = {
  134. sdp: payload.sdp,
  135. labels: payload.labels,
  136. config: this._options.config
  137. };
  138. var manager = this.managers[peer];
  139. if (!manager) {
  140. manager = new ConnectionManager(this.id, peer, this._socket, options);
  141. this._attachManagerListeners(manager);
  142. this.managers[peer] = manager;
  143. this.connections[peer] = manager.connections;
  144. }
  145. manager.update(options.labels);
  146. manager.handleSDP(payload.sdp, message.type);
  147. break;
  148. case 'EXPIRE':
  149. if (manager) {
  150. manager.close();
  151. manager.emit('error', new Error('Could not connect to peer ' + manager.peer));
  152. }
  153. break;
  154. case 'ANSWER':
  155. if (manager) {
  156. manager.handleSDP(payload.sdp, message.type);
  157. }
  158. break;
  159. case 'CANDIDATE':
  160. if (manager) {
  161. manager.handleCandidate(payload);
  162. }
  163. break;
  164. case 'LEAVE':
  165. if (manager) {
  166. manager.handleLeave();
  167. }
  168. break;
  169. case 'INVALID-KEY':
  170. this._abort('invalid-key', 'API KEY "' + this._key + '" is invalid');
  171. break;
  172. default:
  173. util.log('Unrecognized message type:', message.type);
  174. break;
  175. }
  176. };
  177. /** Process queued calls to connect. */
  178. Peer.prototype._processQueue = function() {
  179. while (this._queued.length > 0) {
  180. var manager = this._queued.pop();
  181. manager.initialize(this.id, this._socket);
  182. }
  183. };
  184. /** Listeners for manager. */
  185. Peer.prototype._attachManagerListeners = function(manager) {
  186. var self = this;
  187. // Handle receiving a connection.
  188. manager.on('connection', function(connection) {
  189. self.emit('connection', connection);
  190. });
  191. // Handle a connection closing.
  192. manager.on('close', function() {
  193. if (!!self.managers[manager.peer]) {
  194. delete self.managers[manager.peer];
  195. delete self.connections[manager.peer];
  196. }
  197. });
  198. manager.on('error', function(err) {
  199. self.emit('error', err);
  200. });
  201. };
  202. /** Destroys the Peer and emits an error message. */
  203. Peer.prototype._abort = function(type, message) {
  204. util.log('Aborting. Error:', message);
  205. var err = new Error(message);
  206. err.type = type;
  207. this.destroy();
  208. this.emit('error', err);
  209. };
  210. Peer.prototype._cleanup = function() {
  211. var self = this;
  212. if (!!this.managers) {
  213. var peers = Object.keys(this.managers);
  214. for (var i = 0, ii = peers.length; i < ii; i++) {
  215. this.managers[peers[i]].close();
  216. }
  217. }
  218. util.setZeroTimeout(function(){
  219. self.disconnect();
  220. });
  221. this.emit('close');
  222. };
  223. /** Exposed connect function for users. Will try to connect later if user
  224. * is waiting for an ID. */
  225. Peer.prototype.connect = function(peer, options) {
  226. if (this.disconnected) {
  227. var err = new Error('This Peer has been disconnected from the server and can no longer make connections.');
  228. err.type = 'server-disconnected';
  229. this.emit('error', err);
  230. return;
  231. }
  232. options = util.extend({
  233. config: this._options.config
  234. }, options);
  235. var manager = this.managers[peer];
  236. // Firefox currently does not support multiplexing once an offer is made.
  237. if (util.browserisms === 'Firefox' && !!manager && manager.firefoxSingular) {
  238. var err = new Error('Firefox currently does not support multiplexing after a DataChannel has already been established');
  239. err.type = 'firefoxism';
  240. this.emit('error', err);
  241. return;
  242. }
  243. if (!manager) {
  244. manager = new ConnectionManager(this.id, peer, this._socket, options);
  245. this._attachManagerListeners(manager);
  246. this.managers[peer] = manager;
  247. this.connections[peer] = manager.connections;
  248. }
  249. var connection = manager.connect(options);
  250. if (!this.id) {
  251. this._queued.push(manager);
  252. }
  253. return connection;
  254. };
  255. /**
  256. * Return the peer id or null, if there's no id at the moment.
  257. * Reasons for no id could be 'connect in progress' or 'disconnected'
  258. */
  259. Peer.prototype.getId = function() {
  260. return this.id;
  261. };
  262. /**
  263. * Destroys the Peer: closes all active connections as well as the connection
  264. * to the server.
  265. * Warning: The peer can no longer create or accept connections after being
  266. * destroyed.
  267. */
  268. Peer.prototype.destroy = function() {
  269. if (!this.destroyed) {
  270. this._cleanup();
  271. this.destroyed = true;
  272. }
  273. };
  274. /**
  275. * Disconnects the Peer's connection to the PeerServer. Does not close any
  276. * active connections.
  277. * Warning: The peer can no longer create or accept connections after being
  278. * disconnected. It also cannot reconnect to the server.
  279. */
  280. Peer.prototype.disconnect = function() {
  281. if (!this.disconnected) {
  282. if (!!this._socket) {
  283. this._socket.close();
  284. }
  285. this.id = null;
  286. this.disconnected = true;
  287. }
  288. };
  289. /** The current browser. */
  290. Peer.browser = util.browserisms;
  291. /**
  292. * Provides a clean method for checking if there's an active connection to the
  293. * peer server.
  294. */
  295. Peer.prototype.isConnected = function() {
  296. return !this.disconnected;
  297. };
  298. /**
  299. * Returns true if this peer is destroyed and can no longer be used.
  300. */
  301. Peer.prototype.isDestroyed = function() {
  302. return this.destroyed;
  303. };
  304. exports.Peer = Peer;