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 // Any tasks that communicates with the portable device may take >100ms to
6 // complete. Those tasks should be run on an blocking thread instead of the
9 #include "components/storage_monitor/portable_device_watcher_win.h"
12 #include <portabledevice.h>
14 #include "base/files/file_path.h"
15 #include "base/logging.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_util.h"
18 #include "base/strings/utf_string_conversions.h"
19 #include "base/threading/sequenced_worker_pool.h"
20 #include "base/win/scoped_co_mem.h"
21 #include "base/win/scoped_comptr.h"
22 #include "base/win/scoped_propvariant.h"
23 #include "components/storage_monitor/media_storage_util.h"
24 #include "components/storage_monitor/removable_device_constants.h"
25 #include "components/storage_monitor/storage_info.h"
26 #include "content/public/browser/browser_thread.h"
28 namespace storage_monitor
{
32 // Name of the client application that communicates with the MTP device.
33 const base::char16 kClientName
[] = L
"Chromium";
35 // Name of the sequenced task runner.
36 const char kMediaTaskRunnerName
[] = "media-task-runner";
38 // Returns true if |data| represents a class of portable devices.
39 bool IsPortableDeviceStructure(LPARAM data
) {
40 DEV_BROADCAST_HDR
* broadcast_hdr
=
41 reinterpret_cast<DEV_BROADCAST_HDR
*>(data
);
43 (broadcast_hdr
->dbch_devicetype
!= DBT_DEVTYP_DEVICEINTERFACE
)) {
47 GUID guidDevInterface
= GUID_NULL
;
48 if (FAILED(CLSIDFromString(kWPDDevInterfaceGUID
, &guidDevInterface
)))
50 DEV_BROADCAST_DEVICEINTERFACE
* dev_interface
=
51 reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE
*>(data
);
52 return (IsEqualGUID(dev_interface
->dbcc_classguid
, guidDevInterface
) != 0);
55 // Returns the portable device plug and play device ID string.
56 base::string16
GetPnpDeviceId(LPARAM data
) {
57 DEV_BROADCAST_DEVICEINTERFACE
* dev_interface
=
58 reinterpret_cast<DEV_BROADCAST_DEVICEINTERFACE
*>(data
);
60 return base::string16();
61 base::string16
device_id(dev_interface
->dbcc_name
);
62 DCHECK(base::IsStringASCII(device_id
));
63 return base::StringToLowerASCII(device_id
);
66 // Gets the friendly name of the device specified by the |pnp_device_id|. On
67 // success, returns true and fills in |name|.
68 bool GetFriendlyName(const base::string16
& pnp_device_id
,
69 IPortableDeviceManager
* device_manager
,
70 base::string16
* name
) {
71 DCHECK(device_manager
);
74 HRESULT hr
= device_manager
->GetDeviceFriendlyName(pnp_device_id
.c_str(),
79 hr
= device_manager
->GetDeviceFriendlyName(
80 pnp_device_id
.c_str(), WriteInto(name
, name_len
), &name_len
);
81 return (SUCCEEDED(hr
) && !name
->empty());
84 // Gets the manufacturer name of the device specified by the |pnp_device_id|.
85 // On success, returns true and fills in |name|.
86 bool GetManufacturerName(const base::string16
& pnp_device_id
,
87 IPortableDeviceManager
* device_manager
,
88 base::string16
* name
) {
89 DCHECK(device_manager
);
92 HRESULT hr
= device_manager
->GetDeviceManufacturer(pnp_device_id
.c_str(),
97 hr
= device_manager
->GetDeviceManufacturer(pnp_device_id
.c_str(),
98 WriteInto(name
, name_len
),
100 return (SUCCEEDED(hr
) && !name
->empty());
103 // Gets the description of the device specified by the |pnp_device_id|. On
104 // success, returns true and fills in |description|.
105 bool GetDeviceDescription(const base::string16
& pnp_device_id
,
106 IPortableDeviceManager
* device_manager
,
107 base::string16
* description
) {
108 DCHECK(device_manager
);
111 HRESULT hr
= device_manager
->GetDeviceDescription(pnp_device_id
.c_str(), NULL
,
116 hr
= device_manager
->GetDeviceDescription(pnp_device_id
.c_str(),
117 WriteInto(description
, desc_len
),
119 return (SUCCEEDED(hr
) && !description
->empty());
122 // On success, returns true and updates |client_info| with a reference to an
123 // IPortableDeviceValues interface that holds information about the
124 // application that communicates with the device.
125 bool GetClientInformation(
126 base::win::ScopedComPtr
<IPortableDeviceValues
>* client_info
) {
127 HRESULT hr
= client_info
->CreateInstance(__uuidof(PortableDeviceValues
),
128 NULL
, CLSCTX_INPROC_SERVER
);
130 DPLOG(ERROR
) << "Failed to create an instance of IPortableDeviceValues";
134 // Attempt to set client details.
135 (*client_info
)->SetStringValue(WPD_CLIENT_NAME
, kClientName
);
136 (*client_info
)->SetUnsignedIntegerValue(WPD_CLIENT_MAJOR_VERSION
, 0);
137 (*client_info
)->SetUnsignedIntegerValue(WPD_CLIENT_MINOR_VERSION
, 0);
138 (*client_info
)->SetUnsignedIntegerValue(WPD_CLIENT_REVISION
, 0);
139 (*client_info
)->SetUnsignedIntegerValue(
140 WPD_CLIENT_SECURITY_QUALITY_OF_SERVICE
, SECURITY_IMPERSONATION
);
141 (*client_info
)->SetUnsignedIntegerValue(WPD_CLIENT_DESIRED_ACCESS
,
146 // Opens the device for communication. |pnp_device_id| specifies the plug and
147 // play device ID string. On success, returns true and updates |device| with a
148 // reference to the portable device interface.
149 bool SetUp(const base::string16
& pnp_device_id
,
150 base::win::ScopedComPtr
<IPortableDevice
>* device
) {
151 base::win::ScopedComPtr
<IPortableDeviceValues
> client_info
;
152 if (!GetClientInformation(&client_info
))
155 HRESULT hr
= device
->CreateInstance(__uuidof(PortableDevice
), NULL
,
156 CLSCTX_INPROC_SERVER
);
158 DPLOG(ERROR
) << "Failed to create an instance of IPortableDevice";
162 hr
= (*device
)->Open(pnp_device_id
.c_str(), client_info
.get());
166 if (hr
== E_ACCESSDENIED
)
167 DPLOG(ERROR
) << "Access denied to open the device";
171 // Returns the unique id property key of the object specified by the
173 REFPROPERTYKEY
GetUniqueIdPropertyKey(const base::string16
& object_id
) {
174 return (object_id
== WPD_DEVICE_OBJECT_ID
) ?
175 WPD_DEVICE_SERIAL_NUMBER
: WPD_OBJECT_PERSISTENT_UNIQUE_ID
;
178 // On success, returns true and populates |properties_to_read| with the
179 // property key of the object specified by the |object_id|.
180 bool PopulatePropertyKeyCollection(
181 const base::string16
& object_id
,
182 base::win::ScopedComPtr
<IPortableDeviceKeyCollection
>* properties_to_read
) {
183 HRESULT hr
= properties_to_read
->CreateInstance(
184 __uuidof(PortableDeviceKeyCollection
), NULL
, CLSCTX_INPROC_SERVER
);
186 DPLOG(ERROR
) << "Failed to create IPortableDeviceKeyCollection instance";
189 REFPROPERTYKEY key
= GetUniqueIdPropertyKey(object_id
);
190 hr
= (*properties_to_read
)->Add(key
);
191 return SUCCEEDED(hr
);
194 // Wrapper function to get content property string value.
195 bool GetStringPropertyValue(IPortableDeviceValues
* properties_values
,
197 base::string16
* value
) {
198 DCHECK(properties_values
);
200 base::win::ScopedCoMem
<base::char16
> buffer
;
201 HRESULT hr
= properties_values
->GetStringValue(key
, &buffer
);
204 *value
= static_cast<const base::char16
*>(buffer
);
208 // Constructs a unique identifier for the object specified by the |object_id|.
209 // On success, returns true and fills in |unique_id|.
210 bool GetObjectUniqueId(IPortableDevice
* device
,
211 const base::string16
& object_id
,
212 base::string16
* unique_id
) {
215 base::win::ScopedComPtr
<IPortableDeviceContent
> content
;
216 HRESULT hr
= device
->Content(content
.Receive());
218 DPLOG(ERROR
) << "Failed to get IPortableDeviceContent interface";
222 base::win::ScopedComPtr
<IPortableDeviceProperties
> properties
;
223 hr
= content
->Properties(properties
.Receive());
225 DPLOG(ERROR
) << "Failed to get IPortableDeviceProperties interface";
229 base::win::ScopedComPtr
<IPortableDeviceKeyCollection
> properties_to_read
;
230 if (!PopulatePropertyKeyCollection(object_id
, &properties_to_read
))
233 base::win::ScopedComPtr
<IPortableDeviceValues
> properties_values
;
234 if (FAILED(properties
->GetValues(object_id
.c_str(),
235 properties_to_read
.get(),
236 properties_values
.Receive()))) {
240 REFPROPERTYKEY key
= GetUniqueIdPropertyKey(object_id
);
241 return GetStringPropertyValue(properties_values
.get(), key
, unique_id
);
244 // Constructs the device storage unique identifier using |device_serial_num| and
245 // |storage_id|. On success, returns true and fills in |device_storage_id|.
246 bool ConstructDeviceStorageUniqueId(const base::string16
& device_serial_num
,
247 const base::string16
& storage_id
,
248 std::string
* device_storage_id
) {
249 if (device_serial_num
.empty() && storage_id
.empty())
252 DCHECK(device_storage_id
);
253 *device_storage_id
= StorageInfo::MakeDeviceId(
254 StorageInfo::MTP_OR_PTP
,
255 base::UTF16ToUTF8(storage_id
+ L
':' + device_serial_num
));
259 // Gets a list of removable storage object identifiers present in |device|.
260 // On success, returns true and fills in |storage_object_ids|.
261 bool GetRemovableStorageObjectIds(
262 IPortableDevice
* device
,
263 PortableDeviceWatcherWin::StorageObjectIDs
* storage_object_ids
) {
265 DCHECK(storage_object_ids
);
266 base::win::ScopedComPtr
<IPortableDeviceCapabilities
> capabilities
;
267 HRESULT hr
= device
->Capabilities(capabilities
.Receive());
269 DPLOG(ERROR
) << "Failed to get IPortableDeviceCapabilities interface";
273 base::win::ScopedComPtr
<IPortableDevicePropVariantCollection
> storage_ids
;
274 hr
= capabilities
->GetFunctionalObjects(WPD_FUNCTIONAL_CATEGORY_STORAGE
,
275 storage_ids
.Receive());
277 DPLOG(ERROR
) << "Failed to get IPortableDevicePropVariantCollection";
281 DWORD num_storage_obj_ids
= 0;
282 hr
= storage_ids
->GetCount(&num_storage_obj_ids
);
286 for (DWORD index
= 0; index
< num_storage_obj_ids
; ++index
) {
287 base::win::ScopedPropVariant object_id
;
288 hr
= storage_ids
->GetAt(index
, object_id
.Receive());
289 if (SUCCEEDED(hr
) && object_id
.get().vt
== VT_LPWSTR
&&
290 object_id
.get().pwszVal
!= NULL
) {
291 storage_object_ids
->push_back(object_id
.get().pwszVal
);
297 // Returns true if the portable device belongs to a mass storage class.
298 // |pnp_device_id| specifies the plug and play device id.
299 // |device_name| specifies the name of the device.
300 bool IsMassStoragePortableDevice(const base::string16
& pnp_device_id
,
301 const base::string16
& device_name
) {
302 // Based on testing, if the pnp device id starts with "\\?\wpdbusenumroot#",
303 // then the attached device belongs to a mass storage class.
304 if (StartsWith(pnp_device_id
, L
"\\\\?\\wpdbusenumroot#", false))
307 // If the device is a volume mounted device, |device_name| will be
309 return ((device_name
.length() >= 2) && (device_name
[1] == L
':') &&
310 (((device_name
[0] >= L
'A') && (device_name
[0] <= L
'Z')) ||
311 ((device_name
[0] >= L
'a') && (device_name
[0] <= L
'z'))));
314 // Returns the name of the device specified by |pnp_device_id|.
315 base::string16
GetDeviceNameOnBlockingThread(
316 IPortableDeviceManager
* portable_device_manager
,
317 const base::string16
& pnp_device_id
) {
318 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
319 DCHECK(portable_device_manager
);
321 GetFriendlyName(pnp_device_id
, portable_device_manager
, &name
) ||
322 GetDeviceDescription(pnp_device_id
, portable_device_manager
, &name
) ||
323 GetManufacturerName(pnp_device_id
, portable_device_manager
, &name
);
327 // Access the device and gets the device storage details. On success, returns
328 // true and populates |storage_objects| with device storage details.
329 bool GetDeviceStorageObjectsOnBlockingThread(
330 const base::string16
& pnp_device_id
,
331 PortableDeviceWatcherWin::StorageObjects
* storage_objects
) {
332 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
333 DCHECK(storage_objects
);
334 base::win::ScopedComPtr
<IPortableDevice
> device
;
335 if (!SetUp(pnp_device_id
, &device
))
338 base::string16 device_serial_num
;
339 if (!GetObjectUniqueId(device
.get(), WPD_DEVICE_OBJECT_ID
,
340 &device_serial_num
)) {
344 PortableDeviceWatcherWin::StorageObjectIDs storage_obj_ids
;
345 if (!GetRemovableStorageObjectIds(device
.get(), &storage_obj_ids
))
347 for (PortableDeviceWatcherWin::StorageObjectIDs::const_iterator id_iter
=
348 storage_obj_ids
.begin(); id_iter
!= storage_obj_ids
.end(); ++id_iter
) {
349 base::string16 storage_persistent_id
;
350 if (!GetObjectUniqueId(device
.get(), *id_iter
, &storage_persistent_id
))
353 std::string device_storage_id
;
354 if (ConstructDeviceStorageUniqueId(device_serial_num
, storage_persistent_id
,
355 &device_storage_id
)) {
356 storage_objects
->push_back(PortableDeviceWatcherWin::DeviceStorageObject(
357 *id_iter
, device_storage_id
));
363 // Accesses the device and gets the device details (name, storage info, etc).
364 // On success returns true and fills in |device_details|. On failure, returns
365 // false. |pnp_device_id| specifies the plug and play device ID string.
366 bool GetDeviceInfoOnBlockingThread(
367 IPortableDeviceManager
* portable_device_manager
,
368 const base::string16
& pnp_device_id
,
369 PortableDeviceWatcherWin::DeviceDetails
* device_details
) {
370 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
371 DCHECK(portable_device_manager
);
372 DCHECK(device_details
);
373 DCHECK(!pnp_device_id
.empty());
374 device_details
->name
= GetDeviceNameOnBlockingThread(portable_device_manager
,
376 if (IsMassStoragePortableDevice(pnp_device_id
, device_details
->name
))
379 device_details
->location
= pnp_device_id
;
380 PortableDeviceWatcherWin::StorageObjects storage_objects
;
381 return GetDeviceStorageObjectsOnBlockingThread(
382 pnp_device_id
, &device_details
->storage_objects
);
385 // Wrapper function to get an instance of portable device manager. On success,
386 // returns true and fills in |portable_device_mgr|. On failure, returns false.
387 bool GetPortableDeviceManager(
388 base::win::ScopedComPtr
<IPortableDeviceManager
>* portable_device_mgr
) {
389 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
390 HRESULT hr
= portable_device_mgr
->CreateInstance(
391 __uuidof(PortableDeviceManager
), NULL
, CLSCTX_INPROC_SERVER
);
395 // Either there is no portable device support (Windows XP with old versions of
396 // Media Player) or the thread does not have COM initialized.
397 DCHECK_NE(CO_E_NOTINITIALIZED
, hr
);
401 // Enumerates the attached portable devices. On success, returns true and fills
402 // in |devices| with the attached portable device details. On failure, returns
404 bool EnumerateAttachedDevicesOnBlockingThread(
405 PortableDeviceWatcherWin::Devices
* devices
) {
406 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
408 base::win::ScopedComPtr
<IPortableDeviceManager
> portable_device_mgr
;
409 if (!GetPortableDeviceManager(&portable_device_mgr
))
412 // Get the total number of devices found on the system.
413 DWORD pnp_device_count
= 0;
414 HRESULT hr
= portable_device_mgr
->GetDevices(NULL
, &pnp_device_count
);
418 scoped_ptr
<base::char16
*[]> pnp_device_ids(
419 new base::char16
*[pnp_device_count
]);
420 hr
= portable_device_mgr
->GetDevices(pnp_device_ids
.get(), &pnp_device_count
);
424 for (DWORD index
= 0; index
< pnp_device_count
; ++index
) {
425 PortableDeviceWatcherWin::DeviceDetails device_details
;
426 if (GetDeviceInfoOnBlockingThread(portable_device_mgr
.get(),
427 pnp_device_ids
[index
], &device_details
))
428 devices
->push_back(device_details
);
429 CoTaskMemFree(pnp_device_ids
[index
]);
431 return !devices
->empty();
434 // Handles the device attach event message on a media task runner.
435 // |pnp_device_id| specifies the attached plug and play device ID string. On
436 // success, returns true and populates |device_details| with device information.
437 // On failure, returns false.
438 bool HandleDeviceAttachedEventOnBlockingThread(
439 const base::string16
& pnp_device_id
,
440 PortableDeviceWatcherWin::DeviceDetails
* device_details
) {
441 DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
442 DCHECK(device_details
);
443 base::win::ScopedComPtr
<IPortableDeviceManager
> portable_device_mgr
;
444 if (!GetPortableDeviceManager(&portable_device_mgr
))
446 // Sometimes, portable device manager doesn't have the new device details.
447 // Refresh the manager device list to update its details.
448 portable_device_mgr
->RefreshDeviceList();
449 return GetDeviceInfoOnBlockingThread(portable_device_mgr
.get(), pnp_device_id
,
453 // Registers |hwnd| to receive portable device notification details. On success,
454 // returns the device notifications handle else returns NULL.
455 HDEVNOTIFY
RegisterPortableDeviceNotification(HWND hwnd
) {
456 GUID dev_interface_guid
= GUID_NULL
;
457 HRESULT hr
= CLSIDFromString(kWPDDevInterfaceGUID
, &dev_interface_guid
);
460 DEV_BROADCAST_DEVICEINTERFACE db
= {
461 sizeof(DEV_BROADCAST_DEVICEINTERFACE
),
462 DBT_DEVTYP_DEVICEINTERFACE
,
466 return RegisterDeviceNotification(hwnd
, &db
, DEVICE_NOTIFY_WINDOW_HANDLE
);
472 // PortableDeviceWatcherWin ---------------------------------------------------
474 PortableDeviceWatcherWin::DeviceStorageObject::DeviceStorageObject(
475 const base::string16
& temporary_id
,
476 const std::string
& persistent_id
)
477 : object_temporary_id(temporary_id
),
478 object_persistent_id(persistent_id
) {
481 PortableDeviceWatcherWin::PortableDeviceWatcherWin()
482 : notifications_(NULL
),
483 storage_notifications_(NULL
),
484 weak_ptr_factory_(this) {
487 PortableDeviceWatcherWin::~PortableDeviceWatcherWin() {
488 UnregisterDeviceNotification(notifications_
);
491 void PortableDeviceWatcherWin::Init(HWND hwnd
) {
492 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
493 notifications_
= RegisterPortableDeviceNotification(hwnd
);
494 base::SequencedWorkerPool
* pool
= content::BrowserThread::GetBlockingPool();
495 media_task_runner_
= pool
->GetSequencedTaskRunnerWithShutdownBehavior(
496 pool
->GetNamedSequenceToken(kMediaTaskRunnerName
),
497 base::SequencedWorkerPool::CONTINUE_ON_SHUTDOWN
);
498 EnumerateAttachedDevices();
501 void PortableDeviceWatcherWin::OnWindowMessage(UINT event_type
, LPARAM data
) {
502 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
503 if (!IsPortableDeviceStructure(data
))
506 base::string16 device_id
= GetPnpDeviceId(data
);
507 if (event_type
== DBT_DEVICEARRIVAL
)
508 HandleDeviceAttachEvent(device_id
);
509 else if (event_type
== DBT_DEVICEREMOVECOMPLETE
)
510 HandleDeviceDetachEvent(device_id
);
513 bool PortableDeviceWatcherWin::GetMTPStorageInfoFromDeviceId(
514 const std::string
& storage_device_id
,
515 base::string16
* device_location
,
516 base::string16
* storage_object_id
) const {
517 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
518 DCHECK(device_location
);
519 DCHECK(storage_object_id
);
520 MTPStorageMap::const_iterator storage_map_iter
=
521 storage_map_
.find(storage_device_id
);
522 if (storage_map_iter
== storage_map_
.end())
525 MTPDeviceMap::const_iterator device_iter
=
526 device_map_
.find(storage_map_iter
->second
.location());
527 if (device_iter
== device_map_
.end())
529 const StorageObjects
& storage_objects
= device_iter
->second
;
530 for (StorageObjects::const_iterator storage_object_iter
=
531 storage_objects
.begin(); storage_object_iter
!= storage_objects
.end();
532 ++storage_object_iter
) {
533 if (storage_device_id
== storage_object_iter
->object_persistent_id
) {
534 *device_location
= storage_map_iter
->second
.location();
535 *storage_object_id
= storage_object_iter
->object_temporary_id
;
543 base::string16
PortableDeviceWatcherWin::GetStoragePathFromStorageId(
544 const std::string
& storage_unique_id
) {
545 // Construct a dummy device path using the storage name. This is only used
546 // for registering the device media file system.
547 DCHECK(!storage_unique_id
.empty());
548 return base::UTF8ToUTF16("\\\\" + storage_unique_id
);
551 void PortableDeviceWatcherWin::SetNotifications(
552 StorageMonitor::Receiver
* notifications
) {
553 storage_notifications_
= notifications
;
556 void PortableDeviceWatcherWin::EjectDevice(
557 const std::string
& device_id
,
558 base::Callback
<void(StorageMonitor::EjectStatus
)> callback
) {
559 // MTP devices on Windows don't have a detach API needed -- signal
560 // the object as if the device is gone and tell the caller it is OK
562 base::string16 device_location
; // The device_map_ key.
563 base::string16 storage_object_id
;
564 if (!GetMTPStorageInfoFromDeviceId(device_id
,
565 &device_location
, &storage_object_id
)) {
566 callback
.Run(StorageMonitor::EJECT_NO_SUCH_DEVICE
);
569 HandleDeviceDetachEvent(device_location
);
571 callback
.Run(StorageMonitor::EJECT_OK
);
574 void PortableDeviceWatcherWin::EnumerateAttachedDevices() {
575 DCHECK(media_task_runner_
.get());
576 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
577 Devices
* devices
= new Devices
;
578 base::PostTaskAndReplyWithResult(
579 media_task_runner_
.get(), FROM_HERE
,
580 base::Bind(&EnumerateAttachedDevicesOnBlockingThread
, devices
),
581 base::Bind(&PortableDeviceWatcherWin::OnDidEnumerateAttachedDevices
,
582 weak_ptr_factory_
.GetWeakPtr(), base::Owned(devices
)));
585 void PortableDeviceWatcherWin::OnDidEnumerateAttachedDevices(
586 const Devices
* devices
, const bool result
) {
587 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
591 for (Devices::const_iterator device_iter
= devices
->begin();
592 device_iter
!= devices
->end(); ++device_iter
) {
593 OnDidHandleDeviceAttachEvent(&(*device_iter
), result
);
597 void PortableDeviceWatcherWin::HandleDeviceAttachEvent(
598 const base::string16
& pnp_device_id
) {
599 DCHECK(media_task_runner_
.get());
600 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
601 DeviceDetails
* device_details
= new DeviceDetails
;
602 base::PostTaskAndReplyWithResult(
603 media_task_runner_
.get(), FROM_HERE
,
604 base::Bind(&HandleDeviceAttachedEventOnBlockingThread
, pnp_device_id
,
606 base::Bind(&PortableDeviceWatcherWin::OnDidHandleDeviceAttachEvent
,
607 weak_ptr_factory_
.GetWeakPtr(), base::Owned(device_details
)));
610 void PortableDeviceWatcherWin::OnDidHandleDeviceAttachEvent(
611 const DeviceDetails
* device_details
, const bool result
) {
612 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
613 DCHECK(device_details
);
617 const StorageObjects
& storage_objects
= device_details
->storage_objects
;
618 const base::string16
& name
= device_details
->name
;
619 const base::string16
& location
= device_details
->location
;
620 DCHECK(!ContainsKey(device_map_
, location
));
621 for (StorageObjects::const_iterator storage_iter
= storage_objects
.begin();
622 storage_iter
!= storage_objects
.end(); ++storage_iter
) {
623 const std::string
& storage_id
= storage_iter
->object_persistent_id
;
624 DCHECK(!ContainsKey(storage_map_
, storage_id
));
626 // Keep track of storage id and storage name to see how often we receive
628 MediaStorageUtil::RecordDeviceInfoHistogram(false, storage_id
, name
);
629 if (storage_id
.empty() || name
.empty())
632 // Device can have several data partitions. Therefore, add the
633 // partition identifier to the model name. E.g.: "Nexus 7 (s10001)"
634 base::string16
model_name(name
+ L
" (" +
635 storage_iter
->object_temporary_id
+ L
')');
636 StorageInfo
info(storage_id
, location
, base::string16(), base::string16(),
638 storage_map_
[storage_id
] = info
;
639 if (storage_notifications_
) {
640 info
.set_location(GetStoragePathFromStorageId(storage_id
));
641 storage_notifications_
->ProcessAttach(info
);
644 device_map_
[location
] = storage_objects
;
647 void PortableDeviceWatcherWin::HandleDeviceDetachEvent(
648 const base::string16
& pnp_device_id
) {
649 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
650 MTPDeviceMap::iterator device_iter
= device_map_
.find(pnp_device_id
);
651 if (device_iter
== device_map_
.end())
654 const StorageObjects
& storage_objects
= device_iter
->second
;
655 for (StorageObjects::const_iterator storage_object_iter
=
656 storage_objects
.begin(); storage_object_iter
!= storage_objects
.end();
657 ++storage_object_iter
) {
658 std::string storage_id
= storage_object_iter
->object_persistent_id
;
659 MTPStorageMap::iterator storage_map_iter
= storage_map_
.find(storage_id
);
660 DCHECK(storage_map_iter
!= storage_map_
.end());
661 if (storage_notifications_
) {
662 storage_notifications_
->ProcessDetach(
663 storage_map_iter
->second
.device_id());
665 storage_map_
.erase(storage_map_iter
);
667 device_map_
.erase(device_iter
);
670 } // namespace storage_monitor