connection.js 8.4 KB

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