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.
5 #include "content/browser/fileapi/upload_file_system_file_element_reader.h"
10 #include "net/base/net_errors.h"
11 #include "webkit/browser/blob/file_stream_reader.h"
12 #include "webkit/browser/fileapi/file_system_context.h"
13 #include "webkit/browser/fileapi/file_system_url.h"
17 UploadFileSystemFileElementReader::UploadFileSystemFileElementReader(
18 fileapi::FileSystemContext
* file_system_context
,
22 const base::Time
& expected_modification_time
)
23 : file_system_context_(file_system_context
),
25 range_offset_(range_offset
),
26 range_length_(range_length
),
27 expected_modification_time_(expected_modification_time
),
30 weak_ptr_factory_(this) {
33 UploadFileSystemFileElementReader::~UploadFileSystemFileElementReader() {
36 int UploadFileSystemFileElementReader::Init(
37 const net::CompletionCallback
& callback
) {
39 weak_ptr_factory_
.InvalidateWeakPtrs();
43 // Initialize the stream reader and the length.
45 file_system_context_
->CreateFileStreamReader(
46 file_system_context_
->CrackURL(url_
),
48 expected_modification_time_
);
49 DCHECK(stream_reader_
);
51 const int64 result
= stream_reader_
->GetLength(
52 base::Bind(&UploadFileSystemFileElementReader::OnGetLength
,
53 weak_ptr_factory_
.GetWeakPtr(),
56 stream_length_
= result
;
60 // The error code can be casted to int.
61 return static_cast<int>(result
);
64 uint64
UploadFileSystemFileElementReader::GetContentLength() const {
65 return std::min(stream_length_
, range_length_
);
68 uint64
UploadFileSystemFileElementReader::BytesRemaining() const {
69 return GetContentLength() - position_
;
72 int UploadFileSystemFileElementReader::Read(
75 const net::CompletionCallback
& callback
) {
76 DCHECK_LT(0, buf_length
);
77 DCHECK(stream_reader_
);
79 const uint64 num_bytes_to_read
=
80 std::min(BytesRemaining(), static_cast<uint64
>(buf_length
));
82 if (num_bytes_to_read
== 0)
85 const int result
= stream_reader_
->Read(
86 buf
, num_bytes_to_read
,
87 base::Bind(&UploadFileSystemFileElementReader::OnRead
,
88 weak_ptr_factory_
.GetWeakPtr(),
91 OnRead(net::CompletionCallback(), result
);
95 void UploadFileSystemFileElementReader::OnGetLength(
96 const net::CompletionCallback
& callback
,
99 stream_length_
= result
;
100 callback
.Run(net::OK
);
103 callback
.Run(result
);
106 void UploadFileSystemFileElementReader::OnRead(
107 const net::CompletionCallback
& callback
,
111 DCHECK_LE(position_
, GetContentLength());
113 if (!callback
.is_null())
114 callback
.Run(result
);
117 } // namespace content