<commit_before>"use strict";
/**
 * @fileoverview MediaHandler
 */

/* MediaHandler
 * @class PeerConnection helper Class.
 * @param {SIP.Session} session
 * @param {Object} [options]
 * @param {SIP.WebRTC.MediaStreamManager} [options.mediaStreamManager]
 *        The MediaStreamManager to acquire/release streams from/to.
 *        If not provided, a default MediaStreamManager will be used.
 */
module.exports = function (SIP) {

var MediaHandler = function(session, options) {
  options = options || {};

  this.logger = session.ua.getLogger('sip.invitecontext.mediahandler', session.id);
  this.session = session;
  this.localMedia = null;
  this.ready = true;
  this.mediaStreamManager = options.mediaStreamManager || new SIP.WebRTC.MediaStreamManager(this.logger);
  this.audioMuted = false;
  this.videoMuted = false;

  // old init() from here on
  var idx, jdx, length, server,
    self = this,
    servers = [],
    stunServers = options.stunServers || null,
    turnServers = options.turnServers || null,
    config = this.session.ua.configuration;
  this.RTCConstraints = options.RTCConstraints || {};

  if (!stunServers) {
    stunServers = config.stunServers;
  }

  if(!turnServers) {
    turnServers = config.turnServers;
  }

  /* Change 'url' to 'urls' whenever this issue is solved:
   * https://code.google.com/p/webrtc/issues/detail?id=2096
   */
  [].concat(stunServers).forEach(function (server) {
    servers.push({'url': server});
  });

  length = turnServers.length;
  for (idx = 0; idx < length; idx++) {
    server = turnServers[idx];
    for (jdx = 0; jdx < server.urls.length; jdx++) {
      servers.push({
        'url': server.urls[jdx],
        'username': server.username,
        'credential': server.password
      });
    }
  }

  this.onIceCompleted = SIP.Utils.defer();
  this.onIceCompleted.promise.then(function(pc) {
    self.emit('iceGatheringComplete', pc);
    if (self.iceCheckingTimer) {
      SIP.Timers.clearTimeout(self.iceCheckingTimer);
      self.iceCheckingTimer = null;
    }
  });

  this.peerConnection = new SIP.WebRTC.RTCPeerConnection({'iceServers': servers}, this.RTCConstraints);

  // Firefox (35.0.1) sometimes throws on calls to peerConnection.getRemoteStreams
  // even if peerConnection.onaddstream was just called. In order to make
  // MediaHandler.prototype.getRemoteStreams work, keep track of them manually
  this._remoteStreams = [];

  this.peerConnection.onaddstream = function(e) {
    self.logger.log('stream added: '+ e.stream.id);
    self._remoteStreams.push(e.stream);
    self.render();
    self.emit('addStream', e);
  };

  this.peerConnection.onremovestream = function(e) {
    self.logger.log('stream removed: '+ e.stream.id);
  };

  this.peerConnection.onicecandidate = function(e) {
    self.emit('iceCandidate', e);
    if (e.candidate) {
      self.logger.log('ICE candidate received: '+ (e.candidate.candidate === null ? null : e.candidate.candidate.trim()));
      if (!self.iceCheckingTimer) {
        self.iceCheckingTimer = SIP.Timers.setTimeout(function() {
          self.logger.log('RTCIceChecking Timeout Triggered after '+config.iceCheckingTimeout+' milliseconds');
          self.onIceCompleted.resolve(this);
        }.bind(this), config.iceCheckingTimeout);
      }
    } else {
      self.onIceCompleted.resolve(this);
    }
  };

  this.peerConnection.onicegatheringstatechange = function () {
    self.logger.log('RTCIceGatheringState changed: ' + this.iceGatheringState);
    if (this.iceGatheringState === 'gathering') {
      self.emit('iceGathering', this);
    }
    if (this.iceGatheringState === 'complete') {
      self.onIceCompleted.resolve(this);
    }
  };

  this.peerConnection.oniceconnectionstatechange = function() {  //need e for commented out case
    var stateEvent;

    if (this.iceConnectionState === 'checking' && !self.iceCheckingTimer) {
      self.iceCheckingTimer = SIP.Timers.setTimeout(function() {
        self.logger.log('RTCIceChecking Timeout Triggered after '+config.iceCheckingTimeout+' milliseconds');
        self.onIceCompleted.resolve(this);
      }.bind(this), config.iceCheckingTimeout);
    }
<commit_msg>WebRTC.MediaHandler: dedupe code that starts iceCheckingTimer<commit_after>"use strict";
/**
 * @fileoverview MediaHandler
 */

/* MediaHandler
 * @class PeerConnection helper Class.
 * @param {SIP.Session} session
 * @param {Object} [options]
 * @param {SIP.WebRTC.MediaStreamManager} [options.mediaStreamManager]
 *        The MediaStreamManager to acquire/release streams from/to.
 *        If not provided, a default MediaStreamManager will be used.
 */
module.exports = function (SIP) {

var MediaHandler = function(session, options) {
  options = options || {};

  this.logger = session.ua.getLogger('sip.invitecontext.mediahandler', session.id);
  this.session = session;
  this.localMedia = null;
  this.ready = true;
  this.mediaStreamManager = options.mediaStreamManager || new SIP.WebRTC.MediaStreamManager(this.logger);
  this.audioMuted = false;
  this.videoMuted = false;

  // old init() from here on
  var idx, jdx, length, server,
    self = this,
    servers = [],
    stunServers = options.stunServers || null,
    turnServers = options.turnServers || null,
    config = this.session.ua.configuration;
  this.RTCConstraints = options.RTCConstraints || {};

  if (!stunServers) {
    stunServers = config.stunServers;
  }

  if(!turnServers) {
    turnServers = config.turnServers;
  }

  /* Change 'url' to 'urls' whenever this issue is solved:
   * https://code.google.com/p/webrtc/issues/detail?id=2096
   */
  [].concat(stunServers).forEach(function (server) {
    servers.push({'url': server});
  });

  length = turnServers.length;
  for (idx = 0; idx < length; idx++) {
    server = turnServers[idx];
    for (jdx = 0; jdx < server.urls.length; jdx++) {
      servers.push({
        'url': server.urls[jdx],
        'username': server.username,
        'credential': server.password
      });
    }
  }

  this.onIceCompleted = SIP.Utils.defer();
  this.onIceCompleted.promise.then(function(pc) {
    self.emit('iceGatheringComplete', pc);
    if (self.iceCheckingTimer) {
      SIP.Timers.clearTimeout(self.iceCheckingTimer);
      self.iceCheckingTimer = null;
    }
  });

  this.peerConnection = new SIP.WebRTC.RTCPeerConnection({'iceServers': servers}, this.RTCConstraints);

  // Firefox (35.0.1) sometimes throws on calls to peerConnection.getRemoteStreams
  // even if peerConnection.onaddstream was just called. In order to make
  // MediaHandler.prototype.getRemoteStreams work, keep track of them manually
  this._remoteStreams = [];

  this.peerConnection.onaddstream = function(e) {
    self.logger.log('stream added: '+ e.stream.id);
    self._remoteStreams.push(e.stream);
    self.render();
    self.emit('addStream', e);
  };

  this.peerConnection.onremovestream = function(e) {
    self.logger.log('stream removed: '+ e.stream.id);
  };

  this.startIceCheckingTimer = function () {
    if (!self.iceCheckingTimer) {
      self.iceCheckingTimer = SIP.Timers.setTimeout(function() {
        self.logger.log('RTCIceChecking Timeout Triggered after '+config.iceCheckingTimeout+' milliseconds');
        self.onIceCompleted.resolve(this);
      }.bind(this.peerConnection), config.iceCheckingTimeout);
    }
  };

  this.peerConnection.onicecandidate = function(e) {
    self.emit('iceCandidate', e);
    if (e.candidate) {
      self.logger.log('ICE candidate received: '+ (e.candidate.candidate === null ? null : e.candidate.candidate.trim()));
      self.startIceCheckingTimer();
    } else {
      self.onIceCompleted.resolve(this);
    }
  };

  this.peerConnection.onicegatheringstatechange = function () {
    self.logger.log('RTCIceGatheringState changed: ' + this.iceGatheringState);
    if (this.iceGatheringState === 'gathering') {
      self.emit('iceGathering', this);
    }
    if (this.iceGatheringState === 'complete') {
      self.onIceCompleted.resolve(this);
    }
  };

  this.peerConnection.oniceconnectionstatechange = function() {  //need e for commented out case
    var stateEvent;

    if (this.iceConnectionState === 'checking') {
      self.startIceCheckingTimer();
    }

{'fraction_non_alphanumeric': 0.13722859233959503, 'fraction_numerical': 0.0024396194193705783, 'mean_word_length': 3.5499445061043287, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 3, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7430611', 'n_tokens_mistral': 2657, 'n_tokens_neox': 2565, 'n_words': 493}