connectionmanager.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. // Set up PeerConnection.
  39. this._startPeerConnection();
  40. // Process queued DCs.
  41. this._processQueue();
  42. // Listen for ICE candidates.
  43. this._setupIce();
  44. // Listen for negotiation needed.
  45. // Chrome only **
  46. this._setupNegotiationHandler();
  47. // Listen for data channel.
  48. this._setupDataChannel();
  49. this.initialize = function() { };
  50. };
  51. /** Start a PC. */
  52. ConnectionManager.prototype._startPeerConnection = function() {
  53. util.log('Creating RTCPeerConnection');
  54. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  55. };
  56. /** Add DataChannels to all queued DataConnections. */
  57. ConnectionManager.prototype._processQueue = function() {
  58. var conn = this._queued.pop();
  59. if (!!conn) {
  60. var reliable = util.browserisms === 'Firefox' ? conn.reliable : false;
  61. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: reliable }));
  62. }
  63. };
  64. /** Set up ICE candidate handlers. */
  65. ConnectionManager.prototype._setupIce = function() {
  66. util.log('Listening for ICE candidates.');
  67. var self = this;
  68. this.pc.onicecandidate = function(evt) {
  69. if (evt.candidate) {
  70. util.log('Received ICE candidates.');
  71. self._socket.send({
  72. type: 'CANDIDATE',
  73. payload: {
  74. candidate: evt.candidate
  75. },
  76. dst: self.peer
  77. });
  78. }
  79. };
  80. this.pc.oniceconnectionstatechange = function() {
  81. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  82. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  83. self.close();
  84. }
  85. };
  86. // Fallback for older Chrome impls.
  87. this.pc.onicechange = function() {
  88. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  89. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  90. self.close();
  91. }
  92. };
  93. };
  94. /** Set up onnegotiationneeded. */
  95. ConnectionManager.prototype._setupNegotiationHandler = function() {
  96. var self = this;
  97. util.log('Listening for `negotiationneeded`');
  98. this.pc.onnegotiationneeded = function() {
  99. util.log('`negotiationneeded` triggered');
  100. self._makeOffer();
  101. };
  102. };
  103. /** Set up Data Channel listener. */
  104. ConnectionManager.prototype._setupDataChannel = function() {
  105. var self = this;
  106. util.log('Listening for data channel');
  107. this.pc.ondatachannel = function(evt) {
  108. util.log('Received data channel');
  109. var dc = evt.channel;
  110. var label = dc.label;
  111. // This should not be empty.
  112. var options = self.labels[label] || {};
  113. var connection = new DataConnection(self.peer, dc, options);
  114. self._attachConnectionListeners(connection);
  115. self.connections[label] = connection;
  116. self.emit('connection', connection);
  117. };
  118. };
  119. /** Send an offer. */
  120. ConnectionManager.prototype._makeOffer = function() {
  121. var self = this;
  122. this.pc.createOffer(function(offer) {
  123. util.log('Created offer.');
  124. // Firefox currently does not support multiplexing once an offer is made.
  125. self.firefoxSingular = true;
  126. if (util.browserisms === 'Webkit') {
  127. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  128. }
  129. self.pc.setLocalDescription(offer, function() {
  130. util.log('Set localDescription to offer');
  131. self._socket.send({
  132. type: 'OFFER',
  133. payload: {
  134. sdp: offer,
  135. config: self._options.config,
  136. labels: self.labels
  137. },
  138. dst: self.peer
  139. });
  140. // We can now reset labels because all info has been communicated.
  141. self.labels = {};
  142. }, function(err) {
  143. self.emit('error', err);
  144. util.log('Failed to setLocalDescription, ', err);
  145. });
  146. }, function(err) {
  147. self.emit('error', err);
  148. util.log('Failed to createOffer, ', err);
  149. });
  150. };
  151. /** Create an answer for PC. */
  152. ConnectionManager.prototype._makeAnswer = function() {
  153. var self = this;
  154. this.pc.createAnswer(function(answer) {
  155. util.log('Created answer.');
  156. if (util.browserisms === 'Webkit') {
  157. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  158. }
  159. self.pc.setLocalDescription(answer, function() {
  160. util.log('Set localDescription to answer.');
  161. self._socket.send({
  162. type: 'ANSWER',
  163. payload: {
  164. sdp: answer
  165. },
  166. dst: self.peer
  167. });
  168. }, function(err) {
  169. self.emit('error', err);
  170. util.log('Failed to setLocalDescription, ', err);
  171. });
  172. }, function(err) {
  173. self.emit('error', err);
  174. util.log('Failed to create answer, ', err);
  175. });
  176. };
  177. /** Clean up PC, close related DCs. */
  178. ConnectionManager.prototype._cleanup = function() {
  179. util.log('Cleanup ConnectionManager for ' + this.peer);
  180. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  181. this.pc.close();
  182. this.pc = null;
  183. }
  184. var self = this;
  185. this._socket.send({
  186. type: 'LEAVE',
  187. dst: self.peer
  188. });
  189. this.open = false;
  190. this.emit('close');
  191. };
  192. /** Attach connection listeners. */
  193. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  194. var self = this;
  195. connection.on('close', function() {
  196. if (!!self.connections[connection.label]) {
  197. delete self.connections[connection.label];
  198. }
  199. if (!Object.keys(self.connections).length) {
  200. self._cleanup();
  201. }
  202. });
  203. connection.on('open', function() {
  204. self._lock = false;
  205. self._processQueue();
  206. });
  207. };
  208. /** Handle an SDP. */
  209. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  210. sdp = new RTCSessionDescription(sdp);
  211. var self = this;
  212. this.pc.setRemoteDescription(sdp, function() {
  213. util.log('Set remoteDescription: ' + type);
  214. if (type === 'OFFER') {
  215. self._makeAnswer();
  216. }
  217. }, function(err) {
  218. self.emit('error', err);
  219. util.log('Failed to setRemoteDescription, ', err);
  220. });
  221. };
  222. /** Handle a candidate. */
  223. ConnectionManager.prototype.handleCandidate = function(message) {
  224. var candidate = new RTCIceCandidate(message.candidate);
  225. this.pc.addIceCandidate(candidate);
  226. util.log('Added ICE candidate.');
  227. };
  228. /** Handle peer leaving. */
  229. ConnectionManager.prototype.handleLeave = function() {
  230. util.log('Peer ' + this.peer + ' disconnected.');
  231. this.close();
  232. };
  233. /** Closes manager and all related connections. */
  234. ConnectionManager.prototype.close = function() {
  235. if (!this.open) {
  236. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  237. return;
  238. }
  239. var labels = Object.keys(this.connections);
  240. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  241. var label = labels[i];
  242. var connection = this.connections[label];
  243. connection.close();
  244. }
  245. this.connections = null;
  246. this._cleanup();
  247. };
  248. /** Create and returns a DataConnection with the peer with the given label. */
  249. ConnectionManager.prototype.connect = function(options) {
  250. if (!this.open) {
  251. return;
  252. }
  253. options = util.extend({
  254. label: 'peerjs',
  255. reliable: (util.browserisms === 'Firefox')
  256. }, options);
  257. // Check if label is taken...if so, generate a new label randomly.
  258. while (!!this.connections[options.label]) {
  259. options.label = 'peerjs' + this._default;
  260. this._default += 1;
  261. }
  262. this.labels[options.label] = options;
  263. var dc;
  264. if (!!this.pc && !this._lock) {
  265. var reliable = util.browserisms === 'Firefox' ? options.reliable : false;
  266. dc = this.pc.createDataChannel(options.label, { reliable: reliable });
  267. if (util.browserisms === 'Firefox') {
  268. this._makeOffer();
  269. }
  270. }
  271. var connection = new DataConnection(this.peer, dc, options);
  272. this._attachConnectionListeners(connection);
  273. this.connections[options.label] = connection;
  274. if (!this.pc || this._lock) {
  275. this._queued.push(connection);
  276. }
  277. this._lock = true
  278. return connection;
  279. };
  280. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  281. ConnectionManager.prototype.update = function(updates) {
  282. var labels = Object.keys(updates);
  283. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  284. var label = labels[i];
  285. this.labels[label] = updates[label];
  286. }
  287. };