connection.js 8.6 KB

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