• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 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 "chrome/browser/translate/translate_url_fetcher.h"
6 
7 #include "chrome/browser/browser_process.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 
13 namespace {
14 
15 // Retry parameter for fetching.
16 const int kMaxRetry = 16;
17 
18 }  // namespace
19 
TranslateURLFetcher(int id)20 TranslateURLFetcher::TranslateURLFetcher(int id)
21     : id_(id),
22       state_(IDLE),
23       retry_count_(0) {
24 }
25 
~TranslateURLFetcher()26 TranslateURLFetcher::~TranslateURLFetcher() {
27 }
28 
Request(const GURL & url,const TranslateURLFetcher::Callback & callback)29 bool TranslateURLFetcher::Request(
30     const GURL& url,
31     const TranslateURLFetcher::Callback& callback) {
32   // This function is not supposed to be called before previous operaion is not
33   // finished.
34   if (state_ == REQUESTING) {
35     NOTREACHED();
36     return false;
37   }
38 
39   if (retry_count_ >= kMaxRetry)
40     return false;
41   retry_count_++;
42 
43   state_ = REQUESTING;
44   url_ = url;
45   callback_ = callback;
46 
47   fetcher_.reset(net::URLFetcher::Create(
48       id_,
49       url_,
50       net::URLFetcher::GET,
51       this));
52   fetcher_->SetLoadFlags(net::LOAD_DO_NOT_SEND_COOKIES |
53                          net::LOAD_DO_NOT_SAVE_COOKIES);
54   fetcher_->SetRequestContext(g_browser_process->system_request_context());
55   // Set retry parameter for HTTP status code 5xx. This doesn't work against
56   // 106 (net::ERR_INTERNET_DISCONNECTED) and so on.
57   // TranslateLanguageList handles network status, and implements retry.
58   fetcher_->SetMaxRetriesOn5xx(max_retry_on_5xx_);
59   if (!extra_request_header_.empty())
60     fetcher_->SetExtraRequestHeaders(extra_request_header_);
61 
62   fetcher_->Start();
63 
64   return true;
65 }
66 
OnURLFetchComplete(const net::URLFetcher * source)67 void TranslateURLFetcher::OnURLFetchComplete(const net::URLFetcher* source) {
68   DCHECK(fetcher_.get() == source);
69 
70   std::string data;
71   if (source->GetStatus().status() == net::URLRequestStatus::SUCCESS &&
72       source->GetResponseCode() == net::HTTP_OK) {
73     state_ = COMPLETED;
74     source->GetResponseAsString(&data);
75   } else {
76     state_ = FAILED;
77   }
78 
79   // Transfer URLFetcher's ownership before invoking a callback.
80   scoped_ptr<const net::URLFetcher> delete_ptr(fetcher_.release());
81   callback_.Run(id_, state_ == COMPLETED, data);
82 }
83