connectionmanager.js 7.7 KB

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