connection.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. /**
  2. * A DataChannel PeerConnection between two Peers.
  3. */
  4. function DataConnection(id, peer, socket, httpUrl, cb, options) {
  5. if (!(this instanceof DataConnection)) return new DataConnection(options);
  6. EventEmitter.call(this);
  7. options = util.extend({
  8. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  9. reliable: false
  10. }, options);
  11. this._options = options;
  12. this._id = id;
  13. this._peer = peer;
  14. this._originator = (options.sdp === undefined);
  15. this._cb = cb;
  16. this._metadata = options.metadata;
  17. this._socket = socket;
  18. // Firefoxism: connectDataConnection ports.
  19. if (util.browserisms === 'Firefox') {
  20. this._firefoxPortSetup();
  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: this._options.reliable });
  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');
  71. this._pc = new RTCPeerConnection(this._options.config, { 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._socket.send({
  81. type: 'CANDIDATE',
  82. candidate: evt.candidate,
  83. dst: self._peer,
  84. src: self._id
  85. });
  86. }
  87. };
  88. };
  89. // Awaiting update in Firefox spec ***
  90. /** Sets up DataChannel handlers.
  91. DataConnection.prototype._setupDataChannel = function() {
  92. var self = this;
  93. if (this._originator) {
  94. if (util.browserisms === 'Webkit') {
  95. // TODO: figure out the right thing to do with this.
  96. this._pc.onstatechange = function() {
  97. util.log('State Change: ', self._pc.readyState);
  98. }
  99. } else {
  100. this._pc.onconnection = function() {
  101. util.log('ORIGINATOR: onconnection triggered');
  102. self._startDataChannel();
  103. };
  104. }
  105. } else {
  106. this._pc.onconnection = function() {
  107. util.log('SINK: onconnection triggered');
  108. };
  109. }
  110. this._pc.onclosedconnection = function() {
  111. // Remove socket handlers perhaps.
  112. self.emit('close', self._peer);
  113. };
  114. };
  115. */
  116. DataConnection.prototype._firefoxPortSetup = function() {
  117. if (!DataConnection.usedPorts) {
  118. DataConnection.usedPorts = [];
  119. }
  120. this.localPort = util.randomPort();
  121. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  122. this.localPort = util.randomPort();
  123. }
  124. this.remotePort = util.randomPort();
  125. while (this.remotePort === this.localPort ||
  126. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  127. this.remotePort = util.randomPort();
  128. }
  129. DataConnection.usedPorts.push(this.remotePort);
  130. DataConnection.usedPorts.push(this.localPort);
  131. }
  132. DataConnection.prototype._configureDataChannel = function() {
  133. var self = this;
  134. if (util.browserisms === 'Firefox') {
  135. this._dc.binaryType = 'blob';
  136. }
  137. this._dc.onopen = function() {
  138. util.log('Data channel connection success');
  139. self._cb(null, self);
  140. };
  141. this._dc.onmessage = function(e) {
  142. self._handleDataMessage(e);
  143. };
  144. };
  145. /** Decide whether to handle Firefoxisms. */
  146. DataConnection.prototype._firefoxAdditional = function() {
  147. var self = this;
  148. getUserMedia({ audio: true, fake: true }, function(s) {
  149. self._pc.addStream(s);
  150. if (self._originator) {
  151. self._makeOffer();
  152. } else {
  153. self._makeAnswer();
  154. }
  155. }, function(err) { util.log('Could not getUserMedia'); });
  156. }
  157. DataConnection.prototype._makeOffer = function() {
  158. var self = this;
  159. this._pc.createOffer(function(offer) {
  160. util.log('Created offer');
  161. self._pc.setLocalDescription(offer, function() {
  162. util.log('Set localDescription to offer');
  163. //self._peerReady = false;
  164. self._socket.send({
  165. type: 'OFFER',
  166. sdp: offer,
  167. dst: self._peer,
  168. src: self._id,
  169. metadata: self.metadata
  170. });
  171. }, function(err) {
  172. self._cb('Failed to setLocalDescription');
  173. util.log('Failed to setLocalDescription, ', err);
  174. });
  175. });
  176. };
  177. /** Create an answer for PC. */
  178. DataConnection.prototype._makeAnswer = function() {
  179. var self = this;
  180. this._pc.createAnswer(function(answer) {
  181. util.log('Created answer');
  182. self._pc.setLocalDescription(answer, function() {
  183. util.log('Set localDescription to answer');
  184. self._socket.send({
  185. type: 'ANSWER',
  186. src: self._id,
  187. sdp: answer,
  188. dst: self._peer
  189. });
  190. }, function(err) {
  191. self._cb('Failed to setLocalDescription');
  192. util.log('Failed to setLocalDescription, ', err)
  193. });
  194. }, function(err) {
  195. self._cb('Failed to create answer');
  196. util.log('Failed to create answer, ', err)
  197. });
  198. };
  199. DataConnection.prototype._cleanup = function() {
  200. if (!!this._pc && this._pc.readyState != 'closed') {
  201. this._pc.close();
  202. this._pc = null;
  203. }
  204. if (!!this._dc && this._dc.readyState != 'closed') {
  205. this._dc.close();
  206. this._dc = null;
  207. }
  208. this.emit('close', this._peer);
  209. };
  210. // Handles a DataChannel message.
  211. DataConnection.prototype._handleDataMessage = function(e) {
  212. var self = this;
  213. if (e.data.constructor === Blob) {
  214. util.blobToArrayBuffer(e.data, function(ab) {
  215. var data = BinaryPack.unpack(ab);
  216. self.emit('data', data);
  217. });
  218. } else if (e.data.constructor === ArrayBuffer) {
  219. var data = BinaryPack.unpack(e.data);
  220. self.emit('data', data);
  221. } else if (e.data.constructor === String) {
  222. var ab = util.binaryStringToArrayBuffer(e.data);
  223. var data = BinaryPack.unpack(ab);
  224. self.emit('data', data);
  225. }
  226. };
  227. /**
  228. * Exposed functionality for users.
  229. */
  230. /** Allows user to close connection. */
  231. DataConnection.prototype.close = function() {
  232. this._cleanup();
  233. var self = this;
  234. this._socket.send({
  235. type: 'LEAVE',
  236. dst: self._peer,
  237. src: self._id,
  238. });
  239. };
  240. /** Allows user to send data. */
  241. DataConnection.prototype.send = function(data) {
  242. var self = this;
  243. var blob = BinaryPack.pack(data);
  244. if (util.browserisms === 'Webkit') {
  245. util.blobToBinaryString(blob, function(str){
  246. self._dc.send(str);
  247. });
  248. } else {
  249. this._dc.send(blob);
  250. }
  251. };
  252. DataConnection.prototype.getMetadata = function() {
  253. return this._metadata;
  254. };
  255. DataConnection.prototype.handleSDP = function(message) {
  256. var sdp = message.sdp;
  257. if (util.browserisms != 'Firefox') {
  258. sdp = new RTCSessionDescription(sdp);
  259. }
  260. var self = this;
  261. this._pc.setRemoteDescription(sdp, function() {
  262. util.log('Set remoteDescription: ' + message.type);
  263. // Firefoxism
  264. if (message.type === 'ANSWER' && util.browserisms === 'Firefox') {
  265. self._pc.connectDataConnection(self.localPort, self.remotePort);
  266. self._socket.send({
  267. type: 'PORT',
  268. dst: self._peer,
  269. src: self._id,
  270. remote: self.localPort,
  271. local: self.remotePort
  272. });
  273. }
  274. }, function(err) {
  275. this._cb('Failed to setRemoteDescription');
  276. util.log('Failed to setRemoteDescription, ', err);
  277. });
  278. };
  279. DataConnection.prototype.handleCandidate = function(message) {
  280. var candidate = new RTCIceCandidate(message.candidate);
  281. this._pc.addIceCandidate(candidate);
  282. util.log('Added ice candidate');
  283. };
  284. DataConnection.prototype.handleLeave = function() {
  285. util.log('Peer ' + this._peer + ' disconnected');
  286. this._cleanup();
  287. };
  288. DataConnection.prototype.handlePort = function(message) {
  289. if (!DataConnection.usedPorts) {
  290. DataConnection.usedPorts = [];
  291. }
  292. DataConnection.usedPorts.push(message.local);
  293. DataConnection.usedPorts.push(message.remote);
  294. this._pc.connectDataConnection(message.local, message.remote);
  295. };