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/extensions/blob_reader.h"
6
7#include "base/format_macros.h"
8#include "base/strings/string_util.h"
9#include "base/strings/stringprintf.h"
10#include "chrome/browser/profiles/profile.h"
11#include "content/public/browser/browser_thread.h"
12#include "net/http/http_request_headers.h"
13#include "net/url_request/url_fetcher.h"
14#include "net/url_request/url_request_context.h"
15#include "net/url_request/url_request_context_getter.h"
16
17BlobReader::BlobReader(Profile* profile,
18                       const std::string& blob_uuid,
19                       BlobReadCallback callback)
20    : callback_(callback) {
21  GURL blob_url;
22  if (StartsWithASCII(blob_uuid, "blob:blobinternal", true)) {
23    // TODO(michaeln): remove support for deprecated blob urls
24    blob_url = GURL(blob_uuid);
25  } else {
26    blob_url = GURL(std::string("blob:uuid/") + blob_uuid);
27  }
28  DCHECK(blob_url.is_valid());
29  fetcher_.reset(net::URLFetcher::Create(
30      blob_url, net::URLFetcher::GET,
31      this));
32  fetcher_->SetRequestContext(profile->GetRequestContext());
33}
34
35BlobReader::~BlobReader() {
36}
37
38void BlobReader::SetByteRange(int64 offset, int64 length) {
39  CHECK_GE(offset, 0);
40  CHECK_GT(length, 0);
41  CHECK_LE(offset, kint64max - length);
42
43  net::HttpRequestHeaders headers;
44  headers.SetHeader(
45      net::HttpRequestHeaders::kRange,
46      base::StringPrintf("bytes=%" PRId64 "-%" PRId64, offset,
47                         offset + length - 1));
48  fetcher_->SetExtraRequestHeaders(headers.ToString());
49}
50
51void BlobReader::Start() {
52  fetcher_->Start();
53}
54
55// Overridden from net::URLFetcherDelegate.
56void BlobReader::OnURLFetchComplete(const net::URLFetcher* source) {
57  scoped_ptr<std::string> response(new std::string);
58  source->GetResponseAsString(response.get());
59  callback_.Run(response.Pass());
60
61  delete this;
62}
63