connection.js 8.2 KB

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