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.
5 #include "chrome/browser/extensions/blob_reader.h"
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/http/http_response_headers.h"
14 #include "net/url_request/url_fetcher.h"
15 #include "net/url_request/url_request_context.h"
16 #include "net/url_request/url_request_context_getter.h"
18 BlobReader::BlobReader(Profile
* profile
,
19 const std::string
& blob_uuid
,
20 BlobReadCallback callback
)
21 : callback_(callback
) {
22 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
24 if (base::StartsWith(blob_uuid
, "blob:blobinternal",
25 base::CompareCase::SENSITIVE
)) {
26 // TODO(michaeln): remove support for deprecated blob urls
27 blob_url
= GURL(blob_uuid
);
29 blob_url
= GURL(std::string("blob:uuid/") + blob_uuid
);
31 DCHECK(blob_url
.is_valid());
32 fetcher_
= net::URLFetcher::Create(blob_url
, net::URLFetcher::GET
, this);
33 fetcher_
->SetRequestContext(profile
->GetRequestContext());
36 BlobReader::~BlobReader() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI
); }
38 void BlobReader::SetByteRange(int64 offset
, int64 length
) {
39 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
42 CHECK_LE(offset
, kint64max
- length
);
44 net::HttpRequestHeaders headers
;
46 net::HttpRequestHeaders::kRange
,
47 base::StringPrintf("bytes=%" PRId64
"-%" PRId64
, offset
,
48 offset
+ length
- 1));
49 fetcher_
->SetExtraRequestHeaders(headers
.ToString());
52 void BlobReader::Start() {
53 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
57 // Overridden from net::URLFetcherDelegate.
58 void BlobReader::OnURLFetchComplete(const net::URLFetcher
* source
) {
59 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
60 scoped_ptr
<std::string
> response(new std::string
);
61 int64 first
= 0, last
= 0, length
= 0;
62 source
->GetResponseAsString(response
.get());
63 source
->GetResponseHeaders()->GetContentRange(&first
, &last
, &length
);
64 callback_
.Run(response
.Pass(), length
);