connectionmanager.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. /**
  2. * Manages DataConnections between its peer and one other peer.
  3. * Internally, manages PeerConnection.
  4. */
  5. function ConnectionManager(id, peer, socket, options) {
  6. if (!(this instanceof ConnectionManager)) return new ConnectionManager(id, peer, socket, options);
  7. EventEmitter.call(this);
  8. options = util.extend({
  9. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  10. }, options);
  11. this._options = options;
  12. // PeerConnection is not yet dead.
  13. this.open = true;
  14. this.id = id;
  15. this.peer = peer;
  16. this.pc = null;
  17. // Mapping labels to metadata and serialization.
  18. // label => { metadata: ..., serialization: ..., reliable: ...}
  19. this.labels = {};
  20. // A default label in the event that none are passed in.
  21. this._default = 0;
  22. // DataConnections on this PC.
  23. this.connections = {};
  24. this._queued = [];
  25. this._socket = socket;
  26. if (!!this.id) {
  27. this.initialize();
  28. }
  29. };
  30. util.inherits(ConnectionManager, EventEmitter);
  31. ConnectionManager.prototype.initialize = function(id, socket) {
  32. if (!!id) {
  33. this.id = id;
  34. }
  35. if (!!socket) {
  36. this._socket = socket;
  37. }
  38. // Firefoxism where ports need to be generated.
  39. if (util.browserisms === 'Firefox') {
  40. this._firefoxPortSetup();
  41. }
  42. // Set up PeerConnection.
  43. this._startPeerConnection();
  44. // Process queued DCs.
  45. if (util.browserisms !== 'Firefox') {
  46. this._processQueue();
  47. }
  48. // Listen for ICE candidates.
  49. this._setupIce();
  50. // Listen for data channel.
  51. this._setupDataChannel();
  52. // Listen for negotiation needed.
  53. // Chrome only--Firefox instead has to manually makeOffer.
  54. if (util.browserisms !== 'Firefox') {
  55. this._setupNegotiationHandler();
  56. } else if (this._options.originator) {
  57. this._firefoxHandlerSetup()
  58. this._firefoxAdditional()
  59. }
  60. this.initialize = function() { };
  61. };
  62. /** Firefoxism that requires a fake media stream. */
  63. ConnectionManager.prototype._firefoxAdditional = function() {
  64. util.log('Additional media stream for Firefox.');
  65. var self = this;
  66. getUserMedia({ audio: true, fake: true }, function(s) {
  67. self.pc.addStream(s);
  68. if (self._options.originator) {
  69. self._makeOffer();
  70. } else {
  71. self._makeAnswer();
  72. }
  73. }, function(err) { util.log('Could not getUserMedia'); });
  74. };
  75. /** Firefoxism that requires ports to be set up. */
  76. ConnectionManager.prototype._firefoxPortSetup = function() {
  77. if (!ConnectionManager.usedPorts) {
  78. ConnectionManager.usedPorts = [];
  79. }
  80. this._localPort = util.randomPort();
  81. while (ConnectionManager.usedPorts.indexOf(this._localPort) != -1) {
  82. this._localPort = util.randomPort();
  83. }
  84. this._remotePort = util.randomPort();
  85. while (this._remotePort === this._localPort ||
  86. ConnectionManager.usedPorts.indexOf(this._remotePort) != -1) {
  87. this._remotePort = util.randomPort();
  88. }
  89. ConnectionManager.usedPorts.push(this._remotePort);
  90. ConnectionManager.usedPorts.push(this._localPort);
  91. };
  92. /** Firefoxism that is `onconnection`. */
  93. ConnectionManager.prototype._firefoxHandlerSetup = function() {
  94. util.log('Setup Firefox `onconnection`.');
  95. var self = this;
  96. this.pc.onconnection = function() {
  97. util.log('FIREFOX: onconnection triggered');
  98. self._processQueue();
  99. }
  100. };
  101. /** Start a PC. */
  102. ConnectionManager.prototype._startPeerConnection = function() {
  103. util.log('Creating RTCPeerConnection');
  104. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  105. };
  106. /** Add DataChannels to all queued DataConnections. */
  107. ConnectionManager.prototype._processQueue = function() {
  108. var conn = this._queued.pop();
  109. if (!!conn) {
  110. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: false }));
  111. }
  112. };
  113. /** Set up ICE candidate handlers. */
  114. ConnectionManager.prototype._setupIce = function() {
  115. util.log('Listening for ICE candidates.');
  116. var self = this;
  117. this.pc.onicecandidate = function(evt) {
  118. if (evt.candidate) {
  119. util.log('Received ICE candidates.');
  120. self._socket.send({
  121. type: 'CANDIDATE',
  122. payload: {
  123. candidate: evt.candidate
  124. },
  125. dst: self.peer
  126. });
  127. }
  128. };
  129. };
  130. /** Set up onnegotiationneeded. */
  131. ConnectionManager.prototype._setupNegotiationHandler = function() {
  132. var self = this;
  133. util.log('Listening for `negotiationneeded`');
  134. this.pc.onnegotiationneeded = function() {
  135. util.log('`negotiationneeded` triggered');
  136. self._makeOffer();
  137. };
  138. };
  139. /** Set up Data Channel listener. */
  140. ConnectionManager.prototype._setupDataChannel = function() {
  141. var self = this;
  142. util.log('Listening for data channel');
  143. this.pc.ondatachannel = function(evt) {
  144. util.log('Received data channel');
  145. // Firefoxism: ondatachannel receives channel directly. NOT TO SPEC.
  146. var dc = util.browserisms === 'Firefox' ? evt : evt.channel;
  147. var label = dc.label;
  148. // This should not be empty.
  149. var options = self.labels[label] || {};
  150. var connection = new DataConnection(self.peer, dc, options);
  151. delete self.labels[label];
  152. self._attachConnectionListeners(connection);
  153. self.connections[label] = connection;
  154. self.emit('connection', connection);
  155. };
  156. };
  157. /** Send an offer. */
  158. ConnectionManager.prototype._makeOffer = function() {
  159. var self = this;
  160. this.pc.createOffer(function(offer) {
  161. util.log('Created offer.');
  162. self.pc.setLocalDescription(offer, function() {
  163. util.log('Set localDescription to offer');
  164. self._socket.send({
  165. type: 'OFFER',
  166. payload: {
  167. browserisms: util.browserisms,
  168. sdp: offer,
  169. config: self._options.config,
  170. labels: self.labels
  171. },
  172. dst: self.peer
  173. });
  174. // We can now reset labels because all info has been communicated.
  175. self.labels = {};
  176. }, function(err) {
  177. self.emit('error', err);
  178. util.log('Failed to setLocalDescription, ', err);
  179. });
  180. });
  181. };
  182. /** Create an answer for PC. */
  183. ConnectionManager.prototype._makeAnswer = function() {
  184. var self = this;
  185. this.pc.createAnswer(function(answer) {
  186. util.log('Created answer.');
  187. self.pc.setLocalDescription(answer, function() {
  188. util.log('Set localDescription to answer.');
  189. self._socket.send({
  190. type: 'ANSWER',
  191. payload: {
  192. browserisms: util.browserisms,
  193. sdp: answer
  194. },
  195. dst: self.peer
  196. });
  197. }, function(err) {
  198. self.emit('error', err);
  199. util.log('Failed to setLocalDescription, ', err);
  200. });
  201. }, function(err) {
  202. self.emit('error', err);
  203. util.log('Failed to create answer, ', err);
  204. });
  205. };
  206. /** Clean up PC, close related DCs. */
  207. ConnectionManager.prototype._cleanup = function() {
  208. util.log('Cleanup ConnectionManager for ' + this.peer);
  209. if (!!this.pc && this.pc.readyState !== 'closed') {
  210. this.pc.close();
  211. this.pc = null;
  212. }
  213. var self = this;
  214. this._socket.send({
  215. type: 'LEAVE',
  216. dst: self.peer
  217. });
  218. this.open = false;
  219. this.emit('close');
  220. };
  221. /** Attach connection listeners. */
  222. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  223. var self = this;
  224. connection.on('close', function() {
  225. if (!!self.connections[connection.label]) {
  226. delete self.connections[connection.label];
  227. }
  228. if (!Object.keys(self.connections).length) {
  229. self._cleanup();
  230. }
  231. });
  232. connection.on('open', function() {
  233. self._lock = false;
  234. if (util.browserisms !== 'Firefox') {
  235. self._processQueue();
  236. }
  237. });
  238. };
  239. /** Firefoxism: handle receiving a set of ports. */
  240. ConnectionManager.prototype.handlePort = function(ports) {
  241. util.log('Received ports, calling connectDataConnection.');
  242. if (!ConnectionManager.usedPorts) {
  243. ConnectionManager.usedPorts = [];
  244. }
  245. ConnectionManager.usedPorts.push(ports.local);
  246. ConnectionManager.usedPorts.push(ports.remote);
  247. this.pc.connectDataConnection(ports.local, ports.remote);
  248. };
  249. /** Handle an SDP. */
  250. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  251. if (util.browserisms !== 'Firefox') {
  252. // Doesn't need to happen for FF.
  253. sdp = new RTCSessionDescription(sdp);
  254. }
  255. var self = this;
  256. this.pc.setRemoteDescription(sdp, function() {
  257. util.log('Set remoteDescription: ' + type);
  258. if (type === 'OFFER') {
  259. if (util.browserisms === 'Firefox') {
  260. self._firefoxAdditional();
  261. } else {
  262. self._makeAnswer();
  263. }
  264. } else if (util.browserisms === 'Firefox') {
  265. // Firefoxism.
  266. util.log('Peer ANSWER received, connectDataConnection called.');
  267. self.pc.connectDataConnection(self._localPort, self._remotePort);
  268. self._socket.send({
  269. type: 'PORT',
  270. payload: {
  271. remote: self._localPort,
  272. local: self._remotePort
  273. },
  274. dst: self.peer
  275. });
  276. }
  277. }, function(err) {
  278. self.emit('error', err);
  279. util.log('Failed to setRemoteDescription, ', err);
  280. });
  281. };
  282. /** Handle a candidate. */
  283. ConnectionManager.prototype.handleCandidate = function(message) {
  284. var candidate = new RTCIceCandidate(message.candidate);
  285. this.pc.addIceCandidate(candidate);
  286. util.log('Added ICE candidate.');
  287. };
  288. /** Handle peer leaving. */
  289. ConnectionManager.prototype.handleLeave = function() {
  290. util.log('Peer ' + this.peer + ' disconnected.');
  291. this.close();
  292. };
  293. /** Closes manager and all related connections. */
  294. ConnectionManager.prototype.close = function() {
  295. if (!this.open) {
  296. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  297. return;
  298. }
  299. var labels = Object.keys(this.connections);
  300. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  301. var label = labels[i];
  302. var connection = this.connections[label];
  303. connection.close();
  304. }
  305. this.connections = null;
  306. this._cleanup();
  307. };
  308. /** Create and returns a DataConnection with the peer with the given label. */
  309. ConnectionManager.prototype.connect = function(options) {
  310. if (!this.open) {
  311. return;
  312. }
  313. options = util.extend({
  314. label: 'peerjs'
  315. }, options);
  316. // Check if label is taken...if so, generate a new label randomly.
  317. while (!!this.connections[options.label]) {
  318. options.label = 'peerjs' + this._default;
  319. this._default += 1;
  320. }
  321. this.labels[options.label] = options;
  322. var dc;
  323. if (!!this.pc && !this._lock && util.browserisms !== 'Firefox') {
  324. dc = this.pc.createDataChannel(options.label, { reliable: false });
  325. }
  326. var connection = new DataConnection(this.peer, dc, options);
  327. this._attachConnectionListeners(connection);
  328. this.connections[options.label] = connection;
  329. if (!this.pc || this._lock || util.browserisms === 'Firefox') {
  330. this._queued.push(connection);
  331. }
  332. this._lock = true
  333. return [options.label, connection];
  334. };
  335. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  336. ConnectionManager.prototype.update = function(updates) {
  337. var labels = Object.keys(updates);
  338. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  339. var label = labels[i];
  340. this.labels[label] = updates[label];
  341. }
  342. };