<commit_before>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */

/* globals setCodecParam, removeCodecParam, displayError, displayStatus,
   gatheredIceCandidateTypes, hasTurnServer, iceCandidateType, localStream,
   maybePreferAudioReceiveCodec, maybePreferAudioSendCodec,
   maybePreferVideoReceiveCodec, maybePreferVideoSendCodec,
   maybeSetAudioReceiveBitRate, maybeSetAudioSendBitRate,
   maybeSetVideoReceiveBitRate, maybeSetVideoSendBitRate,
   maybeSetVideoSendInitialBitRate, mergeConstraints, onRemoteHangup,
   onUserMediaError, onUserMediaSuccess, params, parseJSON, pc:true,
   remoteStream:true, remoteVideo, requestTurnServers, sendAsyncUrlRequest,
   requestUserMedia, sdpConstraints, sharingDiv, webSocket:true, startTime:true,
   transitionToActive, updateInfoDiv, waitForRemoteVideo */
/* exported connectToRoom, openSignalingChannel */

'use strict';

var isSignalingChannelReady = false;
var hasLocalStream = false;
var hasReceivedOffer = false;
var messageQueue = [];

// Connects client to the room. This happens by simultaneously requesting
// media, requesting turn, and registering with GAE. Once all three of those
// tasks is complete, the signaling process begins. At the same time, a
// WebSocket connection is opened using |wss_url| followed by a subsequent
// registration once GAE registration completes.
function connectToRoom(roomId) {
  var mediaPromise = getMediaIfNeeded();
  var turnPromise = getTurnServersIfNeeded();

  // Asynchronously open a WebSocket connection to WSS.
  var channelPromise = openSignalingChannel().catch(function(error) {
    displayError(error.message);
    return Promise.reject(error);
  });

  // Asynchronously register with GAE.
  var registerPromise = registerWithGAE(roomId).then(function(roomParams) {
    // The only difference in parameters should be clientId and isInitiator,
    // and the turn servers that we requested.
    // TODO(tkchin): clean up response format. JSHint doesn't like it either.
    /* jshint ignore:start */
    params.clientId = roomParams.client_id;
    params.roomId = roomParams.room_id;
    params.isInitiator = roomParams.is_initiator === 'true';
    /* jshint ignore:end */
    params.messages = roomParams.messages;
  }).catch(function(error) {
    displayError(error.message);
    return Promise.reject(error);
  });

  // We only register with WSS if the web socket connection is open and if we're
  // already registered with GAE.
  Promise.all([channelPromise, registerPromise]).then(function() {
    registerWithWSS(params.roomId, params.clientId);
  }).catch(function(error) {
    displayError('Could not begin WSS registration: ' + error.message);
  });

  // We only create a peer connection once we have media and TURN. Since right
  // now we send candidates as soon as the peer connection generates them we
  // need to wait for registration as well.
  // TODO(tkchin): create peer connection earlier, but only send candidates if
  // registration has occurred.
  Promise.all([registerPromise, turnPromise, mediaPromise]).then(function() {
    startSignaling();
  }).catch(function(error) {
    displayError('Could not begin signaling: ' + error.message);
  });
}

// Asynchronously request user media if needed.
function getMediaIfNeeded() {
  // params.mediaConstraints.audio and params.mediaConstraints.video could be
  // objects, so check '!=== false' instead of '=== true'.
  hasLocalStream = (params.mediaConstraints.audio !== false ||
                    params.mediaConstraints.video !== false);
  var mediaPromise = null;
  if (hasLocalStream) {
    var mediaConstraints = params.mediaConstraints;
    mediaPromise = requestUserMedia(mediaConstraints).then(function(stream) {
      trace('Got access to local media with mediaConstraints:\n' +
          '  \'' + JSON.stringify(mediaConstraints) + '\'');
      onUserMediaSuccess(stream);
    }).catch(function(error) {
      trace('Error getting user media: ' + error.message);
      alert('getUserMedia() failed. Is this a WebRTC capable browser?');

      hasLocalStream = false;
      onUserMediaError(error);
    });
  } else {
    mediaPromise = Promise.resolve();
  }
  return mediaPromise;
}

// Asynchronously request a TURN server if needed.
function getTurnServersIfNeeded() {
  var shouldRequestTurnServers = !hasTurnServer(params) &&
      (params.turnRequestUrl && params.turnRequestUrl.length > 0);
  var turnPromise = null;
  if (shouldRequestTurnServers) {
    var requestUrl = params.turnRequestUrl;
    turnPromise = requestTurnServers(requestUrl).then(function(turnServers) {
      var iceServers = params.peerConnectionConfig.iceServers;
      params.peerConnectionConfig.iceServers = iceServers.concat(turnServers);
    }).catch(function(error) {
      // Error retrieving TURN servers.
      var subject =
          encodeURIComponent('AppRTC demo TURN server not working');
      displayStatus('No TURN server; unlikely that media will traverse' +<commit_msg>Added space to TURN message<commit_after>/*
 *  Copyright (c) 2014 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree.
 */

/* More information about these options at jshint.com/docs/options */

/* globals setCodecParam, removeCodecParam, displayError, displayStatus,
   gatheredIceCandidateTypes, hasTurnServer, iceCandidateType, localStream,
   maybePreferAudioReceiveCodec, maybePreferAudioSendCodec,
   maybePreferVideoReceiveCodec, maybePreferVideoSendCodec,
   maybeSetAudioReceiveBitRate, maybeSetAudioSendBitRate,
   maybeSetVideoReceiveBitRate, maybeSetVideoSendBitRate,
   maybeSetVideoSendInitialBitRate, mergeConstraints, onRemoteHangup,
   onUserMediaError, onUserMediaSuccess, params, parseJSON, pc:true,
   remoteStream:true, remoteVideo, requestTurnServers, sendAsyncUrlRequest,
   requestUserMedia, sdpConstraints, sharingDiv, webSocket:true, startTime:true,
   transitionToActive, updateInfoDiv, waitForRemoteVideo */
/* exported connectToRoom, openSignalingChannel */

'use strict';

var isSignalingChannelReady = false;
var hasLocalStream = false;
var hasReceivedOffer = false;
var messageQueue = [];

// Connects client to the room. This happens by simultaneously requesting
// media, requesting turn, and registering with GAE. Once all three of those
// tasks is complete, the signaling process begins. At the same time, a
// WebSocket connection is opened using |wss_url| followed by a subsequent
// registration once GAE registration completes.
function connectToRoom(roomId) {
  var mediaPromise = getMediaIfNeeded();
  var turnPromise = getTurnServersIfNeeded();

  // Asynchronously open a WebSocket connection to WSS.
  var channelPromise = openSignalingChannel().catch(function(error) {
    displayError(error.message);
    return Promise.reject(error);
  });

  // Asynchronously register with GAE.
  var registerPromise = registerWithGAE(roomId).then(function(roomParams) {
    // The only difference in parameters should be clientId and isInitiator,
    // and the turn servers that we requested.
    // TODO(tkchin): clean up response format. JSHint doesn't like it either.
    /* jshint ignore:start */
    params.clientId = roomParams.client_id;
    params.roomId = roomParams.room_id;
    params.isInitiator = roomParams.is_initiator === 'true';
    /* jshint ignore:end */
    params.messages = roomParams.messages;
  }).catch(function(error) {
    displayError(error.message);
    return Promise.reject(error);
  });

  // We only register with WSS if the web socket connection is open and if we're
  // already registered with GAE.
  Promise.all([channelPromise, registerPromise]).then(function() {
    registerWithWSS(params.roomId, params.clientId);
  }).catch(function(error) {
    displayError('Could not begin WSS registration: ' + error.message);
  });

  // We only create a peer connection once we have media and TURN. Since right
  // now we send candidates as soon as the peer connection generates them we
  // need to wait for registration as well.
  // TODO(tkchin): create peer connection earlier, but only send candidates if
  // registration has occurred.
  Promise.all([registerPromise, turnPromise, mediaPromise]).then(function() {
    startSignaling();
  }).catch(function(error) {
    displayError('Could not begin signaling: ' + error.message);
  });
}

// Asynchronously request user media if needed.
function getMediaIfNeeded() {
  // params.mediaConstraints.audio and params.mediaConstraints.video could be
  // objects, so check '!=== false' instead of '=== true'.
  hasLocalStream = (params.mediaConstraints.audio !== false ||
                    params.mediaConstraints.video !== false);
  var mediaPromise = null;
  if (hasLocalStream) {
    var mediaConstraints = params.mediaConstraints;
    mediaPromise = requestUserMedia(mediaConstraints).then(function(stream) {
      trace('Got access to local media with mediaConstraints:\n' +
          '  \'' + JSON.stringify(mediaConstraints) + '\'');
      onUserMediaSuccess(stream);
    }).catch(function(error) {
      trace('Error getting user media: ' + error.message);
      alert('getUserMedia() failed. Is this a WebRTC capable browser?');

      hasLocalStream = false;
      onUserMediaError(error);
    });
  } else {
    mediaPromise = Promise.resolve();
  }
  return mediaPromise;
}

// Asynchronously request a TURN server if needed.
function getTurnServersIfNeeded() {
  var shouldRequestTurnServers = !hasTurnServer(params) &&
      (params.turnRequestUrl && params.turnRequestUrl.length > 0);
  var turnPromise = null;
  if (shouldRequestTurnServers) {
    var requestUrl = params.turnRequestUrl;
    turnPromise = requestTurnServers(requestUrl).then(function(turnServers) {
      var iceServers = params.peerConnectionConfig.iceServers;
      params.peerConnectionConfig.iceServers = iceServers.concat(turnServers);
    }).catch(function(error) {
      // Error retrieving TURN servers.
      var subject =
          encodeURIComponent('AppRTC demo TURN server not working');
      displayStatus('No TURN server; unlikely that media will traverse ' +
{'fraction_non_alphanumeric': 0.09573141486810552, 'fraction_numerical': 0.0009592326139088729, 'mean_word_length': 4.207792207792208, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, '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': '3005908', 'n_tokens_mistral': 2866, 'n_tokens_neox': 2807, 'n_words': 848}