connectionmanager.js 8.5 KB

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