connection.js 9.2 KB

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