Refactoring mojo android init_library
[chromium-blink-merge.git] / device / media_transfer_protocol / media_transfer_protocol_daemon_client.cc
blob2dddbce4c1916f45b47e8395428858712a194e14
1 // Copyright (c) 2012 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 "device/media_transfer_protocol/media_transfer_protocol_daemon_client.h"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/memory/weak_ptr.h"
11 #include "dbus/bus.h"
12 #include "dbus/message.h"
13 #include "dbus/object_path.h"
14 #include "dbus/object_proxy.h"
15 #include "device/media_transfer_protocol/mtp_file_entry.pb.h"
16 #include "device/media_transfer_protocol/mtp_storage_info.pb.h"
17 #include "third_party/cros_system_api/dbus/service_constants.h"
19 namespace device {
21 namespace {
23 const char kInvalidResponseMsg[] = "Invalid Response: ";
24 uint32 kMaxChunkSize = 1024*1024; // D-Bus has message size limits.
26 // The MediaTransferProtocolDaemonClient implementation.
27 class MediaTransferProtocolDaemonClientImpl
28 : public MediaTransferProtocolDaemonClient {
29 public:
30 explicit MediaTransferProtocolDaemonClientImpl(dbus::Bus* bus)
31 : proxy_(bus->GetObjectProxy(
32 mtpd::kMtpdServiceName,
33 dbus::ObjectPath(mtpd::kMtpdServicePath))),
34 listen_for_changes_called_(false),
35 weak_ptr_factory_(this) {
38 // MediaTransferProtocolDaemonClient override.
39 void EnumerateStorages(const EnumerateStoragesCallback& callback,
40 const ErrorCallback& error_callback) override {
41 dbus::MethodCall method_call(mtpd::kMtpdInterface,
42 mtpd::kEnumerateStorages);
43 proxy_->CallMethod(
44 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
45 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnEnumerateStorages,
46 weak_ptr_factory_.GetWeakPtr(),
47 callback,
48 error_callback));
51 // MediaTransferProtocolDaemonClient override.
52 void GetStorageInfo(const std::string& storage_name,
53 const GetStorageInfoCallback& callback,
54 const ErrorCallback& error_callback) override {
55 dbus::MethodCall method_call(mtpd::kMtpdInterface, mtpd::kGetStorageInfo);
56 dbus::MessageWriter writer(&method_call);
57 writer.AppendString(storage_name);
58 proxy_->CallMethod(
59 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
60 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnGetStorageInfo,
61 weak_ptr_factory_.GetWeakPtr(),
62 storage_name,
63 callback,
64 error_callback));
67 // MediaTransferProtocolDaemonClient override.
68 void OpenStorage(const std::string& storage_name,
69 const std::string& mode,
70 const OpenStorageCallback& callback,
71 const ErrorCallback& error_callback) override {
72 dbus::MethodCall method_call(mtpd::kMtpdInterface, mtpd::kOpenStorage);
73 dbus::MessageWriter writer(&method_call);
74 writer.AppendString(storage_name);
75 DCHECK(mode == mtpd::kReadOnlyMode || mode == mtpd::kReadWriteMode);
76 writer.AppendString(mode);
77 proxy_->CallMethod(
78 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
79 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnOpenStorage,
80 weak_ptr_factory_.GetWeakPtr(),
81 callback,
82 error_callback));
85 // MediaTransferProtocolDaemonClient override.
86 void CloseStorage(const std::string& handle,
87 const CloseStorageCallback& callback,
88 const ErrorCallback& error_callback) override {
89 dbus::MethodCall method_call(mtpd::kMtpdInterface, mtpd::kCloseStorage);
90 dbus::MessageWriter writer(&method_call);
91 writer.AppendString(handle);
92 proxy_->CallMethod(
93 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
94 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnCloseStorage,
95 weak_ptr_factory_.GetWeakPtr(),
96 callback,
97 error_callback));
100 // MediaTransferProtocolDaemonClient override.
101 void ReadDirectoryEntryIds(const std::string& handle,
102 uint32 file_id,
103 const ReadDirectoryEntryIdsCallback& callback,
104 const ErrorCallback& error_callback) override {
105 dbus::MethodCall method_call(mtpd::kMtpdInterface,
106 mtpd::kReadDirectoryEntryIds);
107 dbus::MessageWriter writer(&method_call);
108 writer.AppendString(handle);
109 writer.AppendUint32(file_id);
110 proxy_->CallMethod(
111 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
112 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnReadDirectoryIds,
113 weak_ptr_factory_.GetWeakPtr(),
114 callback,
115 error_callback));
118 void GetFileInfo(const std::string& handle,
119 const std::vector<uint32>& file_ids,
120 size_t offset,
121 size_t entries_to_read,
122 const GetFileInfoCallback& callback,
123 const ErrorCallback& error_callback) override {
124 if (offset >= file_ids.size()) {
125 error_callback.Run();
126 return;
129 dbus::MethodCall method_call(mtpd::kMtpdInterface, mtpd::kGetFileInfo);
130 dbus::MessageWriter writer(&method_call);
131 writer.AppendString(handle);
133 dbus::MessageWriter array_writer(NULL);
134 writer.OpenArray("u", &array_writer);
136 size_t end_offset = file_ids.size();
137 if (offset <= SIZE_MAX - entries_to_read)
138 end_offset = std::min(end_offset, offset + entries_to_read);
139 for (size_t i = offset; i < end_offset; ++i)
140 array_writer.AppendUint32(file_ids[i]);
142 writer.CloseContainer(&array_writer);
144 proxy_->CallMethod(
145 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
146 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnGetFileInfo,
147 weak_ptr_factory_.GetWeakPtr(),
148 callback,
149 error_callback));
152 // MediaTransferProtocolDaemonClient override.
153 void ReadFileChunk(const std::string& handle,
154 uint32 file_id,
155 uint32 offset,
156 uint32 bytes_to_read,
157 const ReadFileCallback& callback,
158 const ErrorCallback& error_callback) override {
159 DCHECK_LE(bytes_to_read, kMaxChunkSize);
160 dbus::MethodCall method_call(mtpd::kMtpdInterface, mtpd::kReadFileChunk);
161 dbus::MessageWriter writer(&method_call);
162 writer.AppendString(handle);
163 writer.AppendUint32(file_id);
164 writer.AppendUint32(offset);
165 writer.AppendUint32(bytes_to_read);
166 proxy_->CallMethod(
167 &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT,
168 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnReadFile,
169 weak_ptr_factory_.GetWeakPtr(),
170 callback,
171 error_callback));
174 void CopyFileFromLocal(const std::string& handle,
175 const int source_file_descriptor,
176 const uint32 parent_id,
177 const std::string& file_name,
178 const CopyFileFromLocalCallback& callback,
179 const ErrorCallback& error_callback) override {
180 dbus::FileDescriptor file_descriptor(source_file_descriptor);
181 file_descriptor.CheckValidity();
183 dbus::MethodCall method_call(mtpd::kMtpdInterface,
184 mtpd::kCopyFileFromLocal);
185 dbus::MessageWriter writer(&method_call);
186 writer.AppendString(handle);
187 writer.AppendFileDescriptor(file_descriptor);
188 writer.AppendUint32(parent_id);
189 writer.AppendString(file_name);
190 proxy_->CallMethod(
191 &method_call, dbus::ObjectProxy::TIMEOUT_INFINITE,
192 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnCopyFileFromLocal,
193 weak_ptr_factory_.GetWeakPtr(), callback, error_callback));
196 // MediaTransferProtocolDaemonClient override.
197 void ListenForChanges(const MTPStorageEventHandler& handler) override {
198 DCHECK(!listen_for_changes_called_);
199 listen_for_changes_called_ = true;
201 static const SignalEventTuple kSignalEventTuples[] = {
202 { mtpd::kMTPStorageAttached, true },
203 { mtpd::kMTPStorageDetached, false },
205 const size_t kNumSignalEventTuples = arraysize(kSignalEventTuples);
207 for (size_t i = 0; i < kNumSignalEventTuples; ++i) {
208 proxy_->ConnectToSignal(
209 mtpd::kMtpdInterface,
210 kSignalEventTuples[i].signal_name,
211 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnMTPStorageSignal,
212 weak_ptr_factory_.GetWeakPtr(),
213 handler,
214 kSignalEventTuples[i].is_attach),
215 base::Bind(&MediaTransferProtocolDaemonClientImpl::OnSignalConnected,
216 weak_ptr_factory_.GetWeakPtr()));
220 private:
221 // A struct to contain a pair of signal name and attachment event type.
222 // Used by SetUpConnections.
223 struct SignalEventTuple {
224 const char* signal_name;
225 bool is_attach;
228 // Handles the result of EnumerateStorages and calls |callback| or
229 // |error_callback|.
230 void OnEnumerateStorages(const EnumerateStoragesCallback& callback,
231 const ErrorCallback& error_callback,
232 dbus::Response* response) {
233 if (!response) {
234 error_callback.Run();
235 return;
237 dbus::MessageReader reader(response);
238 std::vector<std::string> storage_names;
239 if (!reader.PopArrayOfStrings(&storage_names)) {
240 LOG(ERROR) << kInvalidResponseMsg << response->ToString();
241 error_callback.Run();
242 return;
244 callback.Run(storage_names);
247 // Handles the result of GetStorageInfo and calls |callback| or
248 // |error_callback|.
249 void OnGetStorageInfo(const std::string& storage_name,
250 const GetStorageInfoCallback& callback,
251 const ErrorCallback& error_callback,
252 dbus::Response* response) {
253 if (!response) {
254 error_callback.Run();
255 return;
258 dbus::MessageReader reader(response);
259 MtpStorageInfo protobuf;
260 if (!reader.PopArrayOfBytesAsProto(&protobuf)) {
261 LOG(ERROR) << kInvalidResponseMsg << response->ToString();
262 error_callback.Run();
263 return;
265 callback.Run(protobuf);
268 // Handles the result of OpenStorage and calls |callback| or |error_callback|.
269 void OnOpenStorage(const OpenStorageCallback& callback,
270 const ErrorCallback& error_callback,
271 dbus::Response* response) {
272 if (!response) {
273 error_callback.Run();
274 return;
276 dbus::MessageReader reader(response);
277 std::string handle;
278 if (!reader.PopString(&handle)) {
279 LOG(ERROR) << kInvalidResponseMsg << response->ToString();
280 error_callback.Run();
281 return;
283 callback.Run(handle);
286 // Handles the result of CloseStorage and calls |callback| or
287 // |error_callback|.
288 void OnCloseStorage(const CloseStorageCallback& callback,
289 const ErrorCallback& error_callback,
290 dbus::Response* response) {
291 if (!response) {
292 error_callback.Run();
293 return;
295 callback.Run();
298 // Handles the result of ReadDirectoryEntryIds and calls |callback| or
299 // |error_callback|.
300 void OnReadDirectoryIds(const ReadDirectoryEntryIdsCallback& callback,
301 const ErrorCallback& error_callback,
302 dbus::Response* response) {
303 if (!response) {
304 error_callback.Run();
305 return;
308 std::vector<uint32> file_ids;
309 dbus::MessageReader reader(response);
310 dbus::MessageReader array_reader(NULL);
311 if (!reader.PopArray(&array_reader) || reader.HasMoreData()) {
312 LOG(ERROR) << kInvalidResponseMsg << response->ToString();
313 error_callback.Run();
314 return;
317 while (array_reader.HasMoreData()) {
318 uint32 file_id;
319 if (array_reader.PopUint32(&file_id)) {
320 file_ids.push_back(file_id);
321 } else {
322 LOG(ERROR) << kInvalidResponseMsg << response->ToString();
323 error_callback.Run();
324 return;
327 callback.Run(file_ids);
330 // Handles the result of GetFileInfo and calls |callback| or |error_callback|.
331 void OnGetFileInfo(const GetFileInfoCallback& callback,
332 const ErrorCallback& error_callback,
333 dbus::Response* response) {
334 if (!response) {
335 error_callback.Run();
336 return;
339 std::vector<MtpFileEntry> file_entries;
340 dbus::MessageReader reader(response);
341 MtpFileEntries entries_protobuf;
342 if (!reader.PopArrayOfBytesAsProto(&entries_protobuf)) {
343 LOG(ERROR) << kInvalidResponseMsg << response->ToString();
344 error_callback.Run();
345 return;
348 for (int i = 0; i < entries_protobuf.file_entries_size(); ++i)
349 file_entries.push_back(entries_protobuf.file_entries(i));
350 callback.Run(file_entries);
353 // Handles the result of ReadFileChunk and calls |callback| or
354 // |error_callback|.
355 void OnReadFile(const ReadFileCallback& callback,
356 const ErrorCallback& error_callback,
357 dbus::Response* response) {
358 if (!response) {
359 error_callback.Run();
360 return;
363 const uint8* data_bytes = NULL;
364 size_t data_length = 0;
365 dbus::MessageReader reader(response);
366 if (!reader.PopArrayOfBytes(&data_bytes, &data_length)) {
367 error_callback.Run();
368 return;
370 std::string data(reinterpret_cast<const char*>(data_bytes), data_length);
371 callback.Run(data);
374 void OnCopyFileFromLocal(const CopyFileFromLocalCallback& callback,
375 const ErrorCallback& error_callback,
376 dbus::Response* response) {
377 if (!response) {
378 error_callback.Run();
379 return;
382 callback.Run();
385 // Handles MTPStorageAttached/Dettached signals and calls |handler|.
386 void OnMTPStorageSignal(MTPStorageEventHandler handler,
387 bool is_attach,
388 dbus::Signal* signal) {
389 dbus::MessageReader reader(signal);
390 std::string storage_name;
391 if (!reader.PopString(&storage_name)) {
392 LOG(ERROR) << "Invalid signal: " << signal->ToString();
393 return;
395 DCHECK(!storage_name.empty());
396 handler.Run(is_attach, storage_name);
400 // Handles the result of signal connection setup.
401 void OnSignalConnected(const std::string& interface,
402 const std::string& signal,
403 bool succeeded) {
404 LOG_IF(ERROR, !succeeded) << "Connect to " << interface << " "
405 << signal << " failed.";
408 dbus::ObjectProxy* proxy_;
410 bool listen_for_changes_called_;
412 // Note: This should remain the last member so it'll be destroyed and
413 // invalidate its weak pointers before any other members are destroyed.
414 base::WeakPtrFactory<MediaTransferProtocolDaemonClientImpl> weak_ptr_factory_;
416 DISALLOW_COPY_AND_ASSIGN(MediaTransferProtocolDaemonClientImpl);
419 } // namespace
421 ////////////////////////////////////////////////////////////////////////////////
422 // MediaTransferProtocolDaemonClient
424 MediaTransferProtocolDaemonClient::MediaTransferProtocolDaemonClient() {}
426 MediaTransferProtocolDaemonClient::~MediaTransferProtocolDaemonClient() {}
428 // static
429 MediaTransferProtocolDaemonClient* MediaTransferProtocolDaemonClient::Create(
430 dbus::Bus* bus) {
431 return new MediaTransferProtocolDaemonClientImpl(bus);
434 } // namespace device