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 "components/dom_distiller/core/distiller_url_fetcher.h"
6
7#include "net/http/http_status_code.h"
8#include "net/url_request/url_fetcher.h"
9#include "net/url_request/url_fetcher_delegate.h"
10#include "net/url_request/url_request_context_getter.h"
11#include "net/url_request/url_request_status.h"
12#include "url/gurl.h"
13
14using net::URLFetcher;
15
16namespace dom_distiller {
17
18DistillerURLFetcherFactory::DistillerURLFetcherFactory(
19    net::URLRequestContextGetter* context_getter)
20  : context_getter_(context_getter) {
21}
22
23DistillerURLFetcher*
24DistillerURLFetcherFactory::CreateDistillerURLFetcher() const {
25  return new DistillerURLFetcher(context_getter_);
26}
27
28
29DistillerURLFetcher::DistillerURLFetcher(
30    net::URLRequestContextGetter* context_getter)
31  : context_getter_(context_getter) {
32}
33
34DistillerURLFetcher::~DistillerURLFetcher() {
35}
36
37void DistillerURLFetcher::FetchURL(const std::string& url,
38                                   const URLFetcherCallback& callback) {
39  // Don't allow a fetch if one is pending.
40  DCHECK(!url_fetcher_ || !url_fetcher_->GetStatus().is_io_pending());
41  callback_ = callback;
42  url_fetcher_.reset(CreateURLFetcher(context_getter_, url));
43  url_fetcher_->Start();
44}
45
46URLFetcher*  DistillerURLFetcher::CreateURLFetcher(
47    net::URLRequestContextGetter* context_getter,
48    const std::string& url) {
49  net::URLFetcher* fetcher =
50      URLFetcher::Create(GURL(url), URLFetcher::GET, this);
51  fetcher->SetRequestContext(context_getter);
52  static const int kMaxRetries = 5;
53  fetcher->SetMaxRetriesOn5xx(kMaxRetries);
54  return fetcher;
55}
56
57void DistillerURLFetcher::OnURLFetchComplete(
58    const URLFetcher* source) {
59  std::string response;
60  if (source && source->GetStatus().is_success() &&
61      source->GetResponseCode() == net::HTTP_OK) {
62    // Only copy over the data if the request was successful. Insert
63    // an empty string into the proto otherwise.
64    source->GetResponseAsString(&response);
65  }
66  callback_.Run(response);
67}
68
69}  // namespace dom_distiller
70