<commit_before>/**
 * DataPeer
 * Assumes that RTCPeerConnection is defined.
 */
 (function (exports) {
   "use strict";

//-----------------------------------------------------------------------------
// Console debugging utilities
//-----------------------------------------------------------------------------
// Abbreviation for console['type'] (type = log/warn/error) that inserts time at
// front.
function trace_to_console(type) {
  var argsArray = [];
  for (var i = 1; i < arguments.length; i++) {
    argsArray[i - 1] = arguments[i];
  }
  var text = argsArray[0];
  var s = (performance.now() / 1000).toFixed(3) + ": " + text;
  argsArray[0] = s;
  console[type].apply(console, argsArray);
}
var trace = {
  log: trace_to_console.bind(null, "log"),
  warn: trace_to_console.bind(null, "warn"),
  error: trace_to_console.bind(null, "error"),
};

//-----------------------------------------------------------------------------
// A class that wraps a peer connection and its data channels.
//-----------------------------------------------------------------------------
// TODO: check that Handling of pranswer is treated appropriately.
var SimpleDataPeerState = {
  DISCONNECTED: 'DISCONNECTED',
  CONNECTING: 'CONNECTING',
  CONNECTED: 'CONNECTED'
};

function SimpleDataPeer(peerName) {
  this.peerName = peerName;

  // depending on environment, select implementation.
  var RTCPeerConnection = RTCPeerConnection || webkitRTCPeerConnection || mozRTCPeerConnection;
  //TODO wire up STUN/TURN server config from options page
  var static_pc_config = [
    "stun:stun.l.google.com:19302",
    "stun:stun1.l.google.com:19302",
    "stun:stun2.l.google.com:19302",
    "stun:stun3.l.google.com:19302",
    "stun:stun4.l.google.com:19302" // ,
    // "turn:stun.l.google.com:19302"
  ];

  var constraints = {optional: [{DtlsSrtpKeyAgreement: true}]};
  // A way to speak to the peer to send SDP headers etc.
  this._sendSignalMessage = null;
  this._turnRequest = new XMLHttpRequest();

  this._pc = null;  // The peer connection.
  this._pc_runQueue = [];
  // Get TURN servers for the peer connection.
  this._turnRequest.onreadystatechange = function() {
    var i;
    if (this._turnRequest.readyState == 4) {
      var turn_response = null;
      try {
        var parsed = JSON.parse(this._turnRequest.response);
        var iceServer;
        turn_response = {iceServers: []};
        for (i = 0; i < static_pc_config.length; i++) {
          iceServer = { 'url' : static_pc_config[i] };
          turn_response.iceServers.push(iceServer);
        }
        for (i = 0; i < parsed.uris.length; i++) {
          var server_parts = parsed.uris[i].split("?");
          iceServer = { 'url' : server_parts[0],
                        'credential' : parsed.password,
                        'username' : parsed.username };
          turn_response.iceServers.push(iceServer);
        }
      } catch (e) {
        console.log("Invalid TURN response: " + this._turnRequest.response);
      }
      console.log("Got back TURN data: " + JSON.stringify(turn_response));
      this._pc = new RTCPeerConnection(turn_response, constraints);
      // Add basic event handlers.
      this._pc.addEventListener("icecandidate",
                                this._onIceCallback.bind(this));
      this._pc.addEventListener("negotiationneeded",
                                this._onNegotiationNeeded.bind(this));
      this._pc.addEventListener("signalingstatechange",
                                function () {
                                  if (this._pc.signalingState == "stable") {
                                    this._pcState = SimpleDataPeerState.CONNECTED;
                                  }
                                }.bind(this));
      // drain this._pc_runQueue.  As this._pc is no longer null, it
      // won't get modified while we run the callbacks.
      for (i = 0; i < this._pc_runQueue.length; i++) {
        var listener = this._pc_runQueue[i];
        listener();
      }
      this._pc_runQueue = [];
    } else  {
      console.log("Got back no TURN data: " + this._turnRequest.readyState);
      // this._pc = new RTCPeerConnection(null, constraints);
    }
  }.bind(this);
  var request_key = Math.floor(Math.random() * 1e8);
  this._turnRequest.open('GET',
                         'https://computeengineondemand.appspot.com/turn?username=UProxy&key=' + request_key);
  this._turnRequest.send(null);
  // This state variable is used to fake offer/answer when they are wrongly
  // requested and we really just need to reuse what we already have.
  this._pcState = SimpleDataPeerState.DISCONNECTED;

  // Note: to actually do something with data channels opened by a peer, we
  // need someone to manage "datachannel" event.
}

// Queue 'func', a 0-arg closure, for invocation when the TURN server
// gets back to us, and we have a valid RTCPeerConnection in this._pc.
// If we already have it, run func immediately.
SimpleDataPeer.prototype.runWhenReady = function(func) {
  if (this._pc === null) {
    // we're still waiting.
    this._pc_runQueue.push(func);
  } else {
    func();
  }
};

SimpleDataPeer.prototype.addPCEventListener = function(event, func) {
  this._pc_listeners.push({event: event, func: func});
};

SimpleDataPeer.prototype._onSignalingStateChange = function () {
//  trace.log(this.peerName + ": " + "_onSignalingStateChange: ",
//      this._pc.signalingState);
  if (this._pc.signalingState == "stable") {
    this._pcState = SimpleDataPeerState.CONNECTED;
  }<commit_msg>Small log and cleanup on TURN acquisition.<commit_after>/**
 * DataPeer
 * Assumes that RTCPeerConnection is defined.
 */
 (function (exports) {
   "use strict";

//-----------------------------------------------------------------------------
// Console debugging utilities
//-----------------------------------------------------------------------------
// Abbreviation for console['type'] (type = log/warn/error) that inserts time at
// front.
function trace_to_console(type) {
  var argsArray = [];
  for (var i = 1; i < arguments.length; i++) {
    argsArray[i - 1] = arguments[i];
  }
  var text = argsArray[0];
  var s = (performance.now() / 1000).toFixed(3) + ": " + text;
  argsArray[0] = s;
  console[type].apply(console, argsArray);
}
var trace = {
  log: trace_to_console.bind(null, "log"),
  warn: trace_to_console.bind(null, "warn"),
  error: trace_to_console.bind(null, "error"),
};

//-----------------------------------------------------------------------------
// A class that wraps a peer connection and its data channels.
//-----------------------------------------------------------------------------
// TODO: check that Handling of pranswer is treated appropriately.
var SimpleDataPeerState = {
  DISCONNECTED: 'DISCONNECTED',
  CONNECTING: 'CONNECTING',
  CONNECTED: 'CONNECTED'
};

function SimpleDataPeer(peerName) {
  this.peerName = peerName;

  // depending on environment, select implementation.
  var RTCPeerConnection = RTCPeerConnection || webkitRTCPeerConnection || mozRTCPeerConnection;
  //TODO wire up STUN/TURN server config from options page
  var static_pc_config = [
    "stun:stun.l.google.com:19302",
    "stun:stun1.l.google.com:19302",
    "stun:stun2.l.google.com:19302",
    "stun:stun3.l.google.com:19302",
    "stun:stun4.l.google.com:19302" // ,
    // "turn:stun.l.google.com:19302"
  ];

  var constraints = {optional: [{DtlsSrtpKeyAgreement: true}]};
  // A way to speak to the peer to send SDP headers etc.
  this._sendSignalMessage = null;
  this._turnRequest = new XMLHttpRequest();

  this._pc = null;  // The peer connection.
  this._pc_runQueue = [];
  // Get TURN servers for the peer connection.
  this._turnRequest.onreadystatechange = function() {
    var i;
    if (this._turnRequest.readyState == 4) {
      var turn_response = null;
      try {
        var parsed = JSON.parse(this._turnRequest.response);
        var iceServer;
        turn_response = {iceServers: []};
        for (i = 0; i < static_pc_config.length; i++) {
          iceServer = { 'url' : static_pc_config[i] };
          turn_response.iceServers.push(iceServer);
        }
        for (i = 0; i < parsed.uris.length; i++) {
          var server_parts = parsed.uris[i].split("?");
          iceServer = { 'url' : server_parts[0],
                        'credential' : parsed.password,
                        'username' : parsed.username };
          turn_response.iceServers.push(iceServer);
        }
      } catch (e) {
        console.log("Invalid TURN response: " + this._turnRequest.response);
      }
      console.log("Got back TURN data: " + JSON.stringify(turn_response));
      this._pc = new RTCPeerConnection(turn_response, constraints);
      // Add basic event handlers.
      this._pc.addEventListener("icecandidate",
                                this._onIceCallback.bind(this));
      this._pc.addEventListener("negotiationneeded",
                                this._onNegotiationNeeded.bind(this));
      this._pc.addEventListener("signalingstatechange",
                                function () {
                                  if (this._pc.signalingState == "stable") {
                                    this._pcState = SimpleDataPeerState.CONNECTED;
                                  }
                                }.bind(this));
      // drain this._pc_runQueue.  As this._pc is no longer null, it
      // won't get modified while we run the callbacks.
      for (i = 0; i < this._pc_runQueue.length; i++) {
        var listener = this._pc_runQueue[i];
        listener();
      }
      this._pc_runQueue = [];
    } else  {
      console.log("Got back no TURN data: " + this._turnRequest.readyState);
      // this._pc = new RTCPeerConnection(null, constraints);
    }
  }.bind(this);
  var request_key = Math.floor(Math.random() * 1e8);
  console.log('Requesting TURN from ' +
      'https://computeengineondemand.appspot.com/turn?username=UProxy&key=' + request_key);
  this._turnRequest.open(
      'GET', 'https://computeengineondemand.appspot.com/turn?username=UProxy&key=' +
      request_key);
  this._turnRequest.send(null);
  // This state variable is used to fake offer/answer when they are wrongly
  // requested and we really just need to reuse what we already have.
  this._pcState = SimpleDataPeerState.DISCONNECTED;

  // Note: to actually do something with data channels opened by a peer, we
  // need someone to manage "datachannel" event.
}

// Queue 'func', a 0-arg closure, for invocation when the TURN server
// gets back to us, and we have a valid RTCPeerConnection in this._pc.
// If we already have it, run func immediately.
SimpleDataPeer.prototype.runWhenReady = function(func) {
  if (this._pc === null) {
    // we're still waiting.
    this._pc_runQueue.push(func);
  } else {
    func();
  }
};

SimpleDataPeer.prototype.addPCEventListener = function(event, func) {
  this._pc_listeners.push({event: event, func: func});
};

SimpleDataPeer.prototype._onSignalingStateChange = function () {
//  trace.log(this.peerName + ": " + "_onSignalingStateChange: ",
//      this._pc.signalingState);
  if (this._pc.signalingState == "stable") {
    this._pcState = SimpleDataPeerState.CONNECTED;
  }
{'fraction_non_alphanumeric': 0.17608328143073226, 'fraction_numerical': 0.009075540528516772, 'mean_word_length': 2.1931818181818183, 'pattern_counts': {'":': 4, '<': 11, '<?xml version=': 0, '>': 3, 'https://': 3, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3178101', 'n_tokens_mistral': 3395, 'n_tokens_neox': 3260, 'n_words': 778}