connection.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. function DataConnection(id, peer, socket, cb, options) {
  2. if (!(this instanceof DataConnection)) return new DataConnection(options);
  3. EventEmitter.call(this);
  4. options = util.extend({
  5. debug: false,
  6. ice: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  7. }, options);
  8. this.options = options;
  9. // Is this the originator?
  10. this._id = id;
  11. this._peer = peer;
  12. this._originator = (options.sdp == undefined);
  13. this._cb = cb;
  14. this.metadata = options.metadata;
  15. // Set up socket handlers.
  16. this._socket = socket;
  17. // Firefoxism: connectDataConnection ports.
  18. if (browserisms == 'Firefox') {
  19. this._firefoxPortSetup();
  20. }
  21. //
  22. // Set up PeerConnection.
  23. this._startPeerConnection();
  24. // Listen for ICE candidates
  25. this._setupIce();
  26. // Listen for negotiation needed
  27. // ** Chrome only.
  28. if (browserisms === 'Webkit') {
  29. this._setupOffer();
  30. }
  31. // Listen or create a data channel
  32. this._setupDataChannel();
  33. var self = this;
  34. if (options.sdp) {
  35. this.handleSDP({type: 'OFFER', sdp: options.sdp});
  36. if (browserisms !== 'Firefox') {
  37. this._makeAnswer();
  38. }
  39. }
  40. if (browserisms === 'Firefox') {
  41. this._firefoxAdditional();
  42. }
  43. };
  44. util.inherits(DataConnection, EventEmitter);
  45. DataConnection.prototype._setupOffer = function() {
  46. var self = this;
  47. util.log('Listening for `negotiationneeded`');
  48. this._pc.onnegotiationneeded = function() {
  49. util.log('`negotiationneeded` triggered');
  50. self._makeOffer();
  51. };
  52. }
  53. DataConnection.prototype._setupDataChannel = function() {
  54. var self = this;
  55. if (this._originator) {
  56. util.log('Creating data channel');
  57. this._dc = this._pc.createDataChannel(this._peer, { reliable: false });
  58. this._configureDataChannel();
  59. } else {
  60. util.log('Listening for data channel');
  61. this._pc.ondatachannel = function(evt) {
  62. util.log('Received data channel');
  63. self._dc = evt.channel;
  64. self._configureDataChannel();
  65. };
  66. }
  67. };
  68. DataConnection.prototype.handleSDP = function(message) {
  69. var sdp = message.sdp;
  70. if (browserisms != 'Firefox') {
  71. sdp = new RTCSessionDescription(sdp);
  72. }
  73. var self = this;
  74. this._pc.setRemoteDescription(sdp, function() {
  75. util.log('Set remoteDescription: ' + message.type);
  76. // Firefoxism
  77. if (message.type == 'ANSWER' && browserisms == 'Firefox') {
  78. self._pc.connectDataConnection(self.localPort, self.remotePort);
  79. self._socket.send(JSON.stringify({
  80. type: 'PORT',
  81. dst: self._peer,
  82. src: self._id,
  83. remote: self.localPort,
  84. local: self.remotePort
  85. }));
  86. }
  87. }, function(err) {
  88. this._cb('Failed to setRemoteDescription');
  89. util.log('Failed to setRemoteDescription, ', err);
  90. });
  91. };
  92. DataConnection.prototype.handleCandidate = function(message) {
  93. var candidate = new RTCIceCandidate(message.candidate);
  94. this._pc.addIceCandidate(candidate);
  95. };
  96. DataConnection.prototype.handleLeave = function(message) {
  97. util.log('Peer ' + this._peer + ' disconnected');
  98. if (!!this._pc && this._pc.readyState != 'closed') {
  99. this._pc.close();
  100. this._pc = null;
  101. }
  102. if (!!this._dc && this._dc.readyState != 'closed') {
  103. this._dc.close();
  104. this._dc = null;
  105. }
  106. this.emit('close', this._peer);
  107. };
  108. DataConnection.prototype.handlePort = function(message) {
  109. if (!DataConnection.usedPorts) {
  110. DataConnection.usedPorts = [];
  111. }
  112. DataConnection.usedPorts.push(message.local);
  113. DataConnection.usedPorts.push(message.remote);
  114. this._pc.connectDataConnection(message.local, message.remote);
  115. };
  116. /** Starts a PeerConnection and sets up handlers. */
  117. DataConnection.prototype._startPeerConnection = function() {
  118. util.log('Creating RTCPeerConnection: ', this.options.ice);
  119. this._pc = new RTCPeerConnection(this.options.ice, { optional:[ { RtpDataChannels: true } ]});
  120. };
  121. /** Takes care of ice handlers. */
  122. DataConnection.prototype._setupIce = function() {
  123. util.log('Listening for ICE candidates');
  124. var self = this;
  125. this._pc.onicecandidate = function(evt) {
  126. if (evt.candidate) {
  127. util.log('Received ICE candidates');
  128. self._socket.send(JSON.stringify({
  129. type: 'CANDIDATE',
  130. candidate: evt.candidate,
  131. dst: self._peer,
  132. src: self._id
  133. }));
  134. }
  135. };
  136. };
  137. /** Sets up DataChannel handlers.
  138. DataConnection.prototype._setupDataChannel = function() {
  139. var self = this;
  140. if (this._originator) {
  141. if (browserisms == 'Webkit') {
  142. // TODO: figure out the right thing to do with this.
  143. this._pc.onstatechange = function() {
  144. util.log('State Change: ', self._pc.readyState);
  145. }
  146. } else {
  147. this._pc.onconnection = function() {
  148. util.log('ORIGINATOR: onconnection triggered');
  149. self._startDataChannel();
  150. };
  151. }
  152. } else {
  153. this._pc.onconnection = function() {
  154. util.log('SINK: onconnection triggered');
  155. };
  156. }
  157. this._pc.onclosedconnection = function() {
  158. // Remove socket handlers perhaps.
  159. self.emit('close', self._peer);
  160. };
  161. };
  162. */
  163. DataConnection.prototype._firefoxPortSetup = function() {
  164. if (!DataConnection.usedPorts) {
  165. DataConnection.usedPorts = [];
  166. }
  167. this.localPort = util.randomPort();
  168. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  169. this.localPort = util.randomPort();
  170. }
  171. this.remotePort = util.randomPort();
  172. while (this.remotePort == this.localPort ||
  173. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  174. this.remotePort = util.randomPort();
  175. }
  176. DataConnection.usedPorts.push(this.remotePort);
  177. DataConnection.usedPorts.push(this.localPort);
  178. }
  179. DataConnection.prototype._configureDataChannel = function() {
  180. var self = this;
  181. if (browserisms === 'Firefox') {
  182. this._dc.binaryType = 'blob';
  183. }
  184. this._dc.onopen = function() {
  185. util.log('Data channel connection success');
  186. self._cb(null, self);
  187. };
  188. this._dc.onmessage = function(e) {
  189. self._handleDataMessage(e);
  190. };
  191. };
  192. /** Decide whether to handle Firefoxisms. */
  193. DataConnection.prototype._firefoxAdditional = function() {
  194. var self = this;
  195. getUserMedia({ audio: true, fake: true }, function(s) {
  196. self._pc.addStream(s);
  197. if (self._originator) {
  198. self._makeOffer();
  199. } else {
  200. self._makeAnswer();
  201. }
  202. }, function(err) { util.log('Could not getUserMedia'); });
  203. }
  204. DataConnection.prototype._makeOffer = function() {
  205. var self = this;
  206. this._pc.createOffer(function(offer) {
  207. util.log('Created offer');
  208. self._pc.setLocalDescription(offer, function() {
  209. util.log('Set localDescription to offer');
  210. self._socket.send(JSON.stringify({
  211. type: 'OFFER',
  212. sdp: offer,
  213. dst: self._peer,
  214. src: self._id,
  215. metadata: self.metadata
  216. }));
  217. }, function(err) {
  218. self._cb('Failed to setLocalDescription');
  219. util.log('Failed to setLocalDescription, ', err);
  220. });
  221. });
  222. };
  223. /** Create an answer for PC. */
  224. DataConnection.prototype._makeAnswer = function() {
  225. var self = this;
  226. this._pc.createAnswer(function(answer) {
  227. util.log('Created answer');
  228. self._pc.setLocalDescription(answer, function() {
  229. util.log('Set localDescription to answer');
  230. self._socket.send(JSON.stringify({
  231. type: 'ANSWER',
  232. src: self._id,
  233. sdp: answer,
  234. dst: self._peer
  235. }));
  236. }, function(err) {
  237. self._cb('Failed to setLocalDescription');
  238. util.log('Failed to setLocalDescription, ', err)
  239. });
  240. }, function(err) {
  241. self._cb('Failed to create answer');
  242. util.log('Failed to create answer, ', err)
  243. });
  244. };
  245. /** Allows user to send data. */
  246. DataConnection.prototype.send = function(data) {
  247. var self = this;
  248. var blob = BinaryPack.pack(data);
  249. if (browserisms == 'Webkit') {
  250. util.blobToBinaryString(blob, function(str){
  251. self._dc.send(str);
  252. });
  253. } else {
  254. this._dc.send(blob);
  255. }
  256. };
  257. // Handles a DataChannel message.
  258. DataConnection.prototype._handleDataMessage = function(e) {
  259. var self = this;
  260. if (e.data.constructor == Blob) {
  261. util.blobToArrayBuffer(e.data, function(ab) {
  262. var data = BinaryPack.unpack(ab);
  263. self.emit('data', data);
  264. });
  265. } else if (e.data.constructor == ArrayBuffer) {
  266. var data = BinaryPack.unpack(e.data);
  267. self.emit('data', data);
  268. } else if (e.data.constructor == String) {
  269. var ab = util.binaryStringToArrayBuffer(e.data);
  270. var data = BinaryPack.unpack(ab);
  271. self.emit('data', data);
  272. }
  273. };