<commit_before>// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/geolocation/network_location_request.h"

#include <set>

#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/common/geoposition.h"
#include "content/common/net/url_fetcher_impl.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"

namespace {

const size_t kMaxRequestLength = 2048;

const char kAccessTokenString[] = "access_token";
const char kLocationString[] = "location";
const char kLatitudeString[] = "lat";
const char kLongitudeString[] = "lng";
const char kAccuracyString[] = "accuracy";
const char kStatusString[] = "status";
const char kStatusOKString[] = "OK";

// Local functions
// Creates the request url to send to the server.
GURL FormRequestURL(const std::string& url,
                    const string16& access_token,
                    const WifiData& wifi_data,
                    const base::Time& timestamp);

// Parsers the server response.
void GetLocationFromResponse(bool http_post_result,
                             int status_code,
                             const std::string& response_body,
                             const base::Time& timestamp,
                             const GURL& server_url,
                             Geoposition* position,
                             string16* access_token);

// Parses the server response body. Returns true if parsing was successful.
// Sets |*position| to the parsed location if a valid fix was received,
// otherwise leaves it unchanged (i.e. IsInitialized() == false).
bool ParseServerResponse(const std::string& response_body,
                         const base::Time& timestamp,
                         Geoposition* position,
                         string16* access_token);
void AddWifiData(const WifiData& wifi_data,
                 int age_milliseconds,
                 std::vector<std::string>* params);
}  // namespace

int NetworkLocationRequest::url_fetcher_id_for_tests = 0;

NetworkLocationRequest::NetworkLocationRequest(
    net::URLRequestContextGetter* context,
    const GURL& url,
    ListenerInterface* listener)
        : url_context_(context), listener_(listener),
          url_(url) {
  DCHECK(listener);
}

NetworkLocationRequest::~NetworkLocationRequest() {
}

bool NetworkLocationRequest::MakeRequest(const std::string& host_name,
                                         const string16& access_token,
                                         const RadioData& radio_data,
                                         const WifiData& wifi_data,
                                         const base::Time& timestamp) {
  if (url_fetcher_ != NULL) {
    DVLOG(1) << "NetworkLocationRequest : Cancelling pending request";
    url_fetcher_.reset();
  }
  radio_data_ = radio_data;
  wifi_data_ = wifi_data;
  timestamp_ = timestamp;

  GURL request_url = FormRequestURL(url_.spec(), access_token,
                                    wifi_data, timestamp_);
  url_fetcher_.reset(URLFetcherImpl::Create(
      url_fetcher_id_for_tests, request_url, URLFetcherImpl::GET, this));
  url_fetcher_->SetRequestContext(url_context_);
  url_fetcher_->SetLoadFlags(
      net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
      net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
      net::LOAD_DO_NOT_SEND_AUTH_DATA);

  url_fetcher_->Start();
  return true;
}

void NetworkLocationRequest::OnURLFetchComplete(
    const content::URLFetcher* source) {
  DCHECK_EQ(url_fetcher_.get(), source);

  net::URLRequestStatus status = source->GetStatus();
  int response_code = source->GetResponseCode();

  Geoposition position;
  string16 access_token;
  std::string data;
  source->GetResponseAsString(&data);
  GetLocationFromResponse(status.is_success(),
                          response_code,
                          data,
                          timestamp_,
                          source->GetURL(),
                          &position,
                          &access_token);
  const bool server_error =
      !status.is_success() || (response_code >= 500 && response_code < 600);
  url_fetcher_.reset();

  DCHECK(listener_);
  DVLOG(1) << "NetworkLocationRequest::Run() : Calling listener with position.";
  listener_->LocationResponseAvailable(position, server_error, access_token,
                                       radio_data_, wifi_data_);
}

// Local functions.
namespace {

struct AccessPointLess {
  bool operator()(const AccessPointData* ap1,
                  const AccessPointData* ap2) const {
    return ap2->radio_signal_strength < ap1->radio_signal_strength;
  }
};

GURL FormRequestURL(const std::string& url,
                    const string16& access_token,
                    const WifiData& wifi_data,
                    const base::Time& timestamp) {
  int age = kint32min;  // Invalid so AddInteger() will ignore.
  if (!timestamp.is_null()) {
    // Convert absolute timestamps into a relative age.
    int64 delta_ms = (base::Time::Now() - timestamp).InMilliseconds();
    if (delta_ms >= 0 && delta_ms < kint32max)
      age = static_cast<int>(delta_ms);
  }

  std::vector<std::string> params;
  params.push_back("browser=chromium");
  params.push_back("sensor=true");
  if (!access_token.empty())
    params.push_back("token=" + UTF16ToUTF8(access_token));
  AddWifiData(wifi_data, age, &params);

  std::string request_string = url + '?' + JoinString(params, '&');
  if (request_string.length() > kMaxRequestLength) {
    size_t last_param_pos =
        request_string.find_last_of('&', kMaxRequestLength);<commit_msg>Change geolocaiton browser name in official builds<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/geolocation/network_location_request.h"

#include <set>

#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/string_number_conversions.h"
#include "base/utf_string_conversions.h"
#include "base/values.h"
#include "content/common/geoposition.h"
#include "content/common/net/url_fetcher_impl.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"

namespace {

const size_t kMaxRequestLength = 2048;

const char kAccessTokenString[] = "access_token";
const char kLocationString[] = "location";
const char kLatitudeString[] = "lat";
const char kLongitudeString[] = "lng";
const char kAccuracyString[] = "accuracy";
const char kStatusString[] = "status";
const char kStatusOKString[] = "OK";

// Local functions
// Creates the request url to send to the server.
GURL FormRequestURL(const std::string& url,
                    const string16& access_token,
                    const WifiData& wifi_data,
                    const base::Time& timestamp);

// Parsers the server response.
void GetLocationFromResponse(bool http_post_result,
                             int status_code,
                             const std::string& response_body,
                             const base::Time& timestamp,
                             const GURL& server_url,
                             Geoposition* position,
                             string16* access_token);

// Parses the server response body. Returns true if parsing was successful.
// Sets |*position| to the parsed location if a valid fix was received,
// otherwise leaves it unchanged (i.e. IsInitialized() == false).
bool ParseServerResponse(const std::string& response_body,
                         const base::Time& timestamp,
                         Geoposition* position,
                         string16* access_token);
void AddWifiData(const WifiData& wifi_data,
                 int age_milliseconds,
                 std::vector<std::string>* params);
}  // namespace

int NetworkLocationRequest::url_fetcher_id_for_tests = 0;

NetworkLocationRequest::NetworkLocationRequest(
    net::URLRequestContextGetter* context,
    const GURL& url,
    ListenerInterface* listener)
        : url_context_(context), listener_(listener),
          url_(url) {
  DCHECK(listener);
}

NetworkLocationRequest::~NetworkLocationRequest() {
}

bool NetworkLocationRequest::MakeRequest(const std::string& host_name,
                                         const string16& access_token,
                                         const RadioData& radio_data,
                                         const WifiData& wifi_data,
                                         const base::Time& timestamp) {
  if (url_fetcher_ != NULL) {
    DVLOG(1) << "NetworkLocationRequest : Cancelling pending request";
    url_fetcher_.reset();
  }
  radio_data_ = radio_data;
  wifi_data_ = wifi_data;
  timestamp_ = timestamp;

  GURL request_url = FormRequestURL(url_.spec(), access_token,
                                    wifi_data, timestamp_);
  url_fetcher_.reset(URLFetcherImpl::Create(
      url_fetcher_id_for_tests, request_url, URLFetcherImpl::GET, this));
  url_fetcher_->SetRequestContext(url_context_);
  url_fetcher_->SetLoadFlags(
      net::LOAD_BYPASS_CACHE | net::LOAD_DISABLE_CACHE |
      net::LOAD_DO_NOT_SAVE_COOKIES | net::LOAD_DO_NOT_SEND_COOKIES |
      net::LOAD_DO_NOT_SEND_AUTH_DATA);

  url_fetcher_->Start();
  return true;
}

void NetworkLocationRequest::OnURLFetchComplete(
    const content::URLFetcher* source) {
  DCHECK_EQ(url_fetcher_.get(), source);

  net::URLRequestStatus status = source->GetStatus();
  int response_code = source->GetResponseCode();

  Geoposition position;
  string16 access_token;
  std::string data;
  source->GetResponseAsString(&data);
  GetLocationFromResponse(status.is_success(),
                          response_code,
                          data,
                          timestamp_,
                          source->GetURL(),
                          &position,
                          &access_token);
  const bool server_error =
      !status.is_success() || (response_code >= 500 && response_code < 600);
  url_fetcher_.reset();

  DCHECK(listener_);
  DVLOG(1) << "NetworkLocationRequest::Run() : Calling listener with position.";
  listener_->LocationResponseAvailable(position, server_error, access_token,
                                       radio_data_, wifi_data_);
}

// Local functions.
namespace {

struct AccessPointLess {
  bool operator()(const AccessPointData* ap1,
                  const AccessPointData* ap2) const {
    return ap2->radio_signal_strength < ap1->radio_signal_strength;
  }
};

GURL FormRequestURL(const std::string& url,
                    const string16& access_token,
                    const WifiData& wifi_data,
                    const base::Time& timestamp) {
  int age = kint32min;  // Invalid so AddInteger() will ignore.
  if (!timestamp.is_null()) {
    // Convert absolute timestamps into a relative age.
    int64 delta_ms = (base::Time::Now() - timestamp).InMilliseconds();
    if (delta_ms >= 0 && delta_ms < kint32max)
      age = static_cast<int>(delta_ms);
  }

  std::vector<std::string> params;
#if defined(GOOGLE_CHROME_BUILD)
  params.push_back("browser=googlechrome");
#else
  params.push_back("browser=chromium");
#endif

  params.push_back("sensor=true");
  if (!access_token.empty())
    params.push_back("token=" + UTF16ToUTF8(access_token));
  AddWifiData(wifi_data, age, &params);

  std::string request_string = url + '?' + JoinString(params, '&');
  if (request_string.length() > kMaxRequestLength) {
    size_t last_param_pos =
        request_string.find_last_of('&', kMaxRequestLength);
{'fraction_non_alphanumeric': 0.10324189526184539, 'fraction_numerical': 0.0071487946799667496, 'mean_word_length': 2.7738393977415305, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 37, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 22, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '369405', 'n_tokens_mistral': 3490, 'n_tokens_neox': 3377, 'n_words': 768}