1// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "components/translate/core/browser/translate_url_fetcher.h"
6
7#include "components/translate/core/browser/translate_download_manager.h"
8#include "net/base/load_flags.h"
9#include "net/http/http_status_code.h"
10#include "net/url_request/url_fetcher.h"
11#include "net/url_request/url_request_status.h"
12
13namespace translate {
14
15namespace {
16
17// Retry parameter for fetching.
18const int kMaxRetry = 16;
19
20}  // namespace
21
22TranslateURLFetcher::TranslateURLFetcher(int id) : id_(id),
23                                                   state_(IDLE),
24                                                   retry_count_(0) {
25}
26
27TranslateURLFetcher::~TranslateURLFetcher() {
28}
29
30bool TranslateURLFetcher::Request(
31    const GURL& url,
32    const TranslateURLFetcher::Callback& callback) {
33  // This function is not supposed to be called before previous operaion is not
34  // finished.
35  if (state_ == REQUESTING) {
36    NOTREACHED();
37    return false;
38  }
39
40  if (retry_count_ >= kMaxRetry)
41    return false;
42  retry_count_++;
43
44  state_ = REQUESTING;
45  url_ = url;
46  callback_ = callback;
47
48  fetcher_.reset(net::URLFetcher::Create(
49      id_,
50      url_,
51      net::URLFetcher::GET,
52      this));
53  fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
54                         net::LOAD_DO_NOT_SAVE_COOKIES);
55  fetcher_->SetRequestContext(
56      TranslateDownloadManager::GetInstance()->request_context());
57  // Set retry parameter for HTTP status code 5xx. This doesn't work against
58  // 106 (net::ERR_INTERNET_DISCONNECTED) and so on.
59  // TranslateLanguageList handles network status, and implements retry.
60  fetcher_->SetMaxRetriesOn5xx(max_retry_on_5xx_);
61  if (!extra_request_header_.empty())
62    fetcher_->SetExtraRequestHeaders(extra_request_header_);
63
64  fetcher_->Start();
65
66  return true;
67}
68
69void TranslateURLFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
70  DCHECK(fetcher_.get() == source);
71
72  std::string data;
73  if (source->GetStatus().status() == net::URLRequestStatus::SUCCESS &&
74      source->GetResponseCode() == net::HTTP_OK) {
75    state_ = COMPLETED;
76    source->GetResponseAsString(&data);
77  } else {
78    state_ = FAILED;
79  }
80
81  // Transfer URLFetcher's ownership before invoking a callback.
82  scoped_ptr<const net::URLFetcher> delete_ptr(fetcher_.release());
83  callback_.Run(id_, state_ == COMPLETED, data);
84}
85
86}  // namespace translate
87