connectionmanager.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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. self.pc.setLocalDescription(offer, function() {
  127. util.log('Set localDescription to offer');
  128. self._socket.send({
  129. type: 'OFFER',
  130. payload: {
  131. sdp: offer,
  132. config: self._options.config,
  133. labels: self.labels
  134. },
  135. dst: self.peer
  136. });
  137. // We can now reset labels because all info has been communicated.
  138. self.labels = {};
  139. }, function(err) {
  140. self.emit('error', err);
  141. util.log('Failed to setLocalDescription, ', err);
  142. });
  143. });
  144. };
  145. /** Create an answer for PC. */
  146. ConnectionManager.prototype._makeAnswer = function() {
  147. var self = this;
  148. this.pc.createAnswer(function(answer) {
  149. util.log('Created answer.');
  150. self.pc.setLocalDescription(answer, function() {
  151. util.log('Set localDescription to answer.');
  152. self._socket.send({
  153. type: 'ANSWER',
  154. payload: {
  155. sdp: answer
  156. },
  157. dst: self.peer
  158. });
  159. }, function(err) {
  160. self.emit('error', err);
  161. util.log('Failed to setLocalDescription, ', err);
  162. });
  163. }, function(err) {
  164. self.emit('error', err);
  165. util.log('Failed to create answer, ', err);
  166. });
  167. };
  168. /** Clean up PC, close related DCs. */
  169. ConnectionManager.prototype._cleanup = function() {
  170. util.log('Cleanup ConnectionManager for ' + this.peer);
  171. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  172. this.pc.close();
  173. this.pc = null;
  174. }
  175. var self = this;
  176. this._socket.send({
  177. type: 'LEAVE',
  178. dst: self.peer
  179. });
  180. this.open = false;
  181. this.emit('close');
  182. };
  183. /** Attach connection listeners. */
  184. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  185. var self = this;
  186. connection.on('close', function() {
  187. if (!!self.connections[connection.label]) {
  188. delete self.connections[connection.label];
  189. }
  190. if (!Object.keys(self.connections).length) {
  191. self._cleanup();
  192. }
  193. });
  194. connection.on('open', function() {
  195. self._lock = false;
  196. self._processQueue();
  197. });
  198. };
  199. /** Handle an SDP. */
  200. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  201. sdp = new RTCSessionDescription(sdp);
  202. var self = this;
  203. this.pc.setRemoteDescription(sdp, function() {
  204. util.log('Set remoteDescription: ' + type);
  205. if (type === 'OFFER') {
  206. self._makeAnswer();
  207. }
  208. }, function(err) {
  209. self.emit('error', err);
  210. util.log('Failed to setRemoteDescription, ', err);
  211. });
  212. };
  213. /** Handle a candidate. */
  214. ConnectionManager.prototype.handleCandidate = function(message) {
  215. var candidate = new RTCIceCandidate(message.candidate);
  216. this.pc.addIceCandidate(candidate);
  217. util.log('Added ICE candidate.');
  218. };
  219. /** Handle peer leaving. */
  220. ConnectionManager.prototype.handleLeave = function() {
  221. util.log('Peer ' + this.peer + ' disconnected.');
  222. this.close();
  223. };
  224. /** Closes manager and all related connections. */
  225. ConnectionManager.prototype.close = function() {
  226. if (!this.open) {
  227. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  228. return;
  229. }
  230. var labels = Object.keys(this.connections);
  231. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  232. var label = labels[i];
  233. var connection = this.connections[label];
  234. connection.close();
  235. }
  236. this.connections = null;
  237. this._cleanup();
  238. };
  239. /** Create and returns a DataConnection with the peer with the given label. */
  240. ConnectionManager.prototype.connect = function(options) {
  241. if (!this.open) {
  242. return;
  243. }
  244. if (util.browserisms === 'Firefox') {
  245. options = util.extend({
  246. label: 'peerjs',
  247. reliable: true
  248. }, options);
  249. } else {
  250. options = util.extend({
  251. label: 'peerjs',
  252. reliable: false
  253. }, options);
  254. }
  255. // Check if label is taken...if so, generate a new label randomly.
  256. while (!!this.connections[options.label]) {
  257. options.label = 'peerjs' + this._default;
  258. this._default += 1;
  259. }
  260. this.labels[options.label] = options;
  261. var dc;
  262. if (!!this.pc && !this._lock) {
  263. var reliable = util.browserisms === 'Firefox' ? options.reliable : false;
  264. dc = this.pc.createDataChannel(options.label, { reliable: reliable });
  265. if (util.browserisms === 'Firefox') {
  266. this._makeOffer();
  267. }
  268. }
  269. var connection = new DataConnection(this.peer, dc, options);
  270. this._attachConnectionListeners(connection);
  271. this.connections[options.label] = connection;
  272. if (!this.pc || this._lock) {
  273. this._queued.push(connection);
  274. }
  275. this._lock = true
  276. return connection;
  277. };
  278. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  279. ConnectionManager.prototype.update = function(updates) {
  280. var labels = Object.keys(updates);
  281. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  282. var label = labels[i];
  283. this.labels[label] = updates[label];
  284. }
  285. };