connection.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. function DataConnection(id, peer, socket, httpUrl, 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. this._id = id;
  10. this._peer = peer;
  11. this._originator = (options.sdp === undefined);
  12. this._cb = cb;
  13. this._httpUrl = httpUrl;
  14. this.metadata = options.metadata;
  15. // Set up socket handlers.
  16. this._socket = socket;
  17. // Firefoxism: connectDataConnection ports.
  18. if (util.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 (util.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 (util.browserisms !== 'Firefox') {
  37. this._makeAnswer();
  38. }
  39. }
  40. if (util.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. /** Starts a PeerConnection and sets up handlers. */
  69. DataConnection.prototype._startPeerConnection = function() {
  70. util.log('Creating RTCPeerConnection: ', this.options.ice);
  71. this._pc = new RTCPeerConnection(this.options.ice, { optional:[ { RtpDataChannels: true } ]});
  72. };
  73. /** Takes care of ice handlers. */
  74. DataConnection.prototype._setupIce = function() {
  75. util.log('Listening for ICE candidates');
  76. var self = this;
  77. this._pc.onicecandidate = function(evt) {
  78. if (evt.candidate) {
  79. util.log('Received ICE candidates');
  80. self._handleBroker('ice', JSON.stringify({
  81. type: 'CANDIDATE',
  82. candidate: evt.candidate,
  83. dst: self._peer,
  84. src: self._id
  85. }));
  86. }
  87. };
  88. };
  89. DataConnection.prototype._handleBroker = function(type, data) {
  90. if (this._socketOpen) {
  91. this._socket.send(data);
  92. } else {
  93. var http = new XMLHttpRequest();
  94. http.open('post', this._httpUrl + '/' + type, true);
  95. http.setRequestHeader('Content-Type', 'application/json');
  96. http.onload = function() {
  97. util.log(http.responseText);
  98. }
  99. http.send(data);
  100. }
  101. };
  102. // Awaiting update in Firefox spec ***
  103. /** Sets up DataChannel handlers.
  104. DataConnection.prototype._setupDataChannel = function() {
  105. var self = this;
  106. if (this._originator) {
  107. if (util.browserisms === 'Webkit') {
  108. // TODO: figure out the right thing to do with this.
  109. this._pc.onstatechange = function() {
  110. util.log('State Change: ', self._pc.readyState);
  111. }
  112. } else {
  113. this._pc.onconnection = function() {
  114. util.log('ORIGINATOR: onconnection triggered');
  115. self._startDataChannel();
  116. };
  117. }
  118. } else {
  119. this._pc.onconnection = function() {
  120. util.log('SINK: onconnection triggered');
  121. };
  122. }
  123. this._pc.onclosedconnection = function() {
  124. // Remove socket handlers perhaps.
  125. self.emit('close', self._peer);
  126. };
  127. };
  128. */
  129. DataConnection.prototype._firefoxPortSetup = function() {
  130. if (!DataConnection.usedPorts) {
  131. DataConnection.usedPorts = [];
  132. }
  133. this.localPort = util.randomPort();
  134. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  135. this.localPort = util.randomPort();
  136. }
  137. this.remotePort = util.randomPort();
  138. while (this.remotePort === this.localPort ||
  139. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  140. this.remotePort = util.randomPort();
  141. }
  142. DataConnection.usedPorts.push(this.remotePort);
  143. DataConnection.usedPorts.push(this.localPort);
  144. }
  145. DataConnection.prototype._configureDataChannel = function() {
  146. var self = this;
  147. if (util.browserisms === 'Firefox') {
  148. this._dc.binaryType = 'blob';
  149. }
  150. this._dc.onopen = function() {
  151. util.log('Data channel connection success');
  152. self._cb(null, self);
  153. };
  154. this._dc.onmessage = function(e) {
  155. self._handleDataMessage(e);
  156. };
  157. };
  158. /** Decide whether to handle Firefoxisms. */
  159. DataConnection.prototype._firefoxAdditional = function() {
  160. var self = this;
  161. getUserMedia({ audio: true, fake: true }, function(s) {
  162. self._pc.addStream(s);
  163. if (self._originator) {
  164. self._makeOffer();
  165. } else {
  166. self._makeAnswer();
  167. }
  168. }, function(err) { util.log('Could not getUserMedia'); });
  169. }
  170. DataConnection.prototype._makeOffer = function() {
  171. var self = this;
  172. this._pc.createOffer(function(offer) {
  173. util.log('Created offer');
  174. self._pc.setLocalDescription(offer, function() {
  175. util.log('Set localDescription to offer');
  176. self._handleBroker('offer', JSON.stringify({
  177. type: 'OFFER',
  178. sdp: offer,
  179. dst: self._peer,
  180. src: self._id,
  181. metadata: self.metadata
  182. }));
  183. }, function(err) {
  184. self._cb('Failed to setLocalDescription');
  185. util.log('Failed to setLocalDescription, ', err);
  186. });
  187. });
  188. };
  189. /** Create an answer for PC. */
  190. DataConnection.prototype._makeAnswer = function() {
  191. var self = this;
  192. this._pc.createAnswer(function(answer) {
  193. util.log('Created answer');
  194. self._pc.setLocalDescription(answer, function() {
  195. util.log('Set localDescription to answer');
  196. self._handleBroker('answer', JSON.stringify({
  197. type: 'ANSWER',
  198. src: self._id,
  199. sdp: answer,
  200. dst: self._peer
  201. }));
  202. }, function(err) {
  203. self._cb('Failed to setLocalDescription');
  204. util.log('Failed to setLocalDescription, ', err)
  205. });
  206. }, function(err) {
  207. self._cb('Failed to create answer');
  208. util.log('Failed to create answer, ', err)
  209. });
  210. };
  211. DataConnection.prototype._cleanup = function() {
  212. if (!!this._pc && this._pc.readyState != 'closed') {
  213. this._pc.close();
  214. this._pc = null;
  215. }
  216. if (!!this._dc && this._dc.readyState != 'closed') {
  217. this._dc.close();
  218. this._dc = null;
  219. }
  220. this.emit('close', this._peer);
  221. };
  222. // Handles a DataChannel message.
  223. DataConnection.prototype._handleDataMessage = function(e) {
  224. var self = this;
  225. if (e.data.constructor === Blob) {
  226. util.blobToArrayBuffer(e.data, function(ab) {
  227. var data = BinaryPack.unpack(ab);
  228. self.emit('data', data);
  229. });
  230. } else if (e.data.constructor === ArrayBuffer) {
  231. var data = BinaryPack.unpack(e.data);
  232. self.emit('data', data);
  233. } else if (e.data.constructor === String) {
  234. var ab = util.binaryStringToArrayBuffer(e.data);
  235. var data = BinaryPack.unpack(ab);
  236. self.emit('data', data);
  237. }
  238. };
  239. /**
  240. * Exposed functionality for users.
  241. */
  242. /** Allows user to close connection. */
  243. DataConnection.prototype.close = function() {
  244. this._cleanup();
  245. var self = this;
  246. this._handleBroker('leave', JSON.stringify({
  247. type: 'LEAVE',
  248. dst: self._peer,
  249. src: self._id,
  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 (util.browserisms === 'Webkit') {
  257. util.blobToBinaryString(blob, function(str){
  258. self._dc.send(str);
  259. });
  260. } else {
  261. this._dc.send(blob);
  262. }
  263. };
  264. /**
  265. * Exposed functions for Peer.
  266. */
  267. DataConnection.prototype.setSocketOpen = function() {
  268. this._socketOpen = true;
  269. };
  270. DataConnection.prototype.handleSDP = function(message) {
  271. var sdp = message.sdp;
  272. if (util.browserisms != 'Firefox') {
  273. sdp = new RTCSessionDescription(sdp);
  274. }
  275. var self = this;
  276. this._pc.setRemoteDescription(sdp, function() {
  277. util.log('Set remoteDescription: ' + message.type);
  278. // Firefoxism
  279. if (message.type === 'ANSWER' && util.browserisms === 'Firefox') {
  280. self._pc.connectDataConnection(self.localPort, self.remotePort);
  281. self._handleBroker('port', JSON.stringify({
  282. type: 'PORT',
  283. dst: self._peer,
  284. src: self._id,
  285. remote: self.localPort,
  286. local: self.remotePort
  287. }));
  288. }
  289. }, function(err) {
  290. this._cb('Failed to setRemoteDescription');
  291. util.log('Failed to setRemoteDescription, ', err);
  292. });
  293. };
  294. DataConnection.prototype.handleCandidate = function(message) {
  295. var candidate = new RTCIceCandidate(message.candidate);
  296. this._pc.addIceCandidate(candidate);
  297. };
  298. DataConnection.prototype.handleLeave = function() {
  299. util.log('Peer ' + this._peer + ' disconnected');
  300. this._cleanup();
  301. };
  302. DataConnection.prototype.handlePort = function(message) {
  303. if (!DataConnection.usedPorts) {
  304. DataConnection.usedPorts = [];
  305. }
  306. DataConnection.usedPorts.push(message.local);
  307. DataConnection.usedPorts.push(message.remote);
  308. this._pc.connectDataConnection(message.local, message.remote);
  309. };